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