forked from 1jehuang/jcode
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcomm_session.rs
More file actions
957 lines (900 loc) · 31.5 KB
/
comm_session.rs
File metadata and controls
957 lines (900 loc) · 31.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
use super::client_lifecycle::process_message_streaming_mpsc;
use super::swarm_mutation_state::{
PersistedSwarmMutationResponse, SwarmMutationRuntime, begin_or_replay, finish_request,
request_key,
};
use super::{
SessionInterruptQueues, SwarmEvent, SwarmEventType, SwarmMember, SwarmState, VersionedPlan,
append_swarm_completion_report_instructions, broadcast_swarm_plan, broadcast_swarm_status,
create_headless_session, fanout_session_event, persist_swarm_state_for, record_swarm_event,
record_swarm_event_for_session, remove_session_channel_subscriptions,
remove_session_from_swarm, remove_session_interrupt_queue, truncate_detail,
update_member_status, update_member_status_with_report,
};
use crate::agent::Agent;
use crate::protocol::{NotificationType, ServerEvent};
use crate::provider::Provider;
use crate::session::Session;
use std::collections::{HashMap, HashSet};
use std::path::PathBuf;
use std::sync::Arc;
use std::time::Instant;
use tokio::sync::{Mutex, RwLock, broadcast, mpsc};
type SessionAgents = Arc<RwLock<HashMap<String, Arc<Mutex<Agent>>>>>;
type ChannelSubscriptions = Arc<RwLock<HashMap<String, HashMap<String, HashSet<String>>>>>;
fn create_visible_spawn_session(
working_dir: Option<&str>,
model_override: Option<&str>,
selfdev_requested: bool,
) -> anyhow::Result<(String, PathBuf)> {
let cwd = working_dir
.map(PathBuf::from)
.unwrap_or_else(|| std::env::current_dir().unwrap_or_else(|_| PathBuf::from(".")));
let mut session = Session::create(None, None);
session.working_dir = Some(cwd.display().to_string());
if let Some(model) = model_override {
session.model = Some(model.to_string());
}
if selfdev_requested {
session.set_canary("self-dev");
}
session.save()?;
Ok((session.id.clone(), cwd))
}
async fn resolve_spawn_working_dir(
requested_working_dir: Option<String>,
req_session_id: &str,
sessions: &SessionAgents,
swarm_members: &Arc<RwLock<HashMap<String, SwarmMember>>>,
) -> Option<String> {
if requested_working_dir
.as_deref()
.is_some_and(|dir| !dir.trim().is_empty())
{
return requested_working_dir;
}
if let Some(agent_dir) = {
let agent_sessions = sessions.read().await;
agent_sessions.get(req_session_id).and_then(|agent| {
agent
.try_lock()
.ok()
.and_then(|agent_guard| agent_guard.working_dir().map(str::to_string))
})
} {
if !agent_dir.trim().is_empty() {
return Some(agent_dir);
}
}
swarm_members
.read()
.await
.get(req_session_id)
.and_then(|member| member.working_dir.as_ref())
.map(|dir| dir.display().to_string())
.filter(|dir| !dir.trim().is_empty())
}
fn spawn_visible_session_window(
session_id: &str,
cwd: &std::path::Path,
selfdev_requested: bool,
) -> anyhow::Result<bool> {
let exe = crate::build::client_update_candidate(selfdev_requested)
.map(|(path, _label)| path)
.or_else(|| std::env::current_exe().ok())
.unwrap_or_else(|| PathBuf::from("jcode"));
if selfdev_requested {
crate::cli::tui_launch::spawn_selfdev_in_new_terminal(&exe, session_id, cwd)
} else {
crate::cli::tui_launch::spawn_resume_in_new_terminal(&exe, session_id, cwd)
}
}
fn persist_headed_startup_message(session_id: &str, message: &str) {
crate::tui::App::save_startup_submission_for_session(
session_id,
message.to_string(),
Vec::new(),
);
}
fn clear_headed_startup_message(session_id: &str) {
if let Ok(jcode_dir) = crate::storage::jcode_dir() {
let path = jcode_dir.join(format!("client-input-{}", session_id));
let _ = std::fs::remove_file(path);
}
}
fn cleanup_prepared_visible_spawn_session(session_id: &str) {
clear_headed_startup_message(session_id);
if let Ok(path) = crate::session::session_path(session_id) {
let _ = std::fs::remove_file(path);
}
if let Ok(path) = crate::session::session_journal_path(session_id) {
let _ = std::fs::remove_file(path);
}
}
fn prepare_visible_spawn_session<F>(
working_dir: Option<&str>,
model_override: Option<&str>,
selfdev_requested: bool,
startup_message: Option<&str>,
launch_visible: F,
) -> anyhow::Result<(String, bool)>
where
F: FnOnce(&str, &std::path::Path, bool) -> anyhow::Result<bool>,
{
let (new_session_id, cwd) =
create_visible_spawn_session(working_dir, model_override, selfdev_requested)?;
if let Some(message) = startup_message {
persist_headed_startup_message(&new_session_id, message);
}
match launch_visible(&new_session_id, &cwd, selfdev_requested) {
Ok(launched) => {
if !launched {
cleanup_prepared_visible_spawn_session(&new_session_id);
}
Ok((new_session_id, launched))
}
Err(error) => {
cleanup_prepared_visible_spawn_session(&new_session_id);
Err(error)
}
}
}
#[expect(
clippy::too_many_arguments,
reason = "visible spawn registration updates swarm state, event history, and UI delivery metadata together"
)]
async fn register_visible_spawned_member(
session_id: &str,
swarm_id: &str,
working_dir: Option<&str>,
has_startup_message: bool,
report_back_to_session_id: Option<&str>,
swarm_members: &Arc<RwLock<HashMap<String, SwarmMember>>>,
swarms_by_id: &Arc<RwLock<HashMap<String, HashSet<String>>>>,
event_history: &Arc<RwLock<std::collections::VecDeque<SwarmEvent>>>,
event_counter: &Arc<std::sync::atomic::AtomicU64>,
swarm_event_tx: &broadcast::Sender<SwarmEvent>,
) {
let (event_tx, _event_rx) = mpsc::unbounded_channel();
let now = Instant::now();
let friendly_name = crate::id::extract_session_name(session_id)
.map(|name| name.to_string())
.unwrap_or_else(|| session_id.to_string());
let (status, detail) = if has_startup_message {
("running".to_string(), Some("startup queued".to_string()))
} else {
("spawned".to_string(), Some("launching client".to_string()))
};
{
let mut members = swarm_members.write().await;
members.insert(
session_id.to_string(),
SwarmMember {
session_id: session_id.to_string(),
event_tx,
event_txs: HashMap::new(),
working_dir: working_dir.map(PathBuf::from),
swarm_id: Some(swarm_id.to_string()),
swarm_enabled: true,
status,
detail,
friendly_name: Some(friendly_name),
report_back_to_session_id: report_back_to_session_id.map(str::to_string),
latest_completion_report: None,
role: "agent".to_string(),
joined_at: now,
last_status_change: now,
is_headless: false,
},
);
}
{
let mut swarms = swarms_by_id.write().await;
swarms
.entry(swarm_id.to_string())
.or_insert_with(HashSet::new)
.insert(session_id.to_string());
}
record_swarm_event_for_session(
session_id,
SwarmEventType::MemberChange {
action: "joined".to_string(),
},
swarm_members,
event_history,
event_counter,
swarm_event_tx,
)
.await;
broadcast_swarm_status(swarm_id, swarm_members, swarms_by_id).await;
}
#[expect(
clippy::too_many_arguments,
reason = "server-side swarm spawning needs session, swarm state, provider, and event sinks together"
)]
pub(super) async fn spawn_swarm_agent(
req_session_id: &str,
swarm_id: &str,
working_dir: Option<String>,
initial_message: Option<String>,
sessions: &SessionAgents,
global_session_id: &Arc<RwLock<String>>,
provider_template: &Arc<dyn Provider>,
swarm_members: &Arc<RwLock<HashMap<String, SwarmMember>>>,
swarms_by_id: &Arc<RwLock<HashMap<String, HashSet<String>>>>,
swarm_coordinators: &Arc<RwLock<HashMap<String, String>>>,
swarm_plans: &Arc<RwLock<HashMap<String, VersionedPlan>>>,
event_history: &Arc<RwLock<std::collections::VecDeque<SwarmEvent>>>,
event_counter: &Arc<std::sync::atomic::AtomicU64>,
swarm_event_tx: &broadcast::Sender<SwarmEvent>,
mcp_pool: &Arc<crate::mcp::SharedMcpPool>,
soft_interrupt_queues: &SessionInterruptQueues,
) -> anyhow::Result<String> {
let resolved_working_dir =
resolve_spawn_working_dir(working_dir, req_session_id, sessions, swarm_members).await;
let coordinator_model = {
let agent_sessions = sessions.read().await;
agent_sessions.get(req_session_id).and_then(|agent| {
agent
.try_lock()
.ok()
.map(|agent_guard| agent_guard.provider_model())
})
};
let spawn_model = crate::config::config()
.agents
.swarm_model
.clone()
.or(coordinator_model.clone());
let coordinator_is_canary = {
let agent_sessions = sessions.read().await;
agent_sessions
.get(req_session_id)
.and_then(|agent| {
agent
.try_lock()
.ok()
.map(|agent_guard| agent_guard.is_canary())
})
.unwrap_or(false)
};
let startup_message = initial_message
.as_deref()
.map(append_swarm_completion_report_instructions);
let visible_spawn = prepare_visible_spawn_session(
resolved_working_dir.as_deref(),
spawn_model.as_deref(),
coordinator_is_canary,
startup_message.as_deref(),
spawn_visible_session_window,
);
let (new_session_id, is_headless_fallback) = match visible_spawn {
Ok((new_session_id, true)) => Ok((new_session_id, false)),
Ok((_, false)) | Err(_) => {
let cmd = if let Some(ref dir) = resolved_working_dir {
format!("create_session:{dir}")
} else {
"create_session".to_string()
};
create_headless_session(
sessions,
global_session_id,
provider_template,
&cmd,
swarm_members,
swarms_by_id,
swarm_coordinators,
swarm_plans,
soft_interrupt_queues,
coordinator_is_canary,
spawn_model.clone(),
Some(Arc::clone(mcp_pool)),
Some(req_session_id.to_string()),
)
.await
.and_then(|result_json| {
serde_json::from_str::<serde_json::Value>(&result_json)
.ok()
.and_then(|value| {
value
.get("session_id")
.and_then(|session_id| session_id.as_str())
.map(|session_id| session_id.to_string())
})
.map(|session_id| (session_id, true))
.ok_or_else(|| anyhow::anyhow!("Failed to parse spawned session id"))
})
}
}?;
let startup_message = startup_message.clone();
{
let mut plans = swarm_plans.write().await;
if let Some(plan) = plans.get_mut(swarm_id)
&& (!plan.items.is_empty() || !plan.participants.is_empty())
{
plan.participants.insert(req_session_id.to_string());
plan.participants.insert(new_session_id.clone());
}
}
broadcast_swarm_plan(
swarm_id,
Some("participant_spawned".to_string()),
swarm_plans,
swarm_members,
swarms_by_id,
)
.await;
if !is_headless_fallback {
register_visible_spawned_member(
&new_session_id,
swarm_id,
resolved_working_dir.as_deref(),
startup_message.is_some(),
Some(req_session_id),
swarm_members,
swarms_by_id,
event_history,
event_counter,
swarm_event_tx,
)
.await;
}
let swarm_state = SwarmState {
members: Arc::clone(swarm_members),
swarms_by_id: Arc::clone(swarms_by_id),
plans: Arc::clone(swarm_plans),
coordinators: Arc::clone(swarm_coordinators),
};
persist_swarm_state_for(swarm_id, &swarm_state).await;
if let Some(initial_msg) = startup_message
&& is_headless_fallback
{
record_swarm_event_for_session(
&new_session_id,
SwarmEventType::MemberChange {
action: "joined".to_string(),
},
swarm_members,
event_history,
event_counter,
swarm_event_tx,
)
.await;
let agent_arc = {
let agent_sessions = sessions.read().await;
agent_sessions.get(&new_session_id).cloned()
};
if let Some(agent_arc) = agent_arc {
let sid_clone = new_session_id.clone();
let swarm_members2 = Arc::clone(swarm_members);
let swarms_by_id2 = Arc::clone(swarms_by_id);
let event_history2 = Arc::clone(event_history);
let event_counter2 = Arc::clone(event_counter);
let swarm_event_tx2 = swarm_event_tx.clone();
tokio::spawn(async move {
update_member_status(
&sid_clone,
"running",
Some(truncate_detail(&initial_msg, 120)),
&swarm_members2,
&swarms_by_id2,
Some(&event_history2),
Some(&event_counter2),
Some(&swarm_event_tx2),
)
.await;
let event_tx = super::session_event_fanout_sender(
sid_clone.clone(),
Arc::clone(&swarm_members2),
);
let start_message_index = {
let agent = agent_arc.lock().await;
agent.message_count()
};
let result = process_message_streaming_mpsc(
Arc::clone(&agent_arc),
&initial_msg,
vec![],
None,
event_tx,
)
.await;
let completion_report = if result.is_ok() {
let agent = agent_arc.lock().await;
agent.latest_assistant_text_after(start_message_index)
} else {
None
};
let (new_status, new_detail) = match result {
Ok(()) => ("ready", None),
Err(ref error) => ("failed", Some(truncate_detail(&error.to_string(), 120))),
};
update_member_status_with_report(
&sid_clone,
new_status,
new_detail,
completion_report,
&swarm_members2,
&swarms_by_id2,
Some(&event_history2),
Some(&event_counter2),
Some(&swarm_event_tx2),
)
.await;
});
}
}
Ok(new_session_id)
}
#[allow(clippy::too_many_arguments)]
pub(super) async fn handle_comm_spawn(
id: u64,
req_session_id: String,
working_dir: Option<String>,
initial_message: Option<String>,
request_nonce: Option<String>,
client_event_tx: &mpsc::UnboundedSender<ServerEvent>,
sessions: &SessionAgents,
global_session_id: &Arc<RwLock<String>>,
provider_template: &Arc<dyn Provider>,
swarm_members: &Arc<RwLock<HashMap<String, SwarmMember>>>,
swarms_by_id: &Arc<RwLock<HashMap<String, HashSet<String>>>>,
swarm_coordinators: &Arc<RwLock<HashMap<String, String>>>,
swarm_plans: &Arc<RwLock<HashMap<String, VersionedPlan>>>,
_channel_subscriptions: &ChannelSubscriptions,
_channel_subscriptions_by_session: &ChannelSubscriptions,
event_history: &Arc<RwLock<std::collections::VecDeque<SwarmEvent>>>,
event_counter: &Arc<std::sync::atomic::AtomicU64>,
swarm_event_tx: &broadcast::Sender<SwarmEvent>,
mcp_pool: &Arc<crate::mcp::SharedMcpPool>,
soft_interrupt_queues: &SessionInterruptQueues,
swarm_mutation_runtime: &SwarmMutationRuntime,
) {
let swarm_id = match ensure_spawn_coordinator_swarm(
id,
&req_session_id,
"Only the coordinator can spawn new agents. Assign the current session as coordinator first, e.g. swarm assign_role target_session=current role=coordinator.",
client_event_tx,
swarm_members,
swarms_by_id,
swarm_coordinators,
swarm_plans,
)
.await
{
Some(swarm_id) => swarm_id,
None => return,
};
let mutation_key = request_key(
&req_session_id,
"spawn",
&[
swarm_id.clone(),
working_dir.clone().unwrap_or_default(),
initial_message.clone().unwrap_or_default(),
request_nonce.clone().unwrap_or_default(),
],
);
let Some(mutation_state) = begin_or_replay(
swarm_mutation_runtime,
&mutation_key,
"spawn",
&req_session_id,
id,
client_event_tx,
)
.await
else {
return;
};
let response = match spawn_swarm_agent(
&req_session_id,
&swarm_id,
working_dir,
initial_message,
sessions,
global_session_id,
provider_template,
swarm_members,
swarms_by_id,
swarm_coordinators,
swarm_plans,
event_history,
event_counter,
swarm_event_tx,
mcp_pool,
soft_interrupt_queues,
)
.await
{
Ok(new_session_id) => PersistedSwarmMutationResponse::Spawn { new_session_id },
Err(error) => PersistedSwarmMutationResponse::Error {
message: format!("Failed to spawn agent: {error}"),
retry_after_secs: None,
},
};
finish_request(swarm_mutation_runtime, &mutation_state, response).await;
}
#[allow(clippy::too_many_arguments)]
pub(super) async fn handle_comm_stop(
id: u64,
req_session_id: String,
target_session: String,
force: bool,
client_event_tx: &mpsc::UnboundedSender<ServerEvent>,
sessions: &SessionAgents,
swarm_members: &Arc<RwLock<HashMap<String, SwarmMember>>>,
swarms_by_id: &Arc<RwLock<HashMap<String, HashSet<String>>>>,
swarm_coordinators: &Arc<RwLock<HashMap<String, String>>>,
swarm_plans: &Arc<RwLock<HashMap<String, VersionedPlan>>>,
channel_subscriptions: &ChannelSubscriptions,
channel_subscriptions_by_session: &ChannelSubscriptions,
event_history: &Arc<RwLock<std::collections::VecDeque<SwarmEvent>>>,
event_counter: &Arc<std::sync::atomic::AtomicU64>,
swarm_event_tx: &broadcast::Sender<SwarmEvent>,
soft_interrupt_queues: &SessionInterruptQueues,
swarm_mutation_runtime: &SwarmMutationRuntime,
) {
let swarm_id = if let Some(swarm_id) = require_coordinator_swarm(
id,
&req_session_id,
"Only the coordinator can stop agents.",
client_event_tx,
swarm_members,
swarm_coordinators,
)
.await
{
swarm_id
} else {
return;
};
let target_session =
match resolve_stop_target_session(&swarm_id, &target_session, swarm_members).await {
Ok(target_session) => target_session,
Err(message) => {
let _ = client_event_tx.send(ServerEvent::Error {
id,
message,
retry_after_secs: None,
});
return;
}
};
let stop_allowed = {
let members = swarm_members.read().await;
members
.get(&target_session)
.map(|member| swarm_stop_allowed_by_owner(&req_session_id, member, force))
.unwrap_or(false)
};
if !stop_allowed {
let _ = client_event_tx.send(ServerEvent::Error {
id,
message: format!(
"Refusing to stop session '{target_session}' because it was not spawned by this coordinator. Pass force=true to stop a non-owned/user-created swarm session explicitly."
),
retry_after_secs: None,
});
return;
}
let _ = fanout_session_event(
swarm_members,
&target_session,
ServerEvent::SessionCloseRequested {
reason: format!("Stopped by coordinator {req_session_id}"),
},
)
.await;
let mutation_key = request_key(&req_session_id, "stop", &[swarm_id, target_session.clone()]);
let Some(mutation_state) = begin_or_replay(
swarm_mutation_runtime,
&mutation_key,
"stop",
&req_session_id,
id,
client_event_tx,
)
.await
else {
return;
};
let mut sessions_guard = sessions.write().await;
let removed_agent = sessions_guard.remove(&target_session);
let removed_live_agent = removed_agent.is_some();
drop(sessions_guard);
if let Some(agent_arc) = removed_agent {
remove_session_interrupt_queue(soft_interrupt_queues, &target_session).await;
if let Ok(agent) = agent_arc.try_lock() {
let memory_enabled = agent.memory_enabled();
let transcript = if memory_enabled {
Some(agent.build_transcript_for_extraction())
} else {
None
};
let sid = target_session.clone();
let working_dir = agent.working_dir().map(|dir| dir.to_string());
drop(agent);
if let Some(transcript) = transcript {
crate::memory_agent::trigger_final_extraction_with_dir(
transcript,
sid,
working_dir,
);
}
}
}
let (removed_swarm_id, removed_name) = {
let mut members = swarm_members.write().await;
if let Some(member) = members.remove(&target_session) {
(member.swarm_id, member.friendly_name)
} else {
(None, None)
}
};
if let Some(ref swarm_id) = removed_swarm_id {
record_swarm_event(
event_history,
event_counter,
swarm_event_tx,
target_session.clone(),
removed_name.clone(),
Some(swarm_id.clone()),
SwarmEventType::MemberChange {
action: "left".to_string(),
},
)
.await;
remove_session_from_swarm(
&target_session,
swarm_id,
swarm_members,
swarms_by_id,
swarm_coordinators,
swarm_plans,
)
.await;
}
remove_session_channel_subscriptions(
&target_session,
channel_subscriptions,
channel_subscriptions_by_session,
)
.await;
let response = if removed_live_agent || removed_swarm_id.is_some() {
PersistedSwarmMutationResponse::Done
} else {
PersistedSwarmMutationResponse::Error {
message: format!("Unknown session '{target_session}'"),
retry_after_secs: None,
}
};
finish_request(swarm_mutation_runtime, &mutation_state, response).await;
}
fn swarm_stop_allowed_by_owner(
req_session_id: &str,
target_member: &SwarmMember,
force: bool,
) -> bool {
force || target_member.report_back_to_session_id.as_deref() == Some(req_session_id)
}
async fn resolve_stop_target_session(
swarm_id: &str,
target: &str,
swarm_members: &Arc<RwLock<HashMap<String, SwarmMember>>>,
) -> std::result::Result<String, String> {
let target = target.trim();
if target.is_empty() {
return Err("target_session is required.".to_string());
}
let members = swarm_members.read().await;
if members
.get(target)
.is_some_and(|member| member.swarm_id.as_deref() == Some(swarm_id))
{
return Ok(target.to_string());
}
let mut matches = members
.iter()
.filter(|(_, member)| member.swarm_id.as_deref() == Some(swarm_id))
.filter(|(session_id, member)| {
member.friendly_name.as_deref() == Some(target)
|| session_id.starts_with(target)
|| session_id.ends_with(target)
})
.map(|(session_id, member)| {
(
session_id.clone(),
member
.friendly_name
.as_deref()
.unwrap_or(session_id)
.to_string(),
)
})
.collect::<Vec<_>>();
matches.sort_by(|a, b| a.0.cmp(&b.0));
match matches.len() {
0 => Err(format!(
"Unknown swarm session '{target}'. Use an exact session ID, unique friendly name, or unique session ID prefix/suffix."
)),
1 => Ok(matches.remove(0).0),
_ => Err(format!(
"Ambiguous swarm session '{target}' matched: {}. Use an exact session ID.",
matches
.iter()
.map(|(session_id, friendly)| format!("{friendly} [{session_id}]"))
.collect::<Vec<_>>()
.join(", ")
)),
}
}
fn swarm_member_status_is_stale_for_coordination(status: &str) -> bool {
matches!(
status,
"crashed" | "failed" | "stopped" | "closed" | "disconnected"
)
}
#[expect(
clippy::too_many_arguments,
reason = "spawn coordinator resolution checks swarm membership, coordinator state, and promotion side effects together"
)]
async fn ensure_spawn_coordinator_swarm(
id: u64,
req_session_id: &str,
permission_error: &str,
client_event_tx: &mpsc::UnboundedSender<ServerEvent>,
swarm_members: &Arc<RwLock<HashMap<String, SwarmMember>>>,
swarms_by_id: &Arc<RwLock<HashMap<String, HashSet<String>>>>,
swarm_coordinators: &Arc<RwLock<HashMap<String, String>>>,
swarm_plans: &Arc<RwLock<HashMap<String, VersionedPlan>>>,
) -> Option<String> {
let (swarm_id, from_name, coordinator_id, coordinator_is_stale) = {
let members = swarm_members.read().await;
let swarm_id = members
.get(req_session_id)
.and_then(|member| member.swarm_id.clone());
let from_name = members
.get(req_session_id)
.and_then(|member| member.friendly_name.clone());
let coordinator_id = if let Some(ref swarm_id) = swarm_id {
let coordinators = swarm_coordinators.read().await;
coordinators.get(swarm_id).cloned()
} else {
None
};
let coordinator_is_stale = coordinator_id.as_ref().is_some_and(|coordinator| {
!members.get(coordinator).is_some_and(|member| {
member.swarm_id.as_deref() == swarm_id.as_deref()
&& !swarm_member_status_is_stale_for_coordination(&member.status)
})
});
(swarm_id, from_name, coordinator_id, coordinator_is_stale)
};
let Some(swarm_id) = swarm_id else {
let _ = client_event_tx.send(ServerEvent::Error {
id,
message: "Not in a swarm.".to_string(),
retry_after_secs: None,
});
return None;
};
if coordinator_id.as_deref() == Some(req_session_id) {
return Some(swarm_id);
}
if coordinator_id.is_some() && !coordinator_is_stale {
let _ = client_event_tx.send(ServerEvent::Error {
id,
message: permission_error.to_string(),
retry_after_secs: None,
});
return None;
}
let promoted = {
let mut coordinators = swarm_coordinators.write().await;
match coordinators.get(&swarm_id) {
Some(existing) if existing == req_session_id => false,
Some(_) if !coordinator_is_stale => {
let _ = client_event_tx.send(ServerEvent::Error {
id,
message: permission_error.to_string(),
retry_after_secs: None,
});
return None;
}
_ => {
coordinators.insert(swarm_id.clone(), req_session_id.to_string());
true
}
}
};
if promoted {
{
let mut members = swarm_members.write().await;
if let Some(member) = members.get_mut(req_session_id) {
member.role = "coordinator".to_string();
}
}
let swarm_state = SwarmState {
members: Arc::clone(swarm_members),
swarms_by_id: Arc::clone(swarms_by_id),
plans: Arc::clone(swarm_plans),
coordinators: Arc::clone(swarm_coordinators),
};
persist_swarm_state_for(&swarm_id, &swarm_state).await;
broadcast_swarm_status(&swarm_id, swarm_members, swarms_by_id).await;
let _ = client_event_tx.send(ServerEvent::Notification {
from_session: req_session_id.to_string(),
from_name,
notification_type: NotificationType::Message {
scope: Some("swarm".to_string()),
channel: None,
},
message: "You are the coordinator for this swarm.".to_string(),
});
}
Some(swarm_id)
}
async fn require_coordinator_swarm(
id: u64,
req_session_id: &str,
permission_error: &str,
client_event_tx: &mpsc::UnboundedSender<ServerEvent>,
swarm_members: &Arc<RwLock<HashMap<String, SwarmMember>>>,
swarm_coordinators: &Arc<RwLock<HashMap<String, String>>>,
) -> Option<String> {
let (swarm_id, is_coordinator, coordinator_is_stale) = {
let members = swarm_members.read().await;
let swarm_id = members
.get(req_session_id)
.and_then(|member| member.swarm_id.clone());
let coordinator_id = if let Some(ref swarm_id) = swarm_id {
let coordinators = swarm_coordinators.read().await;
coordinators.get(swarm_id).cloned()
} else {
None
};
let is_coordinator = coordinator_id.as_deref() == Some(req_session_id);
let coordinator_is_stale = coordinator_id.as_ref().is_some_and(|coordinator| {
!members.get(coordinator).is_some_and(|member| {
member.swarm_id.as_deref() == swarm_id.as_deref()
&& !swarm_member_status_is_stale_for_coordination(&member.status)
})
});
(swarm_id, is_coordinator, coordinator_is_stale)
};
if !is_coordinator && coordinator_is_stale {
if let Some(ref swarm_id) = swarm_id {
let mut coordinators = swarm_coordinators.write().await;
coordinators.insert(swarm_id.clone(), req_session_id.to_string());
drop(coordinators);
let mut members = swarm_members.write().await;
if let Some(member) = members.get_mut(req_session_id) {
member.role = "coordinator".to_string();
}
return Some(swarm_id.clone());
};
}
if !is_coordinator {
let _ = client_event_tx.send(ServerEvent::Error {
id,
message: permission_error.to_string(),
retry_after_secs: None,
});
return None;
}
match swarm_id {
Some(swarm_id) => Some(swarm_id),
None => {
let _ = client_event_tx.send(ServerEvent::Error {
id,
message: "Not in a swarm.".to_string(),
retry_after_secs: None,
});
None
}
}
}
#[cfg(test)]
#[path = "comm_session_tests.rs"]
mod comm_session_tests;