Skip to main content

fauna_api/parrot/
room.rs

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/// One durable message in a room transcript, as the room sends it: its parts as they're
32/// stored (file refs, no bytes over the socket), its author and model as on `Content`.
33#[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    /// The model that wrote a MODEL turn.
42    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
58/// A chat's inbox id as the room sends it: an id, or null.
59fn 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    /// FILE parts arrive as `{ accessCode | path | ref }` and stream lazily through `drive::File`.
68    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/// One buffered send in the shared room queue. When a member sends while the
87/// model is replying, it lands here (visible to all members) instead of the
88/// transcript, and drains FIFO into the transcript as replies complete. `id` is
89/// the stable per-row key used for unqueue/steer targeting and orders the queue.
90#[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/// `"running" | "success" | "error"` in the TypeScript SDK.
122#[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    /// A `run_code` call's `code` fills in as the model writes it.
135    #[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    /// What a running tool is waiting on, like the machine starting.
143    #[serde(default, skip_serializing_if = "Option::is_none")]
144    pub progress: Option<String>,
145    /// The machine room the tool works in, to watch it, joined by reference by the people who
146    /// may use the machine.
147    #[serde(default, skip_serializing_if = "Option::is_none")]
148    pub session: Option<ToolSession>,
149    /// The calls a `run_code` call's program made, as they start and finish.
150    #[serde(default, skip_serializing_if = "Option::is_none")]
151    pub calls: Option<Vec<RoomToolState>>,
152    /// What a `run_code` call's program logged so far.
153    #[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/// The in-progress streamed model reply: `{ turn, text, tools, files }` in the
166/// TypeScript SDK.
167#[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/// A client tool call the room asks your page to run.
176#[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
184/// Chat room hooks. Every method defaults to a no-op, like the optional members
185/// of the TypeScript `RoomHooks` object.
186pub trait RoomHooks: Send + Sync {
187    /// A new message landed (any member's send, or the server's model reply).
188    fn on_message(&self, _room: &ChatRoom, _message: &RoomMessage) {}
189    /// The shared queue changed (an item was buffered, released, or unqueued).
190    fn on_queue(&self, _room: &ChatRoom) {}
191    /// The room's model reply started (true) or finished (false).
192    fn on_thinking(&self, _room: &ChatRoom, _thinking: bool) {}
193    /// The room's model reply is streaming. `text` is the full reply so far;
194    /// `delta` is the new portion since the last call. Fires as the reply grows.
195    /// When the turn finishes, the finished reply also arrives via `on_message` (a
196    /// durable row). `aborted` is true on the terminal call: the streamed turn
197    /// finalized or was cancelled; drop the partial and rely on `on_message`.
198    /// `files` are what the reply attached so far.
199    #[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    /// A client tool call for you (evaluate it, then send_tool_result). A NON_BLOCKING call can
212    /// arrive long after the reply that made it, or again on connect while it's still running;
213    /// a room gets each call once.
214    fn on_tool_call(&self, _room: &ChatRoom, _call: &RoomToolCall) {}
215    /// The chat was renamed.
216    fn on_renamed(&self, _room: &ChatRoom, _name: &str) {}
217    /// The chat's repository was attached, swapped or detached.
218    fn on_repository(&self, _room: &ChatRoom) {}
219    /// The chat's inbox was attached, swapped or detached.
220    fn on_inbox(&self, _room: &ChatRoom) {}
221    /// The reply pointed everyone to a file (Parrot's `open`): show it. A chat attachment, or a
222    /// file in the chat's repository, live.
223    fn on_open_file(&self, _room: &ChatRoom, _file: &Target) {}
224    /// The chat was deleted/closed by its owner (or the host disconnected).
225    fn on_closed(&self, _room: &ChatRoom) {}
226    /// The roster changed (someone joined/left or updated presence/status).
227    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    // The current streamed model turn so far (by turn id).
250    streaming: Option<StreamingReply>,
251    // Hydrated once: a later hydrate is a reconnect.
252    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    // Calls this room has taken, so each runs once, and calls from the connection snapshot
261    // waiting for client tools or hooks.
262    taken_calls: Mutex<HashSet<String>>,
263    waiting_calls: Mutex<Vec<RoomToolCall>>,
264    repository_watchers: Mutex<Vec<(u64, RepositoryWatcher)>>,
265    next_watcher: AtomicU64,
266    /// This room's own presence, whose seat is the page that runs the tools its sends offer.
267    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/// A live, domain-agnostic chat room. `ChatRoom` wraps `Room` and owns everything
275/// chat-transcript-specific: a WINDOWED transcript (the last page hydrated on
276/// connect), `load_older()` pagination for scroll-up backfill, the shared
277/// queue, and the streamed model reply. It is NOT tied to a durable "chat":
278/// Parrot, Extensions.Web, and Marmot's chat side all reuse it. The generic
279/// `Room` stays domain-agnostic (presence + deltas) for non-chat rooms.
280///
281/// Sends go through the append edge (so file parts stream) and the server owns
282/// turn-taking: once the room goes quiet it streams one model reply over the
283/// whole transcript, billed to the room's host principal.
284#[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    /// The currently-loaded transcript window, in order.
307    pub fn get_messages(&self) -> Vec<RoomMessage> {
308        self.chat().messages.clone()
309    }
310
311    /// The current shared queue (buffered sends), in FIFO order.
312    pub fn get_queue(&self) -> Vec<RoomQueueItem> {
313        self.chat().queue.clone()
314    }
315
316    /// The chat's name.
317    pub fn get_name(&self) -> String {
318        self.chat().name.clone()
319    }
320
321    /// Room system prompt (not a transcript row). Empty when unset.
322    pub fn get_system_prompt(&self) -> String {
323        self.chat().system_prompt.clone()
324    }
325
326    /// True for a people only chat: no model ever replies, so sends never queue.
327    pub fn is_human(&self) -> bool {
328        self.chat().human
329    }
330
331    /// The chat's repository, by id. Kept current for everyone in the room.
332    pub fn repository(&self) -> Option<u64> {
333        self.chat().repository
334    }
335
336    /// The chat's inbox, by id: replies' inbox tools work there. Kept current for everyone in the room.
337    pub fn inbox(&self) -> Option<String> {
338        self.chat().inbox.clone()
339    }
340
341    /// The saved chat this room is bound to, by id, or None for an unbound room.
342    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    /// Who owns the chat: `credentials:{id}`, `group:{id}`, `friend:{id}` or `partnership:{id}`. Empty for an unbound room.
351    pub fn owner(&self) -> String {
352        self.chat().owner.clone()
353    }
354
355    /// The group that owns the chat, whose repositories it takes; None for anyone else's.
356    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    /// Attach a repository, or None to detach. Everyone in the room sees the change.
365    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    /// Attach an inbox for replies' inbox tools to work in, or None to detach. Everyone in the room sees the change.
375    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    /// Hear about every repository change, from anyone in the room. Returns a function that stops listening.
385    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    /// Every file in the chat, newest first: what people attached and what Parrot opened.
400    pub async fn attachments(&self) -> Result<Vec<Attachment>> {
401        list_room_attachments(self.get_authorization(), &self.inner.target).await
402    }
403
404    /// True while the server is streaming the room's model reply.
405    pub fn is_thinking(&self) -> bool {
406        self.chat().thinking
407    }
408
409    /// True while older transcript pages remain to be loaded (scroll-up).
410    pub fn has_more(&self) -> bool {
411        self.chat().has_more
412    }
413
414    /// The in-progress streamed model reply, or None when none is streaming.
415    pub fn streaming_reply(&self) -> Option<StreamingReply> {
416        self.chat().streaming.clone()
417    }
418
419    /// Send the reply under way (thinking, and the streamed turn so far) to the hooks
420    /// again, for a UI that sets its hooks after connecting in the middle of a reply.
421    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    /// Load one older page of transcript messages and merge it into the window by
436    /// position. The cursor is how many messages are already loaded, counted from
437    /// the newest, so live messages that arrived since connect keep it correct.
438    /// File parts stream lazily via their `drive::File`s.
439    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    /// Append a message to the shared transcript. USER sends are attributed to
470    /// the caller and nudge the server's debounced model reply. If the room is
471    /// currently replying the server buffers the send into the shared queue
472    /// instead (drained FIFO when the reply finishes); the result says which
473    /// happened. File parts stream their bytes with the message. `model`
474    /// (optional) is the sender's selected model; the reply uses the last
475    /// sender's choice.
476    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    /// React to the message at transcript `position`. A reaction is its own USER
501    /// message (so in a chat with a model it prompts a reply like any send);
502    /// `on: Some(false)` takes it back.
503    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    /// Answer a client tool call addressed to you: its result object, or why it failed. A
523    /// BLOCKING call's reply waits for it, from the page whose send offered the tool; a
524    /// NON_BLOCKING call takes it any time, from any of your pages, even after the reply ended,
525    /// and its result lands in the chat as the same invocation, finished. The first answer wins.
526    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    /// Register Tool.evaluate handlers for originator-only room tool calls.
537    /// When a chat-tool-call arrives, matching tools auto-evaluate and reply.
538    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    /// Runs a call once: a matching client tool, else the on_tool_call hook.
548    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    /// Remove one of your buffered messages from the shared queue. It never
575    /// entered the transcript, so this is not an unsend: the server just drops
576    /// the queue row and it fans out to every member.
577    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    /// Steer the room: stop the in-progress model reply now and have the server
582    /// re-answer after the normal debounce window. Any member may steer.
583    /// `queue_id` releases just that one queued row into the transcript first
584    /// (per-item steer); `all` flushes the whole queue in FIFO order (steer-all).
585    /// Released rows behave like idle sends: the model does NOT reply immediately.
586    /// `stop` cancels the current reply without scheduling a new one.
587    pub async fn steer(&self, options: SteerOptions) -> Result<()> {
588        steer_room(self.get_authorization(), &self.inner.target, options).await
589    }
590
591    /// Replace the room's event hooks after connection (e.g. once the UI
592    /// that owns rendering is ready).
593    pub fn set_hooks(&self, hooks: Arc<dyn RoomHooks>) {
594        *lock(&self.inner.hooks) = hooks;
595        self.run_waiting_calls();
596    }
597
598    /// Fire on_closed using the latest hooks (set_hooks), not the connect-time ones.
599    pub fn emit_closed(&self) {
600        // Drop local roster so a remounted widget cannot paint stale peers.
601        self.room.clear_presences();
602        self.hooks().on_closed(self);
603    }
604
605    /// Broadcast this member's typing state to the room (presence status).
606    pub fn set_typing(&self, me: &Presence, typing: bool) {
607        me.set_status(if typing { "typing" } else { "" });
608    }
609
610    /// Members currently marked as typing (excludes the given self presence).
611    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        // Background calls still running for you, from replies that ended or ran elsewhere.
686        // Nothing can run them yet, so they wait for set_client_tools or set_hooks.
687        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        // A reconnect: what changed while the socket was gone reaches the hooks as it would
693        // have live.
694        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                    // A MODEL row finalizes any in-progress streamed turn.
757                    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                // The server streams the in-progress reply as full text (fans out
798                // to every replica). Compute the delta against what we last saw so
799                // callers can append incrementally.
800                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                // The stream row was cleared: the turn finalized (a durable
836                // chat-message follows) or aborted. Either way, drop the partial;
837                // the transcript's MODEL row (if any) is authoritative.
838                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    // Use ChatRoom.emit_closed so set_hooks(on_closed) after UI mount is honored.
1021    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
1031/// Connect to a chat's live room as a `ChatRoom`. `target` is an access code or the
1032/// room's reference (`parrot:chat:{chatId}`). Resolves with the
1033/// room and the caller's own `Presence` (use it to broadcast typing + position).
1034/// The connection snapshot carries only the last transcript window; scroll-up
1035/// backfill goes through `room.load_older()`.
1036pub 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}