use std::ops::Deref;
use std::sync::atomic::{AtomicU64, Ordering};
use std::sync::{Arc, Mutex, MutexGuard, PoisonError};
use chrono::Utc;
use serde::{Deserialize, Serialize};
use serde_json::{Map, Value, json};
use super::generative::{Author, Content, Part, Reaction, Role, Text, Tool, ToolsOrTool};
use super::share::{
AppendOptions, AppendResult, ChatTarget, SteerOptions, append_room_message,
list_room_attachments, page_messages, room_parts, set_room_repository, steer_room,
unqueue_room_message,
};
use crate::authentification::{CredentialsOrApiKey, Profile};
use crate::billing::PageQuery;
use crate::drive::{self, DriveAuthorization};
use crate::error::Result;
use crate::groups::Group;
use crate::shared::server::{Authorization, Hooks, Presence, Room, connect};
use crate::termite::versioning::Repository;
use crate::view::Target;
pub use super::share::Attachment;
#[derive(Debug, Clone)]
pub struct RoomMessage {
pub id: String,
pub position: u32,
pub role: Role,
pub parts: Vec<Part>,
pub author: Option<Author>,
pub reply_to: Option<String>,
pub model: Option<Text>,
pub created: i64,
}
fn text(value: &Value) -> String {
match value {
Value::String(value) => value.clone(),
Value::Null => String::new(),
value => value.to_string(),
}
}
fn optional(value: &Value) -> Option<String> {
value.as_str().map(str::to_string)
}
impl RoomMessage {
pub fn from_json(
json: &Value,
authorization: &CredentialsOrApiKey,
target: &ChatTarget,
) -> RoomMessage {
RoomMessage {
id: text(&json["id"]),
position: json["position"].as_f64().unwrap_or_default() as u32,
role: serde_json::from_value(json["role"].clone()).unwrap_or(Role::User),
parts: room_parts(&json["parts"], authorization, target),
author: Author::from_json(&json["author"]),
reply_to: optional(&json["replyTo"]),
model: serde_json::from_value(json["model"].clone()).ok(),
created: json["created"].as_f64().unwrap_or_default() as i64,
}
}
}
#[derive(Debug, Clone)]
pub struct RoomQueueItem {
pub id: String,
pub role: Role,
pub parts: Vec<Part>,
pub author: Option<Profile>,
pub model: Option<String>,
pub reasoning: Option<String>,
pub reply_to: Option<String>,
pub created: i64,
}
impl RoomQueueItem {
pub(crate) fn from_json(
json: &Value,
authorization: &CredentialsOrApiKey,
target: &ChatTarget,
) -> RoomQueueItem {
RoomQueueItem {
id: text(&json["id"]),
role: serde_json::from_value(json["role"].clone()).unwrap_or(Role::User),
parts: room_parts(&json["parts"], authorization, target),
author: Profile::from_json(&json["author"]),
model: optional(&json["model"]),
reasoning: optional(&json["reasoning"]),
reply_to: optional(&json["replyTo"]),
created: json["created"].as_f64().unwrap_or_default() as i64,
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum ToolStatus {
Running,
Success,
Error,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum ToolSessionKind {
Browser,
Desktop,
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct ToolSession {
pub kind: ToolSessionKind,
pub reference: String,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub code: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub url: Option<String>,
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct RoomToolState {
pub id: String,
pub name: String,
#[serde(default)]
pub args: Map<String, Value>,
pub status: ToolStatus,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub result: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub progress: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub session: Option<ToolSession>,
}
fn tool_states(json: &Value) -> Vec<RoomToolState> {
json.as_array()
.into_iter()
.flatten()
.filter_map(|tool| serde_json::from_value(tool.clone()).ok())
.collect()
}
#[derive(Debug, Clone)]
pub struct StreamingReply {
pub turn: String,
pub text: String,
pub tools: Vec<RoomToolState>,
pub files: Vec<Attachment>,
}
#[derive(Debug, Clone, PartialEq)]
pub struct RoomToolCall {
pub id: String,
pub name: String,
pub args: Map<String, Value>,
pub turn: Option<String>,
}
pub trait RoomHooks: Send + Sync {
fn on_message(&self, _room: &ChatRoom, _message: &RoomMessage) {}
fn on_queue(&self, _room: &ChatRoom) {}
fn on_thinking(&self, _room: &ChatRoom, _thinking: bool) {}
#[allow(clippy::too_many_arguments)]
fn on_delta(
&self,
_room: &ChatRoom,
_turn: &str,
_delta: &str,
_text: &str,
_aborted: bool,
_tools: &[RoomToolState],
_files: &[Attachment],
) {
}
fn on_tool_call(&self, _room: &ChatRoom, _call: &RoomToolCall) {}
fn on_renamed(&self, _room: &ChatRoom, _name: &str) {}
fn on_repository(&self, _room: &ChatRoom) {}
fn on_open_file(&self, _room: &ChatRoom, _file: &Target) {}
fn on_closed(&self, _room: &ChatRoom) {}
fn on_presence(&self, _room: &ChatRoom) {}
}
impl RoomHooks for () {}
const OLDER_PAGE: u32 = 20;
type RepositoryWatcher = Arc<dyn Fn(Option<u64>) + Send + Sync>;
#[derive(Default)]
struct Chat {
messages: Vec<RoomMessage>,
queue: Vec<RoomQueueItem>,
thinking: bool,
name: String,
system_prompt: String,
human: bool,
repository: Option<u64>,
owner: String,
write: bool,
reference: String,
has_more: bool,
streaming: Option<StreamingReply>,
}
struct ChatState {
target: ChatTarget,
chat: Mutex<Chat>,
hooks: Mutex<Arc<dyn RoomHooks>>,
client_tools: Mutex<Vec<Tool>>,
repository_watchers: Mutex<Vec<(u64, RepositoryWatcher)>>,
next_watcher: AtomicU64,
}
fn lock<T>(mutex: &Mutex<T>) -> MutexGuard<'_, T> {
mutex.lock().unwrap_or_else(PoisonError::into_inner)
}
#[derive(Clone)]
pub struct ChatRoom {
room: Room,
inner: Arc<ChatState>,
}
impl Deref for ChatRoom {
type Target = Room;
fn deref(&self) -> &Room {
&self.room
}
}
impl ChatRoom {
fn chat(&self) -> MutexGuard<'_, Chat> {
lock(&self.inner.chat)
}
fn hooks(&self) -> Arc<dyn RoomHooks> {
lock(&self.inner.hooks).clone()
}
pub fn get_messages(&self) -> Vec<RoomMessage> {
self.chat().messages.clone()
}
pub fn get_queue(&self) -> Vec<RoomQueueItem> {
self.chat().queue.clone()
}
pub fn get_name(&self) -> String {
self.chat().name.clone()
}
pub fn get_system_prompt(&self) -> String {
self.chat().system_prompt.clone()
}
pub fn is_human(&self) -> bool {
self.chat().human
}
pub fn can_write(&self) -> bool {
self.chat().write
}
pub fn repository(&self) -> Option<u64> {
self.chat().repository
}
pub fn chat_id(&self) -> Option<String> {
let reference = self.chat().reference.clone();
reference
.strip_prefix("parrot:chat:")
.filter(|id| !id.is_empty() && id.bytes().all(|byte| byte.is_ascii_digit()))
.map(str::to_string)
}
pub fn owner(&self) -> String {
self.chat().owner.clone()
}
pub fn group(&self) -> Option<Group> {
let owner = self.owner();
owner
.strip_prefix("group:")
.filter(|id| !id.is_empty() && id.bytes().all(|byte| byte.is_ascii_digit()))
.map(|id| Group::from_json(&json!({ "id": id })))
}
pub async fn set_repository(&self, repository: Option<&Repository>) -> Result<()> {
set_room_repository(
self.get_authorization(),
&self.inner.target,
repository.map(|repository| repository.id),
)
.await
}
pub fn watch_repository(
&self,
listener: impl Fn(Option<u64>) + Send + Sync + 'static,
) -> Box<dyn FnOnce() + Send + Sync> {
let id = self.inner.next_watcher.fetch_add(1, Ordering::Relaxed);
lock(&self.inner.repository_watchers).push((id, Arc::new(listener)));
let inner = Arc::downgrade(&self.inner);
Box::new(move || {
if let Some(inner) = inner.upgrade() {
lock(&inner.repository_watchers).retain(|(other, _)| *other != id);
}
})
}
pub async fn attachments(&self) -> Result<Vec<Attachment>> {
list_room_attachments(self.get_authorization(), &self.inner.target).await
}
pub fn is_thinking(&self) -> bool {
self.chat().thinking
}
pub fn has_more(&self) -> bool {
self.chat().has_more
}
pub fn streaming_reply(&self) -> Option<StreamingReply> {
self.chat().streaming.clone()
}
pub fn replay_reply(&self) {
let (thinking, streaming) = {
let chat = self.chat();
(chat.thinking, chat.streaming.clone())
};
let hooks = self.hooks();
if thinking {
hooks.on_thinking(self, true);
}
if let Some(s) = streaming {
hooks.on_delta(self, &s.turn, &s.text, &s.text, false, &s.tools, &s.files);
}
}
pub async fn load_older(&self) -> Result<Vec<RoomMessage>> {
let cursor = self.chat().messages.len() as u32;
let page = page_messages(
self.get_authorization(),
&self.inner.target,
PageQuery {
cursor,
max: OLDER_PAGE,
},
)
.await?;
let mut chat = self.chat();
let older: Vec<RoomMessage> = page
.iter()
.filter(|message| {
!chat
.messages
.iter()
.any(|known| known.position == message.position)
})
.cloned()
.collect();
let mut messages = older.clone();
messages.append(&mut chat.messages);
messages.sort_by_key(|message| message.position);
chat.messages = messages;
chat.has_more = page.len() as u32 == OLDER_PAGE;
Ok(older)
}
pub async fn send_message(
&self,
role: Role,
parts: Vec<Part>,
options: AppendOptions,
) -> Result<AppendResult> {
append_room_message(
self.get_authorization(),
&self.inner.target,
&Content {
parts,
role,
created_at: Utc::now(),
author: None,
model: None,
},
options,
)
.await
}
pub async fn react(
&self,
position: u32,
emoji: &str,
on: Option<bool>,
) -> Result<AppendResult> {
let reaction = Reaction {
emoji: emoji.to_string(),
position,
on: on.unwrap_or(true),
};
self.send_message(
Role::User,
vec![Part::Reaction(reaction)],
AppendOptions::default(),
)
.await
}
pub fn send_tool_result(&self, call_id: &str, result: &str) {
self.post(&json!({ "event": "tool-result", "id": call_id, "result": result }));
}
pub fn set_client_tools(&self, tools: Option<ToolsOrTool>) {
*lock(&self.inner.client_tools) = match tools {
None => Vec::new(),
Some(ToolsOrTool::Tools(tools)) => tools,
Some(ToolsOrTool::Tool(tool)) => vec![tool],
};
}
pub async fn unqueue(&self, queue_id: &str) -> Result<()> {
unqueue_room_message(self.get_authorization(), &self.inner.target, queue_id).await
}
pub async fn steer(&self, options: SteerOptions) -> Result<()> {
steer_room(self.get_authorization(), &self.inner.target, options).await
}
pub fn set_hooks(&self, hooks: Arc<dyn RoomHooks>) {
*lock(&self.inner.hooks) = hooks;
}
pub fn emit_closed(&self) {
self.room.clear_presences();
self.hooks().on_closed(self);
}
pub fn set_typing(&self, me: &Presence, typing: bool) {
me.set_status(if typing { "typing" } else { "" });
}
pub fn typing_presences(&self, me: Option<&Presence>) -> Vec<Presence> {
self.get_presences()
.into_iter()
.filter(|presence| {
me.is_none_or(|me| presence.id() != me.id()) && presence.status() == "typing"
})
.collect()
}
pub fn hydrate(&self, state: &Value) {
let authorization = self.get_authorization().clone();
let target = &self.inner.target;
let chat_state = &state["chat"];
let stream = &state["stream"];
let mut chat = self.chat();
chat.name = chat_state["name"].as_str().unwrap_or_default().to_string();
chat.system_prompt = chat_state["systemPrompt"]
.as_str()
.unwrap_or_default()
.to_string();
chat.human = chat_state["human"] == true;
chat.repository = chat_state["repository"]
.as_f64()
.filter(|repository| *repository > 0.0)
.map(|repository| repository as u64);
chat.owner = chat_state["owner"].as_str().unwrap_or_default().to_string();
chat.write = chat_state["write"] != false;
chat.reference = state["room"]["reference"]
.as_str()
.unwrap_or_default()
.to_string();
chat.messages = state["messages"]
.as_array()
.into_iter()
.flatten()
.map(|message| RoomMessage::from_json(message, &authorization, target))
.collect();
chat.queue = state["queue"]
.as_array()
.into_iter()
.flatten()
.map(|item| RoomQueueItem::from_json(item, &authorization, target))
.collect();
chat.has_more = match &state["hasMore"] {
Value::Bool(more) => *more,
Value::Null => false,
Value::Number(more) => more.as_f64().is_some_and(|more| more != 0.0),
Value::String(more) => !more.is_empty(),
_ => true,
};
chat.thinking = state["thinking"] == true;
chat.streaming = stream["turn"]
.as_str()
.filter(|turn| !turn.is_empty())
.map(|turn| StreamingReply {
turn: turn.to_string(),
text: match &stream["text"] {
Value::Null => String::new(),
value => text(value),
},
tools: tool_states(&stream["tools"]),
files: attachments(&stream["files"], &authorization),
});
}
pub fn handle_event(&self, packet: &Value) -> bool {
let data = &packet["data"];
let hooks = self.hooks();
match packet["event"].as_str().unwrap_or_default() {
"chat-message" => {
if !data["message"].is_object() {
return true;
}
let message = RoomMessage::from_json(
&data["message"],
self.get_authorization(),
&self.inner.target,
);
{
let mut chat = self.chat();
if !chat.messages.iter().any(|known| known.id == message.id) {
chat.messages.push(message.clone());
chat.messages.sort_by_key(|message| message.position);
}
if message.role == Role::Model {
chat.streaming = None;
}
}
hooks.on_message(self, &message);
true
}
"chat-queue-add" => {
if !data["item"].is_object() {
return true;
}
let item = RoomQueueItem::from_json(
&data["item"],
self.get_authorization(),
&self.inner.target,
);
{
let mut chat = self.chat();
if !chat.queue.iter().any(|queued| queued.id == item.id) {
chat.queue.push(item);
chat.queue
.sort_by_key(|queued| queued.id.parse::<i128>().unwrap_or_default());
}
}
hooks.on_queue(self);
true
}
"chat-queue-remove" => {
let id = match &data["id"] {
Value::Null => String::new(),
id => text(id),
};
if id.is_empty() {
return true;
}
self.chat().queue.retain(|queued| queued.id != id);
hooks.on_queue(self);
true
}
"chat-delta" => {
let turn = match &data["turn"] {
Value::Null => String::new(),
turn => text(turn),
};
let full = match &data["text"] {
Value::Null => String::new(),
full => text(full),
};
if turn.is_empty() {
return true;
}
let tools = tool_states(&data["tools"]);
let files = attachments(&data["files"], self.get_authorization());
let delta = {
let mut chat = self.chat();
let previous = match &chat.streaming {
Some(streaming) if streaming.turn == turn => streaming.text.clone(),
_ => String::new(),
};
let delta = full
.strip_prefix(previous.as_str())
.unwrap_or(&full)
.to_string();
chat.streaming = Some(StreamingReply {
turn: turn.clone(),
text: full.clone(),
tools: tools.clone(),
files: files.clone(),
});
delta
};
hooks.on_delta(self, &turn, &delta, &full, false, &tools, &files);
true
}
"chat-delta-done" => {
let turn = match &data["turn"] {
Value::Null => String::new(),
turn => text(turn),
};
let done = {
let mut chat = self.chat();
match &chat.streaming {
Some(streaming) if turn.is_empty() || streaming.turn == turn => {
chat.streaming.take()
}
_ => None,
}
};
if let Some(done) = done {
hooks.on_delta(self, &done.turn, "", &done.text, true, &[], &[]);
}
true
}
"chat-status" => {
let thinking = match &data["thinking"] {
Value::Bool(thinking) => *thinking,
Value::Null => false,
Value::Number(thinking) => {
thinking.as_f64().is_some_and(|thinking| thinking != 0.0)
}
Value::String(thinking) => !thinking.is_empty(),
_ => true,
};
self.chat().thinking = thinking;
hooks.on_thinking(self, thinking);
true
}
"chat-renamed" => {
let name = {
let mut chat = self.chat();
if let Some(name) = data["name"].as_str() {
chat.name = name.to_string();
}
chat.name.clone()
};
hooks.on_renamed(self, &name);
true
}
"chat-repository" => {
let renamed = {
let mut chat = self.chat();
match data["name"].as_str() {
Some(name) if name != chat.name => {
chat.name = name.to_string();
Some(name.to_string())
}
_ => None,
}
};
if let Some(name) = renamed {
hooks.on_renamed(self, &name);
}
let repository = data["repository"]
.as_f64()
.filter(|repository| *repository > 0.0)
.map(|repository| repository as u64);
let changed = {
let mut chat = self.chat();
let changed = chat.repository != repository;
chat.repository = repository;
changed
};
if changed {
hooks.on_repository(self);
let watchers: Vec<RepositoryWatcher> = lock(&self.inner.repository_watchers)
.iter()
.map(|(_, listener)| listener.clone())
.collect();
for listener in watchers {
listener(repository);
}
}
true
}
"chat-open-file" => {
let attachment = &data["attachment"];
let repository = &data["repository"];
if !attachment.is_null() {
hooks.on_open_file(
self,
&Target::Attachment(Attachment::from_json(
attachment,
self.get_authorization(),
)),
);
} else if !repository.is_null() {
let file = drive::File::from_json(
repository,
DriveAuthorization::Repository {
authorization: self.get_authorization().clone(),
repository: repository["id"].as_u64().unwrap_or_default(),
path: repository["path"].as_str().unwrap_or_default().to_string(),
group: repository["group"]
.as_str()
.filter(|g| !g.is_empty())
.map(str::to_string),
},
);
hooks.on_open_file(self, &Target::File(file));
}
true
}
"chat-tool-call" => {
let pick = |key: &str| {
if data[key].is_null() {
packet[key].clone()
} else {
data[key].clone()
}
};
let id = match pick("id") {
Value::Null => String::new(),
id => text(&id),
};
let name = match pick("name") {
Value::Null => String::new(),
name => text(&name),
};
let args = match pick("args") {
Value::Object(args) => args,
_ => Map::new(),
};
let turn = match &data["turn"] {
Value::Null | Value::Bool(false) => None,
Value::String(turn) if turn.is_empty() => None,
turn => Some(text(turn)),
};
if id.is_empty() || name.is_empty() {
return true;
}
let tool = lock(&self.inner.client_tools)
.iter()
.find(|tool| tool.function.name == name)
.cloned();
match tool {
Some(tool) => {
let room = self.clone();
tokio::spawn(async move {
let result = match (tool.evaluate)(Value::Object(args)).await {
Ok(result) => result,
Err(error) => format!("Error: {error}"),
};
room.send_tool_result(&id, &result);
});
}
None => hooks.on_tool_call(
self,
&RoomToolCall {
id,
name,
args,
turn,
},
),
}
true
}
"chat-closed" | "server-closed" => {
self.emit_closed();
true
}
_ => false,
}
}
}
fn attachments(json: &Value, authorization: &CredentialsOrApiKey) -> Vec<Attachment> {
json.as_array()
.into_iter()
.flatten()
.map(|raw| Attachment::from_json(raw, authorization))
.collect()
}
struct ChatHooks {
inner: Arc<ChatState>,
}
impl ChatHooks {
fn room(&self, room: &Room) -> ChatRoom {
ChatRoom {
room: room.clone(),
inner: self.inner.clone(),
}
}
}
impl Hooks for ChatHooks {
fn on_connection(&self, room: &Room, state: &Value) {
self.room(room).hydrate(state);
}
fn on_event(&self, room: &Room, packet: &Value) -> bool {
self.room(room).handle_event(packet)
}
fn on_closed(&self, room: &Room, _reason: Option<&str>) {
self.room(room).emit_closed();
}
fn on_presence(&self, room: &Room) {
let room = self.room(room);
room.hooks().on_presence(&room);
}
}
pub async fn connect_room(
authorization: &CredentialsOrApiKey,
target: &ChatTarget,
hooks: Option<Arc<dyn RoomHooks>>,
) -> Result<(ChatRoom, Presence)> {
let auth = match target {
ChatTarget::Code { code } => Authorization::AccessCode {
authorization: authorization.clone(),
access_code: code.clone(),
},
ChatTarget::Reference { reference } => Authorization::Server {
authorization: authorization.clone(),
server: reference.clone(),
group: None,
},
};
let inner = Arc::new(ChatState {
target: target.clone(),
chat: Mutex::new(Chat {
write: true,
..Chat::default()
}),
hooks: Mutex::new(hooks.unwrap_or_else(|| Arc::new(()))),
client_tools: Mutex::new(Vec::new()),
repository_watchers: Mutex::new(Vec::new()),
next_watcher: AtomicU64::new(0),
});
let me = connect(
auth,
&format!("{}/chat/live", super::get_url()),
Arc::new(ChatHooks {
inner: inner.clone(),
}),
)
.await?;
let room = ChatRoom {
room: me.room().clone(),
inner,
};
room.hooks().on_presence(&room);
Ok((room, me))
}
#[cfg(test)]
mod tests {
use std::sync::{Arc, Mutex};
use serde_json::{Value, json};
use tokio::sync::mpsc;
use tokio_tungstenite::tungstenite::Message;
use super::*;
use crate::authentification::ApiKey;
#[derive(Default)]
struct Recorder {
events: Mutex<Vec<String>>,
}
impl Recorder {
fn push(&self, event: String) {
self.events.lock().unwrap().push(event);
}
}
impl RoomHooks for Recorder {
fn on_message(&self, _room: &ChatRoom, message: &RoomMessage) {
self.push(format!("message {}", message.id));
}
fn on_queue(&self, room: &ChatRoom) {
let ids: Vec<String> = room.get_queue().into_iter().map(|item| item.id).collect();
self.push(format!("queue {}", ids.join(",")));
}
fn on_thinking(&self, _room: &ChatRoom, thinking: bool) {
self.push(format!("thinking {thinking}"));
}
fn on_delta(
&self,
_room: &ChatRoom,
turn: &str,
delta: &str,
text: &str,
aborted: bool,
tools: &[RoomToolState],
_files: &[Attachment],
) {
self.push(format!(
"delta {turn} [{delta}] [{text}] {aborted} {}",
tools.len()
));
}
fn on_tool_call(&self, _room: &ChatRoom, call: &RoomToolCall) {
self.push(format!("tool {} {}", call.id, call.name));
}
fn on_renamed(&self, _room: &ChatRoom, name: &str) {
self.push(format!("renamed {name}"));
}
fn on_repository(&self, room: &ChatRoom) {
self.push(format!("repository {:?}", room.repository()));
}
fn on_open_file(&self, _room: &ChatRoom, file: &Target) {
match file {
Target::Attachment(attachment) => {
self.push(format!("open attachment {}", attachment.r#ref))
}
Target::File(file) => match &file.authorization {
DriveAuthorization::Repository {
repository,
path,
group,
..
} => self.push(format!(
"open repository {repository} {path} {group:?} {}",
file.name()
)),
_ => self.push("open file".to_string()),
},
}
}
fn on_closed(&self, _room: &ChatRoom) {
self.push("closed".to_string());
}
}
fn chat_room(recorder: Arc<Recorder>) -> (ChatRoom, mpsc::UnboundedReceiver<Message>) {
let (ws, outbox) = mpsc::unbounded_channel();
let authorization = CredentialsOrApiKey::ApiKey(ApiKey {
id: "key".to_string(),
..ApiKey::default()
});
let room = Room::new(
"http://localhost/chat/live".to_string(),
ws,
Authorization::Server {
authorization,
server: "parrot:chat:9".to_string(),
group: None,
},
"room".to_string(),
);
let inner = Arc::new(ChatState {
target: ChatTarget::Reference {
reference: "parrot:chat:9".to_string(),
},
chat: Mutex::new(Chat {
write: true,
..Chat::default()
}),
hooks: Mutex::new(recorder),
client_tools: Mutex::new(Vec::new()),
repository_watchers: Mutex::new(Vec::new()),
next_watcher: AtomicU64::new(0),
});
(ChatRoom { room, inner }, outbox)
}
fn message(id: &str, position: u32, role: &str) -> Value {
json!({ "id": id, "position": position, "role": role, "parts": [{ "type": "TEXT", "text": id }], "created": 1 })
}
#[test]
fn hydrate_reads_the_connection_snapshot() {
let recorder = Arc::new(Recorder::default());
let (room, _outbox) = chat_room(recorder);
room.hydrate(&json!({
"chat": { "name": "Plans", "systemPrompt": "Be brief", "human": false, "repository": 4, "owner": "group:12", "write": false },
"room": { "reference": "parrot:chat:9" },
"messages": [message("2", 2, "MODEL"), message("1", 1, "USER")],
"queue": [{ "id": "5", "role": "USER", "parts": [], "created": 2 }],
"hasMore": true,
"thinking": true,
"stream": { "turn": "t1", "text": "Half", "tools": [{ "id": "x", "name": "exec", "status": "running" }] }
}));
assert_eq!(room.get_name(), "Plans");
assert_eq!(room.get_system_prompt(), "Be brief");
assert_eq!(room.repository(), Some(4));
assert!(!room.can_write());
assert_eq!(room.chat_id().as_deref(), Some("9"));
assert_eq!(room.group().unwrap().id, "12");
assert_eq!(room.get_messages().len(), 2);
assert_eq!(room.get_queue()[0].id, "5");
assert!(room.has_more());
assert!(room.is_thinking());
let streaming = room.streaming_reply().unwrap();
assert_eq!(streaming.text, "Half");
assert_eq!(streaming.tools[0].status, ToolStatus::Running);
}
#[test]
fn events_update_the_room_and_reach_the_hooks() {
let recorder = Arc::new(Recorder::default());
let (room, mut outbox) = chat_room(recorder.clone());
let seen = Arc::new(Mutex::new(Vec::new()));
let watched = seen.clone();
let stop =
room.watch_repository(move |repository| watched.lock().unwrap().push(repository));
for packet in [
json!({ "event": "chat-status", "data": { "thinking": true } }),
json!({ "event": "chat-delta", "data": { "turn": "t1", "text": "Hel" } }),
json!({ "event": "chat-delta", "data": { "turn": "t1", "text": "Hello", "tools": [{ "id": "x", "name": "exec", "status": "success" }] } }),
json!({ "event": "chat-delta-done", "data": { "turn": "t1" } }),
json!({ "event": "chat-message", "data": { "message": message("3", 3, "MODEL") } }),
json!({ "event": "chat-message", "data": { "message": message("3", 3, "MODEL") } }),
json!({ "event": "chat-queue-add", "data": { "item": { "id": "10", "role": "USER", "parts": [] } } }),
json!({ "event": "chat-queue-add", "data": { "item": { "id": "9", "role": "USER", "parts": [] } } }),
json!({ "event": "chat-queue-remove", "data": { "id": "10" } }),
json!({ "event": "chat-repository", "data": { "repository": 7, "name": "Build" } }),
json!({ "event": "chat-tool-call", "data": { "id": "c1", "name": "pick", "args": {} } }),
json!({ "event": "chat-closed" }),
] {
assert!(room.handle_event(&packet));
}
stop();
room.handle_event(&json!({ "event": "chat-repository", "data": { "repository": 0 } }));
assert!(!room.handle_event(&json!({ "event": "something-else" })));
assert_eq!(
*recorder.events.lock().unwrap(),
vec![
"thinking true",
"delta t1 [Hel] [Hel] false 0",
"delta t1 [lo] [Hello] false 1",
"delta t1 [] [Hello] true 0",
"message 3",
"message 3",
"queue 10",
"queue 9,10",
"queue 9",
"renamed Build",
"repository Some(7)",
"tool c1 pick",
"closed",
"repository None",
]
);
assert_eq!(room.get_messages().len(), 1);
assert_eq!(*seen.lock().unwrap(), vec![Some(7)]);
room.send_tool_result("c1", "a");
let Some(Message::Text(frame)) = outbox.blocking_recv() else {
panic!("expected a frame");
};
assert_eq!(
serde_json::from_str::<Value>(frame.as_str()).unwrap(),
json!({ "event": "tool-result", "id": "c1", "result": "a" })
);
}
#[test]
fn opened_files_are_attachments_or_live_repository_files() {
let recorder = Arc::new(Recorder::default());
let (room, _outbox) = chat_room(recorder.clone());
room.handle_event(&json!({ "event": "chat-open-file", "data": { "attachment": { "type": "FILE", "ref": "r1", "name": "a.png", "contentType": "image/png", "chat": "9" } } }));
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 } } }));
assert_eq!(
*recorder.events.lock().unwrap(),
vec![
"open attachment r1",
"open repository 41 /repository/src/a.ts Some(\"7\") a.ts",
]
);
}
}