1use std::collections::HashSet;
2use std::ops::Deref;
3use std::sync::atomic::{AtomicU64, Ordering};
4use std::sync::{Arc, Mutex, MutexGuard, PoisonError};
5
6use chrono::Utc;
7use serde::{Deserialize, Serialize};
8use serde_json::{Map, Value, json};
9
10use super::generative::{
11 Author, Content, Part, Reaction, Role, Text, Tool, ToolAnswer, ToolSession, ToolsOrTool,
12};
13use super::share::{
14 AppendOptions, AppendResult, ChatTarget, SteerOptions, append_room_message,
15 list_room_attachments, page_messages, room_parts, set_room_inbox, set_room_repository,
16 steer_room, unqueue_room_message,
17};
18use super::socket::run_tool_call;
19use crate::authentification::{CredentialsOrApiKey, Profile};
20use crate::billing::PageQuery;
21use crate::cicada::inboxes::Inbox;
22use crate::drive::{self, DriveAuthorization};
23use crate::error::Result;
24use crate::groups::Group;
25use crate::shared::server::{Authorization, Hooks, Presence, Room, connect};
26use crate::termite::versioning::Repository;
27use crate::view::Target;
28
29use super::share::Attachment;
30
31#[derive(Debug, Clone)]
34pub struct RoomMessage {
35 pub id: String,
36 pub position: u32,
37 pub role: Role,
38 pub parts: Vec<Part>,
39 pub author: Option<Author>,
40 pub reply_to: Option<String>,
41 pub model: Option<Text>,
43 pub created: i64,
44}
45
46fn text(value: &Value) -> String {
47 match value {
48 Value::String(value) => value.clone(),
49 Value::Null => String::new(),
50 value => value.to_string(),
51 }
52}
53
54fn optional(value: &Value) -> Option<String> {
55 value.as_str().map(str::to_string)
56}
57
58fn inbox_of(value: &Value) -> Option<String> {
60 value
61 .as_str()
62 .filter(|id| !id.is_empty())
63 .map(str::to_string)
64}
65
66impl RoomMessage {
67 pub fn from_json(
69 json: &Value,
70 authorization: &CredentialsOrApiKey,
71 target: &ChatTarget,
72 ) -> RoomMessage {
73 RoomMessage {
74 id: text(&json["id"]),
75 position: json["position"].as_f64().unwrap_or_default() as u32,
76 role: serde_json::from_value(json["role"].clone()).unwrap_or(Role::User),
77 parts: room_parts(&json["parts"], authorization, target),
78 author: Author::from_json(&json["author"]),
79 reply_to: optional(&json["replyTo"]),
80 model: serde_json::from_value(json["model"].clone()).ok(),
81 created: json["created"].as_f64().unwrap_or_default() as i64,
82 }
83 }
84}
85
86#[derive(Debug, Clone)]
91pub struct RoomQueueItem {
92 pub id: String,
93 pub role: Role,
94 pub parts: Vec<Part>,
95 pub author: Option<Profile>,
96 pub model: Option<String>,
97 pub reasoning: Option<String>,
98 pub reply_to: Option<String>,
99 pub created: i64,
100}
101
102impl RoomQueueItem {
103 pub(crate) fn from_json(
104 json: &Value,
105 authorization: &CredentialsOrApiKey,
106 target: &ChatTarget,
107 ) -> RoomQueueItem {
108 RoomQueueItem {
109 id: text(&json["id"]),
110 role: serde_json::from_value(json["role"].clone()).unwrap_or(Role::User),
111 parts: room_parts(&json["parts"], authorization, target),
112 author: Profile::from_json(&json["author"]),
113 model: optional(&json["model"]),
114 reasoning: optional(&json["reasoning"]),
115 reply_to: optional(&json["replyTo"]),
116 created: json["created"].as_f64().unwrap_or_default() as i64,
117 }
118 }
119}
120
121#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
123#[serde(rename_all = "lowercase")]
124pub enum ToolStatus {
125 Running,
126 Success,
127 Error,
128}
129
130#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
131pub struct RoomToolState {
132 pub id: String,
133 pub name: String,
134 #[serde(default)]
136 pub args: Map<String, Value>,
137 pub status: ToolStatus,
138 #[serde(default, skip_serializing_if = "Option::is_none")]
139 pub result: Option<Map<String, Value>>,
140 #[serde(default, skip_serializing_if = "Option::is_none")]
141 pub error: Option<String>,
142 #[serde(default, skip_serializing_if = "Option::is_none")]
144 pub progress: Option<String>,
145 #[serde(default, skip_serializing_if = "Option::is_none")]
148 pub session: Option<ToolSession>,
149 #[serde(default, skip_serializing_if = "Option::is_none")]
151 pub calls: Option<Vec<RoomToolState>>,
152 #[serde(default, skip_serializing_if = "Option::is_none")]
154 pub logs: Option<Vec<String>>,
155}
156
157fn tool_states(json: &Value) -> Vec<RoomToolState> {
158 json.as_array()
159 .into_iter()
160 .flatten()
161 .filter_map(|tool| serde_json::from_value(tool.clone()).ok())
162 .collect()
163}
164
165#[derive(Debug, Clone)]
168pub struct StreamingReply {
169 pub turn: String,
170 pub text: String,
171 pub tools: Vec<RoomToolState>,
172 pub files: Vec<Attachment>,
173}
174
175#[derive(Debug, Clone, PartialEq)]
177pub struct RoomToolCall {
178 pub id: String,
179 pub name: String,
180 pub args: Map<String, Value>,
181 pub turn: Option<String>,
182}
183
184pub trait RoomHooks: Send + Sync {
187 fn on_message(&self, _room: &ChatRoom, _message: &RoomMessage) {}
189 fn on_queue(&self, _room: &ChatRoom) {}
191 fn on_thinking(&self, _room: &ChatRoom, _thinking: bool) {}
193 #[allow(clippy::too_many_arguments)]
200 fn on_delta(
201 &self,
202 _room: &ChatRoom,
203 _turn: &str,
204 _delta: &str,
205 _text: &str,
206 _aborted: bool,
207 _tools: &[RoomToolState],
208 _files: &[Attachment],
209 ) {
210 }
211 fn on_tool_call(&self, _room: &ChatRoom, _call: &RoomToolCall) {}
215 fn on_renamed(&self, _room: &ChatRoom, _name: &str) {}
217 fn on_repository(&self, _room: &ChatRoom) {}
219 fn on_inbox(&self, _room: &ChatRoom) {}
221 fn on_open_file(&self, _room: &ChatRoom, _file: &Target) {}
224 fn on_closed(&self, _room: &ChatRoom) {}
226 fn on_presence(&self, _room: &ChatRoom) {}
228}
229
230impl RoomHooks for () {}
231
232const OLDER_PAGE: u32 = 20;
233
234type RepositoryWatcher = Arc<dyn Fn(Option<u64>) + Send + Sync>;
235
236#[derive(Default)]
237struct Chat {
238 messages: Vec<RoomMessage>,
239 queue: Vec<RoomQueueItem>,
240 thinking: bool,
241 name: String,
242 system_prompt: String,
243 human: bool,
244 repository: Option<u64>,
245 inbox: Option<String>,
246 owner: String,
247 reference: String,
248 has_more: bool,
249 streaming: Option<StreamingReply>,
251 hydrated: bool,
253}
254
255struct ChatState {
256 target: ChatTarget,
257 chat: Mutex<Chat>,
258 hooks: Mutex<Arc<dyn RoomHooks>>,
259 client_tools: Mutex<Vec<Tool>>,
260 taken_calls: Mutex<HashSet<String>>,
263 waiting_calls: Mutex<Vec<RoomToolCall>>,
264 repository_watchers: Mutex<Vec<(u64, RepositoryWatcher)>>,
265 next_watcher: AtomicU64,
266 me: Mutex<Option<Presence>>,
268}
269
270fn lock<T>(mutex: &Mutex<T>) -> MutexGuard<'_, T> {
271 mutex.lock().unwrap_or_else(PoisonError::into_inner)
272}
273
274#[derive(Clone)]
285pub struct ChatRoom {
286 room: Room,
287 inner: Arc<ChatState>,
288}
289
290impl Deref for ChatRoom {
291 type Target = Room;
292 fn deref(&self) -> &Room {
293 &self.room
294 }
295}
296
297impl ChatRoom {
298 fn chat(&self) -> MutexGuard<'_, Chat> {
299 lock(&self.inner.chat)
300 }
301
302 fn hooks(&self) -> Arc<dyn RoomHooks> {
303 lock(&self.inner.hooks).clone()
304 }
305
306 pub fn get_messages(&self) -> Vec<RoomMessage> {
308 self.chat().messages.clone()
309 }
310
311 pub fn get_queue(&self) -> Vec<RoomQueueItem> {
313 self.chat().queue.clone()
314 }
315
316 pub fn get_name(&self) -> String {
318 self.chat().name.clone()
319 }
320
321 pub fn get_system_prompt(&self) -> String {
323 self.chat().system_prompt.clone()
324 }
325
326 pub fn is_human(&self) -> bool {
328 self.chat().human
329 }
330
331 pub fn repository(&self) -> Option<u64> {
333 self.chat().repository
334 }
335
336 pub fn inbox(&self) -> Option<String> {
338 self.chat().inbox.clone()
339 }
340
341 pub fn chat_id(&self) -> Option<String> {
343 let reference = self.chat().reference.clone();
344 reference
345 .strip_prefix("parrot:chat:")
346 .filter(|id| !id.is_empty() && id.bytes().all(|byte| byte.is_ascii_digit()))
347 .map(str::to_string)
348 }
349
350 pub fn owner(&self) -> String {
352 self.chat().owner.clone()
353 }
354
355 pub fn group(&self) -> Option<Group> {
357 let owner = self.owner();
358 owner
359 .strip_prefix("group:")
360 .filter(|id| !id.is_empty() && id.bytes().all(|byte| byte.is_ascii_digit()))
361 .map(|id| Group::from_json(&json!({ "id": id })))
362 }
363
364 pub async fn set_repository(&self, repository: Option<&Repository>) -> Result<()> {
366 set_room_repository(
367 self.get_authorization(),
368 &self.inner.target,
369 repository.map(|repository| repository.id),
370 )
371 .await
372 }
373
374 pub async fn set_inbox(&self, inbox: Option<&Inbox>) -> Result<()> {
376 set_room_inbox(
377 self.get_authorization(),
378 &self.inner.target,
379 inbox.map(|inbox| inbox.id.as_str()),
380 )
381 .await
382 }
383
384 pub fn watch_repository(
386 &self,
387 listener: impl Fn(Option<u64>) + Send + Sync + 'static,
388 ) -> Box<dyn FnOnce() + Send + Sync> {
389 let id = self.inner.next_watcher.fetch_add(1, Ordering::Relaxed);
390 lock(&self.inner.repository_watchers).push((id, Arc::new(listener)));
391 let inner = Arc::downgrade(&self.inner);
392 Box::new(move || {
393 if let Some(inner) = inner.upgrade() {
394 lock(&inner.repository_watchers).retain(|(other, _)| *other != id);
395 }
396 })
397 }
398
399 pub async fn attachments(&self) -> Result<Vec<Attachment>> {
401 list_room_attachments(self.get_authorization(), &self.inner.target).await
402 }
403
404 pub fn is_thinking(&self) -> bool {
406 self.chat().thinking
407 }
408
409 pub fn has_more(&self) -> bool {
411 self.chat().has_more
412 }
413
414 pub fn streaming_reply(&self) -> Option<StreamingReply> {
416 self.chat().streaming.clone()
417 }
418
419 pub fn replay_reply(&self) {
422 let (thinking, streaming) = {
423 let chat = self.chat();
424 (chat.thinking, chat.streaming.clone())
425 };
426 let hooks = self.hooks();
427 if thinking {
428 hooks.on_thinking(self, true);
429 }
430 if let Some(s) = streaming {
431 hooks.on_delta(self, &s.turn, &s.text, &s.text, false, &s.tools, &s.files);
432 }
433 }
434
435 pub async fn load_older(&self) -> Result<Vec<RoomMessage>> {
440 let cursor = self.chat().messages.len() as u32;
441 let page = page_messages(
442 self.get_authorization(),
443 &self.inner.target,
444 PageQuery {
445 cursor,
446 max: OLDER_PAGE,
447 },
448 )
449 .await?;
450 let mut chat = self.chat();
451 let older: Vec<RoomMessage> = page
452 .iter()
453 .filter(|message| {
454 !chat
455 .messages
456 .iter()
457 .any(|known| known.position == message.position)
458 })
459 .cloned()
460 .collect();
461 let mut messages = older.clone();
462 messages.append(&mut chat.messages);
463 messages.sort_by_key(|message| message.position);
464 chat.messages = messages;
465 chat.has_more = page.len() as u32 == OLDER_PAGE;
466 Ok(older)
467 }
468
469 pub async fn send_message(
477 &self,
478 role: Role,
479 parts: Vec<Part>,
480 mut options: AppendOptions,
481 ) -> Result<AppendResult> {
482 if options.tools.is_some() {
483 options.seat = lock(&self.inner.me).as_ref().map(Presence::id);
484 }
485 append_room_message(
486 self.get_authorization(),
487 &self.inner.target,
488 &Content {
489 parts,
490 role,
491 created_at: Utc::now(),
492 author: None,
493 model: None,
494 },
495 options,
496 )
497 .await
498 }
499
500 pub async fn react(
504 &self,
505 position: u32,
506 emoji: &str,
507 on: Option<bool>,
508 ) -> Result<AppendResult> {
509 let reaction = Reaction {
510 emoji: emoji.to_string(),
511 position,
512 on: on.unwrap_or(true),
513 };
514 self.send_message(
515 Role::User,
516 vec![Part::Reaction(reaction)],
517 AppendOptions::default(),
518 )
519 .await
520 }
521
522 pub fn send_tool_result(&self, call_id: &str, answer: &ToolAnswer) {
527 let mut frame = json!({ "event": "tool-result", "id": call_id });
528 if let (Value::Object(frame), Ok(Value::Object(answer))) =
529 (&mut frame, serde_json::to_value(answer))
530 {
531 frame.extend(answer);
532 }
533 self.post(&frame);
534 }
535
536 pub fn set_client_tools(&self, tools: Option<ToolsOrTool>) {
539 *lock(&self.inner.client_tools) = match tools {
540 None => Vec::new(),
541 Some(ToolsOrTool::Tools(tools)) => tools,
542 Some(ToolsOrTool::Tool(tool)) => vec![tool],
543 };
544 self.run_waiting_calls();
545 }
546
547 fn take_call(&self, call: RoomToolCall) {
549 if !lock(&self.inner.taken_calls).insert(call.id.clone()) {
550 return;
551 }
552 let tool = lock(&self.inner.client_tools)
553 .iter()
554 .find(|tool| tool.function.name == call.name)
555 .cloned();
556 let Some(tool) = tool else {
557 self.hooks().on_tool_call(self, &call);
558 return;
559 };
560 let room = self.clone();
561 tokio::spawn(async move {
562 let answer = run_tool_call(&[tool], &call.name, call.args, Arc::new(|_| {})).await;
563 room.send_tool_result(&call.id, &answer);
564 });
565 }
566
567 fn run_waiting_calls(&self) {
568 let waiting = std::mem::take(&mut *lock(&self.inner.waiting_calls));
569 for call in waiting {
570 self.take_call(call);
571 }
572 }
573
574 pub async fn unqueue(&self, queue_id: &str) -> Result<()> {
578 unqueue_room_message(self.get_authorization(), &self.inner.target, queue_id).await
579 }
580
581 pub async fn steer(&self, options: SteerOptions) -> Result<()> {
588 steer_room(self.get_authorization(), &self.inner.target, options).await
589 }
590
591 pub fn set_hooks(&self, hooks: Arc<dyn RoomHooks>) {
594 *lock(&self.inner.hooks) = hooks;
595 self.run_waiting_calls();
596 }
597
598 pub fn emit_closed(&self) {
600 self.room.clear_presences();
602 self.hooks().on_closed(self);
603 }
604
605 pub fn set_typing(&self, me: &Presence, typing: bool) {
607 me.set_status(if typing { "typing" } else { "" });
608 }
609
610 pub fn typing_presences(&self, me: Option<&Presence>) -> Vec<Presence> {
612 self.get_presences()
613 .into_iter()
614 .filter(|presence| {
615 me.is_none_or(|me| presence.id() != me.id()) && presence.status() == "typing"
616 })
617 .collect()
618 }
619
620 pub fn hydrate(&self, state: &Value) {
621 let authorization = self.get_authorization().clone();
622 let target = &self.inner.target;
623 let chat_state = &state["chat"];
624 let stream = &state["stream"];
625 let mut chat = self.chat();
626 let before = chat.hydrated.then(|| {
627 let known: HashSet<String> = chat.messages.iter().map(|m| m.id.clone()).collect();
628 (
629 known,
630 chat.name.clone(),
631 chat.repository,
632 chat.inbox.clone(),
633 )
634 });
635 chat.hydrated = true;
636 chat.name = chat_state["name"].as_str().unwrap_or_default().to_string();
637 chat.system_prompt = chat_state["systemPrompt"]
638 .as_str()
639 .unwrap_or_default()
640 .to_string();
641 chat.human = chat_state["human"] == true;
642 chat.repository = chat_state["repository"]
643 .as_f64()
644 .filter(|repository| *repository > 0.0)
645 .map(|repository| repository as u64);
646 chat.inbox = inbox_of(&chat_state["inbox"]);
647 chat.owner = chat_state["owner"].as_str().unwrap_or_default().to_string();
648 chat.reference = state["room"]["reference"]
649 .as_str()
650 .unwrap_or_default()
651 .to_string();
652 chat.messages = state["messages"]
653 .as_array()
654 .into_iter()
655 .flatten()
656 .map(|message| RoomMessage::from_json(message, &authorization, target))
657 .collect();
658 chat.queue = state["queue"]
659 .as_array()
660 .into_iter()
661 .flatten()
662 .map(|item| RoomQueueItem::from_json(item, &authorization, target))
663 .collect();
664 chat.has_more = match &state["hasMore"] {
665 Value::Bool(more) => *more,
666 Value::Null => false,
667 Value::Number(more) => more.as_f64().is_some_and(|more| more != 0.0),
668 Value::String(more) => !more.is_empty(),
669 _ => true,
670 };
671 chat.thinking = state["thinking"] == true;
672 chat.streaming = stream["turn"]
673 .as_str()
674 .filter(|turn| !turn.is_empty())
675 .map(|turn| StreamingReply {
676 turn: turn.to_string(),
677 text: match &stream["text"] {
678 Value::Null => String::new(),
679 value => text(value),
680 },
681 tools: tool_states(&stream["tools"]),
682 files: attachments(&stream["files"], &authorization),
683 });
684 drop(chat);
685 let calls = state["toolCalls"].as_array().into_iter().flatten();
688 lock(&self.inner.waiting_calls).extend(calls.filter_map(tool_call));
689 let Some((known, name, repository, inbox)) = before else {
690 return;
691 };
692 let (now_name, now_repository, now_inbox, fresh, thinking) = {
695 let chat = self.chat();
696 let fresh: Vec<RoomMessage> = chat
697 .messages
698 .iter()
699 .filter(|message| !known.contains(&message.id))
700 .cloned()
701 .collect();
702 (
703 chat.name.clone(),
704 chat.repository,
705 chat.inbox.clone(),
706 fresh,
707 chat.thinking,
708 )
709 };
710 let hooks = self.hooks();
711 if now_name != name {
712 hooks.on_renamed(self, &now_name);
713 }
714 if now_repository != repository {
715 hooks.on_repository(self);
716 let watchers: Vec<RepositoryWatcher> = lock(&self.inner.repository_watchers)
717 .iter()
718 .map(|(_, listener)| listener.clone())
719 .collect();
720 for listener in watchers {
721 listener(now_repository);
722 }
723 }
724 if now_inbox != inbox {
725 hooks.on_inbox(self);
726 }
727 for message in &fresh {
728 hooks.on_message(self, message);
729 }
730 hooks.on_queue(self);
731 if !thinking {
732 hooks.on_thinking(self, false);
733 }
734 self.replay_reply();
735 }
736
737 pub fn handle_event(&self, packet: &Value) -> bool {
738 let data = &packet["data"];
739 let hooks = self.hooks();
740 match packet["event"].as_str().unwrap_or_default() {
741 "chat-message" => {
742 if !data["message"].is_object() {
743 return true;
744 }
745 let message = RoomMessage::from_json(
746 &data["message"],
747 self.get_authorization(),
748 &self.inner.target,
749 );
750 {
751 let mut chat = self.chat();
752 if !chat.messages.iter().any(|known| known.id == message.id) {
753 chat.messages.push(message.clone());
754 chat.messages.sort_by_key(|message| message.position);
755 }
756 if message.role == Role::Model {
758 chat.streaming = None;
759 }
760 }
761 hooks.on_message(self, &message);
762 true
763 }
764 "chat-queue-add" => {
765 if !data["item"].is_object() {
766 return true;
767 }
768 let item = RoomQueueItem::from_json(
769 &data["item"],
770 self.get_authorization(),
771 &self.inner.target,
772 );
773 {
774 let mut chat = self.chat();
775 if !chat.queue.iter().any(|queued| queued.id == item.id) {
776 chat.queue.push(item);
777 chat.queue
778 .sort_by_key(|queued| queued.id.parse::<i128>().unwrap_or_default());
779 }
780 }
781 hooks.on_queue(self);
782 true
783 }
784 "chat-queue-remove" => {
785 let id = match &data["id"] {
786 Value::Null => String::new(),
787 id => text(id),
788 };
789 if id.is_empty() {
790 return true;
791 }
792 self.chat().queue.retain(|queued| queued.id != id);
793 hooks.on_queue(self);
794 true
795 }
796 "chat-delta" => {
797 let turn = match &data["turn"] {
801 Value::Null => String::new(),
802 turn => text(turn),
803 };
804 let full = match &data["text"] {
805 Value::Null => String::new(),
806 full => text(full),
807 };
808 if turn.is_empty() {
809 return true;
810 }
811 let tools = tool_states(&data["tools"]);
812 let files = attachments(&data["files"], self.get_authorization());
813 let delta = {
814 let mut chat = self.chat();
815 let previous = match &chat.streaming {
816 Some(streaming) if streaming.turn == turn => streaming.text.clone(),
817 _ => String::new(),
818 };
819 let delta = full
820 .strip_prefix(previous.as_str())
821 .unwrap_or(&full)
822 .to_string();
823 chat.streaming = Some(StreamingReply {
824 turn: turn.clone(),
825 text: full.clone(),
826 tools: tools.clone(),
827 files: files.clone(),
828 });
829 delta
830 };
831 hooks.on_delta(self, &turn, &delta, &full, false, &tools, &files);
832 true
833 }
834 "chat-delta-done" => {
835 let turn = match &data["turn"] {
839 Value::Null => String::new(),
840 turn => text(turn),
841 };
842 let done = {
843 let mut chat = self.chat();
844 match &chat.streaming {
845 Some(streaming) if turn.is_empty() || streaming.turn == turn => {
846 chat.streaming.take()
847 }
848 _ => None,
849 }
850 };
851 if let Some(done) = done {
852 hooks.on_delta(self, &done.turn, "", &done.text, true, &[], &[]);
853 }
854 true
855 }
856 "chat-status" => {
857 let thinking = match &data["thinking"] {
858 Value::Bool(thinking) => *thinking,
859 Value::Null => false,
860 Value::Number(thinking) => {
861 thinking.as_f64().is_some_and(|thinking| thinking != 0.0)
862 }
863 Value::String(thinking) => !thinking.is_empty(),
864 _ => true,
865 };
866 self.chat().thinking = thinking;
867 hooks.on_thinking(self, thinking);
868 true
869 }
870 "chat-renamed" => {
871 let name = {
872 let mut chat = self.chat();
873 if let Some(name) = data["name"].as_str() {
874 chat.name = name.to_string();
875 }
876 chat.name.clone()
877 };
878 hooks.on_renamed(self, &name);
879 true
880 }
881 "chat-updated" => {
882 let renamed = {
883 let mut chat = self.chat();
884 match data["name"].as_str() {
885 Some(name) if name != chat.name => {
886 chat.name = name.to_string();
887 Some(name.to_string())
888 }
889 _ => None,
890 }
891 };
892 if let Some(name) = renamed {
893 hooks.on_renamed(self, &name);
894 }
895 let repository = data["repository"]
896 .as_f64()
897 .filter(|repository| *repository > 0.0)
898 .map(|repository| repository as u64);
899 let changed = {
900 let mut chat = self.chat();
901 let changed = chat.repository != repository;
902 chat.repository = repository;
903 changed
904 };
905 if changed {
906 hooks.on_repository(self);
907 let watchers: Vec<RepositoryWatcher> = lock(&self.inner.repository_watchers)
908 .iter()
909 .map(|(_, listener)| listener.clone())
910 .collect();
911 for listener in watchers {
912 listener(repository);
913 }
914 }
915 let inbox = inbox_of(&data["inbox"]);
916 let changed = {
917 let mut chat = self.chat();
918 let changed = chat.inbox != inbox;
919 chat.inbox = inbox;
920 changed
921 };
922 if changed {
923 hooks.on_inbox(self);
924 }
925 true
926 }
927 "chat-open-file" => {
928 let attachment = &data["attachment"];
929 let repository = &data["repository"];
930 if !attachment.is_null() {
931 hooks.on_open_file(
932 self,
933 &Target::Attachment(Attachment::from_json(
934 attachment,
935 self.get_authorization(),
936 )),
937 );
938 } else if !repository.is_null() {
939 let file = drive::File::from_json(
940 repository,
941 DriveAuthorization::Repository {
942 authorization: self.get_authorization().clone(),
943 repository: repository["id"].as_u64().unwrap_or_default(),
944 path: repository["path"].as_str().unwrap_or_default().to_string(),
945 group: repository["group"]
946 .as_str()
947 .filter(|g| !g.is_empty())
948 .map(str::to_string),
949 },
950 );
951 hooks.on_open_file(self, &Target::File(file));
952 }
953 true
954 }
955 "chat-tool-call" => {
956 if let Some(call) = tool_call(data) {
957 self.take_call(call);
958 }
959 true
960 }
961 "chat-closed" | "server-closed" => {
962 self.emit_closed();
963 true
964 }
965 _ => false,
966 }
967 }
968}
969
970fn tool_call(raw: &Value) -> Option<RoomToolCall> {
971 let field = |key: &str| match &raw[key] {
972 Value::Null => String::new(),
973 value => text(value),
974 };
975 let (id, name) = (field("id"), field("name"));
976 if id.is_empty() || name.is_empty() {
977 return None;
978 }
979 Some(RoomToolCall {
980 id,
981 name,
982 args: match &raw["args"] {
983 Value::Object(args) => args.clone(),
984 _ => Map::new(),
985 },
986 turn: Some(field("turn")).filter(|turn| !turn.is_empty()),
987 })
988}
989
990fn attachments(json: &Value, authorization: &CredentialsOrApiKey) -> Vec<Attachment> {
991 json.as_array()
992 .into_iter()
993 .flatten()
994 .map(|raw| Attachment::from_json(raw, authorization))
995 .collect()
996}
997
998struct ChatHooks {
999 inner: Arc<ChatState>,
1000}
1001
1002impl ChatHooks {
1003 fn room(&self, room: &Room) -> ChatRoom {
1004 ChatRoom {
1005 room: room.clone(),
1006 inner: self.inner.clone(),
1007 }
1008 }
1009}
1010
1011impl Hooks for ChatHooks {
1012 fn on_connection(&self, room: &Room, state: &Value) {
1013 self.room(room).hydrate(state);
1014 }
1015
1016 fn on_event(&self, room: &Room, packet: &Value) -> bool {
1017 self.room(room).handle_event(packet)
1018 }
1019
1020 fn on_closed(&self, room: &Room, _reason: Option<&str>) {
1022 self.room(room).emit_closed();
1023 }
1024
1025 fn on_presence(&self, room: &Room) {
1026 let room = self.room(room);
1027 room.hooks().on_presence(&room);
1028 }
1029}
1030
1031pub async fn connect_room(
1037 authorization: &CredentialsOrApiKey,
1038 target: &ChatTarget,
1039 hooks: Option<Arc<dyn RoomHooks>>,
1040) -> Result<(ChatRoom, Presence)> {
1041 let auth = match target {
1042 ChatTarget::Code { code } => Authorization::AccessCode {
1043 authorization: authorization.clone(),
1044 access_code: code.clone(),
1045 },
1046 ChatTarget::Reference { reference } => Authorization::Server {
1047 authorization: authorization.clone(),
1048 server: reference.clone(),
1049 group: None,
1050 },
1051 };
1052
1053 let inner = Arc::new(ChatState {
1054 target: target.clone(),
1055 chat: Mutex::new(Chat::default()),
1056 hooks: Mutex::new(hooks.unwrap_or_else(|| Arc::new(()))),
1057 client_tools: Mutex::new(Vec::new()),
1058 taken_calls: Mutex::new(HashSet::new()),
1059 waiting_calls: Mutex::new(Vec::new()),
1060 repository_watchers: Mutex::new(Vec::new()),
1061 next_watcher: AtomicU64::new(0),
1062 me: Mutex::new(None),
1063 });
1064 let me = connect(
1065 auth,
1066 &format!("{}/chat/live", super::get_url()),
1067 Arc::new(ChatHooks {
1068 inner: inner.clone(),
1069 }),
1070 )
1071 .await?;
1072 *lock(&inner.me) = Some(me.clone());
1073 let room = ChatRoom {
1074 room: me.room().clone(),
1075 inner,
1076 };
1077 room.hooks().on_presence(&room);
1078
1079 Ok((room, me))
1080}
1081
1082#[cfg(test)]
1083mod tests {
1084 use std::sync::{Arc, Mutex};
1085
1086 use serde_json::{Value, json};
1087 use tokio::sync::mpsc;
1088 use tokio_tungstenite::tungstenite::Message;
1089
1090 use super::*;
1091 use crate::authentification::ApiKey;
1092
1093 #[derive(Default)]
1094 struct Recorder {
1095 events: Mutex<Vec<String>>,
1096 }
1097
1098 impl Recorder {
1099 fn push(&self, event: String) {
1100 self.events.lock().unwrap().push(event);
1101 }
1102 }
1103
1104 impl RoomHooks for Recorder {
1105 fn on_message(&self, _room: &ChatRoom, message: &RoomMessage) {
1106 self.push(format!("message {}", message.id));
1107 }
1108 fn on_queue(&self, room: &ChatRoom) {
1109 let ids: Vec<String> = room.get_queue().into_iter().map(|item| item.id).collect();
1110 self.push(format!("queue {}", ids.join(",")));
1111 }
1112 fn on_thinking(&self, _room: &ChatRoom, thinking: bool) {
1113 self.push(format!("thinking {thinking}"));
1114 }
1115 fn on_delta(
1116 &self,
1117 _room: &ChatRoom,
1118 turn: &str,
1119 delta: &str,
1120 text: &str,
1121 aborted: bool,
1122 tools: &[RoomToolState],
1123 _files: &[Attachment],
1124 ) {
1125 self.push(format!(
1126 "delta {turn} [{delta}] [{text}] {aborted} {}",
1127 tools.len()
1128 ));
1129 }
1130 fn on_tool_call(&self, _room: &ChatRoom, call: &RoomToolCall) {
1131 self.push(format!("tool {} {}", call.id, call.name));
1132 }
1133 fn on_renamed(&self, _room: &ChatRoom, name: &str) {
1134 self.push(format!("renamed {name}"));
1135 }
1136 fn on_repository(&self, room: &ChatRoom) {
1137 self.push(format!("repository {:?}", room.repository()));
1138 }
1139 fn on_inbox(&self, room: &ChatRoom) {
1140 self.push(format!("inbox {:?}", room.inbox()));
1141 }
1142 fn on_open_file(&self, _room: &ChatRoom, file: &Target) {
1143 match file {
1144 Target::Attachment(attachment) => {
1145 self.push(format!("open attachment {}", attachment.r#ref))
1146 }
1147 Target::File(file) => match &file.authorization {
1148 DriveAuthorization::Repository {
1149 repository,
1150 path,
1151 group,
1152 ..
1153 } => self.push(format!(
1154 "open repository {repository} {path} {group:?} {}",
1155 file.name()
1156 )),
1157 _ => self.push("open file".to_string()),
1158 },
1159 }
1160 }
1161 fn on_closed(&self, _room: &ChatRoom) {
1162 self.push("closed".to_string());
1163 }
1164 }
1165
1166 fn chat_room(recorder: Arc<Recorder>) -> (ChatRoom, mpsc::UnboundedReceiver<Message>) {
1167 let (ws, outbox) = mpsc::unbounded_channel();
1168 let authorization = CredentialsOrApiKey::ApiKey(ApiKey {
1169 id: "key".to_string(),
1170 ..ApiKey::default()
1171 });
1172 let room = Room::new(
1173 "http://localhost/chat/live".to_string(),
1174 ws,
1175 Authorization::Server {
1176 authorization,
1177 server: "parrot:chat:9".to_string(),
1178 group: None,
1179 },
1180 "room".to_string(),
1181 );
1182 let inner = Arc::new(ChatState {
1183 target: ChatTarget::Reference {
1184 reference: "parrot:chat:9".to_string(),
1185 },
1186 chat: Mutex::new(Chat::default()),
1187 hooks: Mutex::new(recorder),
1188 client_tools: Mutex::new(Vec::new()),
1189 taken_calls: Mutex::new(HashSet::new()),
1190 waiting_calls: Mutex::new(Vec::new()),
1191 repository_watchers: Mutex::new(Vec::new()),
1192 next_watcher: AtomicU64::new(0),
1193 me: Mutex::new(None),
1194 });
1195 (ChatRoom { room, inner }, outbox)
1196 }
1197
1198 fn message(id: &str, position: u32, role: &str) -> Value {
1199 json!({ "id": id, "position": position, "role": role, "parts": [{ "type": "TEXT", "text": id }], "created": 1 })
1200 }
1201
1202 #[test]
1203 fn hydrate_reads_the_connection_snapshot() {
1204 let recorder = Arc::new(Recorder::default());
1205 let (room, _outbox) = chat_room(recorder);
1206 room.hydrate(&json!({
1207 "chat": { "name": "Plans", "systemPrompt": "Be brief", "human": false, "repository": 4, "inbox": "31", "owner": "group:12" },
1208 "room": { "reference": "parrot:chat:9" },
1209 "messages": [message("2", 2, "MODEL"), message("1", 1, "USER")],
1210 "queue": [{ "id": "5", "role": "USER", "parts": [], "created": 2 }],
1211 "hasMore": true,
1212 "thinking": true,
1213 "stream": { "turn": "t1", "text": "Half", "tools": [{ "id": "x", "name": "exec", "status": "running" }] }
1214 }));
1215 assert_eq!(room.get_name(), "Plans");
1216 assert_eq!(room.get_system_prompt(), "Be brief");
1217 assert_eq!(room.repository(), Some(4));
1218 assert_eq!(room.inbox().as_deref(), Some("31"));
1219 assert_eq!(room.chat_id().as_deref(), Some("9"));
1220 assert_eq!(room.group().unwrap().id, "12");
1221 assert_eq!(room.get_messages().len(), 2);
1222 assert_eq!(room.get_queue()[0].id, "5");
1223 assert!(room.has_more());
1224 assert!(room.is_thinking());
1225 let streaming = room.streaming_reply().unwrap();
1226 assert_eq!(streaming.text, "Half");
1227 assert_eq!(streaming.tools[0].status, ToolStatus::Running);
1228 }
1229
1230 #[test]
1231 fn events_update_the_room_and_reach_the_hooks() {
1232 let recorder = Arc::new(Recorder::default());
1233 let (room, mut outbox) = chat_room(recorder.clone());
1234 let seen = Arc::new(Mutex::new(Vec::new()));
1235 let watched = seen.clone();
1236 let stop =
1237 room.watch_repository(move |repository| watched.lock().unwrap().push(repository));
1238
1239 for packet in [
1240 json!({ "event": "chat-status", "data": { "thinking": true } }),
1241 json!({ "event": "chat-delta", "data": { "turn": "t1", "text": "Hel" } }),
1242 json!({ "event": "chat-delta", "data": { "turn": "t1", "text": "Hello", "tools": [{ "id": "x", "name": "exec", "status": "success" }] } }),
1243 json!({ "event": "chat-delta-done", "data": { "turn": "t1" } }),
1244 json!({ "event": "chat-message", "data": { "message": message("3", 3, "MODEL") } }),
1245 json!({ "event": "chat-message", "data": { "message": message("3", 3, "MODEL") } }),
1246 json!({ "event": "chat-queue-add", "data": { "item": { "id": "10", "role": "USER", "parts": [] } } }),
1247 json!({ "event": "chat-queue-add", "data": { "item": { "id": "9", "role": "USER", "parts": [] } } }),
1248 json!({ "event": "chat-queue-remove", "data": { "id": "10" } }),
1249 json!({ "event": "chat-updated", "data": { "name": "Build", "repository": 7, "inbox": "31" } }),
1250 json!({ "event": "chat-tool-call", "data": { "id": "c1", "name": "pick", "args": {} } }),
1251 json!({ "event": "chat-tool-call", "data": { "id": "c1", "name": "pick", "args": {} } }),
1252 json!({ "event": "chat-closed" }),
1253 ] {
1254 assert!(room.handle_event(&packet));
1255 }
1256 stop();
1257 room.handle_event(
1258 &json!({ "event": "chat-updated", "data": { "repository": 0, "inbox": null } }),
1259 );
1260 assert!(!room.handle_event(&json!({ "event": "something-else" })));
1261
1262 assert_eq!(
1263 *recorder.events.lock().unwrap(),
1264 vec![
1265 "thinking true",
1266 "delta t1 [Hel] [Hel] false 0",
1267 "delta t1 [lo] [Hello] false 1",
1268 "delta t1 [] [Hello] true 0",
1269 "message 3",
1270 "message 3",
1271 "queue 10",
1272 "queue 9,10",
1273 "queue 9",
1274 "renamed Build",
1275 "repository Some(7)",
1276 "inbox Some(\"31\")",
1277 "tool c1 pick",
1278 "closed",
1279 "repository None",
1280 "inbox None",
1281 ]
1282 );
1283 assert_eq!(room.get_messages().len(), 1);
1284 assert_eq!(*seen.lock().unwrap(), vec![Some(7)]);
1285
1286 room.send_tool_result(
1287 "c1",
1288 &ToolAnswer::Result {
1289 result: serde_json::Map::from_iter([("a".to_string(), json!(1))]),
1290 },
1291 );
1292 let Some(Message::Text(frame)) = outbox.blocking_recv() else {
1293 panic!("expected a frame");
1294 };
1295 assert_eq!(
1296 serde_json::from_str::<Value>(frame.as_str()).unwrap(),
1297 json!({ "event": "tool-result", "id": "c1", "result": { "a": 1 } })
1298 );
1299 }
1300
1301 #[test]
1302 fn opened_files_are_attachments_or_live_repository_files() {
1303 let recorder = Arc::new(Recorder::default());
1304 let (room, _outbox) = chat_room(recorder.clone());
1305 room.handle_event(&json!({ "event": "chat-open-file", "data": { "attachment": { "type": "FILE", "ref": "r1", "name": "a.png", "contentType": "image/png", "chat": "9" } } }));
1306 room.handle_event(&json!({ "event": "chat-open-file", "data": { "repository": { "id": 41, "group": "7", "path": "/repository/src/a.ts", "name": "a.ts", "contentType": "text/typescript", "contentLength": 3 } } }));
1307 assert_eq!(
1308 *recorder.events.lock().unwrap(),
1309 vec![
1310 "open attachment r1",
1311 "open repository 41 /repository/src/a.ts Some(\"7\") a.ts",
1312 ]
1313 );
1314 }
1315}