use std::collections::{HashMap, VecDeque};
use std::ops::Deref;
use std::sync::atomic::{AtomicU64, Ordering};
use std::sync::{Arc, Mutex, MutexGuard, PoisonError, Weak};
use chrono::{DateTime, Utc};
use futures_util::stream::{self, BoxStream};
use futures_util::{SinkExt, StreamExt};
use serde::{Deserialize, Serialize};
use serde_json::{Map, Value, json};
use tokio::sync::mpsc;
use tokio_tungstenite::tungstenite::Message;
use super::persona::Identity;
use crate::authentification::{CredentialsOrApiKey, Profile};
use crate::drive::{self, FileDates};
use crate::error::{Error, Result};
use crate::groups::Group;
use crate::http::{client, encode, ok, websocket};
use crate::parrot::agent::Memory;
use crate::parrot::generative::{Content, Part, StreamEvent, Tool, file_ref};
use crate::parrot::room::{ChatRoom as ParrotChatRoom, RoomHooks, connect_room};
use crate::parrot::share::ChatTarget;
use crate::shared::server::{Authorization, Hooks, Presence, Room, connect as connect_server};
use crate::termite::versioning::Repository;
pub(crate) async fn serialize_messages(
authorization: &CredentialsOrApiKey,
messages: &[Content],
) -> Result<Vec<Value>> {
let mut out = Vec::with_capacity(messages.len());
for message in messages {
let mut parts = Vec::with_capacity(message.parts.len());
for part in &message.parts {
match part {
Part::File(part) if !part.file.online() => {
let file = &part.file;
let dest = format!("tmp/{}-{}", uuid::Uuid::new_v4(), file.name());
let bytes = file.clone().download(false, None).await?;
let mut ready = drive::from_bytes(
authorization.clone(),
&dest,
&file.content_type,
bytes,
FileDates::default(),
);
ready.upload(None).await?;
parts.push(file_ref(&ready));
}
part => parts.push(part.wire()),
}
}
out.push(json!({ "parts": parts, "role": message.role }));
}
Ok(out)
}
pub(crate) async fn agent_stream(
url: String,
generate: Value,
tools: Vec<Tool>,
) -> Result<BoxStream<'static, StreamEvent>> {
let socket = match tokio_tungstenite::connect_async(url.as_str()).await {
Ok((socket, _)) => socket,
Err(_) => return Err(Error::Message("WebSocket connection failed".to_string())),
};
let (mut write, read) = socket.split();
write.send(Message::text(generate.to_string())).await?;
write
.send(Message::text(json!({ "event": "start" }).to_string()))
.await?;
let (outbox, mut queue) = mpsc::unbounded_channel::<Message>();
tokio::spawn(async move {
while let Some(message) = queue.recv().await {
if write.send(message).await.is_err() {
break;
}
}
let _ = write.close().await;
});
let state = (read, outbox, tools, VecDeque::<StreamEvent>::new(), false);
Ok(stream::unfold(state, |(mut read, outbox, tools, mut queue, finished)| async move {
if finished {
return None;
}
loop {
if let Some(event) = queue.pop_front() {
let finished = matches!(event, StreamEvent::Done { .. } | StreamEvent::Error { .. });
return Some((event, (read, outbox, tools, queue, finished)));
}
match read.next().await {
Some(Ok(Message::Text(raw))) => {
let Ok(packet) = serde_json::from_str::<Value>(raw.as_str()) else {
continue;
};
if packet["event"] == "tool_call" {
let tool = tools
.iter()
.find(|tool| packet["name"].as_str() == Some(tool.function.name.as_str()))
.cloned();
let outbox = outbox.clone();
tokio::spawn(async move {
let declined = json!({ "declined": true }).to_string();
let result = match tool {
Some(tool) => {
let args = match &packet["args"] {
Value::Object(args) => Value::Object(args.clone()),
_ => json!({}),
};
(tool.evaluate)(args).await.unwrap_or(declined)
}
None => declined,
};
let _ = outbox.send(Message::text(
json!({ "event": "tool_result", "id": packet["id"], "result": result }).to_string(),
));
});
continue;
}
if let Ok(event) = serde_json::from_value::<StreamEvent>(packet) {
queue.push_back(event);
}
}
Some(Ok(Message::Close(_))) | Some(Err(_)) | None => return None,
Some(Ok(_)) => {}
}
}
})
.boxed())
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct ChatLast {
#[serde(default)]
pub parts: Vec<Value>,
pub role: String,
#[serde(
deserialize_with = "crate::http::deserialize_date",
serialize_with = "crate::http::serialize_date"
)]
pub created_at: DateTime<Utc>,
pub position: u32,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub author: Option<Profile>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub model: Option<String>,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ChatEntry {
pub name: String,
pub id: String,
#[serde(default)]
pub last: Option<ChatLast>,
}
#[derive(Debug, Clone, Default)]
pub struct GroupOptions {
pub group: Option<Group>,
}
fn authorized(
request: reqwest::RequestBuilder,
authorization: &CredentialsOrApiKey,
group: Option<&Group>,
) -> reqwest::RequestBuilder {
let request = request.header(
"Authorization",
match authorization {
CredentialsOrApiKey::Credentials(credentials) => format!("Token {}", credentials.token),
CredentialsOrApiKey::ApiKey(key) => format!("ApiKey {}", key.id),
},
);
match group {
Some(group) => request.header("Group", &group.id),
None => request,
}
}
pub async fn list_chats(
authorization: &CredentialsOrApiKey,
opts: GroupOptions,
) -> Result<Vec<ChatEntry>> {
let response = authorized(
client().get(format!("{}/chats", super::get_url())),
authorization,
opts.group.as_ref(),
)
.send()
.await?;
let rows: Value = ok(response).await?.json().await?;
Ok(rows
.as_array()
.into_iter()
.flatten()
.filter_map(|row| serde_json::from_value(row.clone()).ok())
.collect())
}
#[derive(Debug, Clone, Default)]
pub struct CreateChatOptions {
pub group: Option<Group>,
pub audience: Option<Vec<String>>,
pub repository: Option<Repository>,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct CreatedChat {
pub name: String,
pub id: String,
}
pub async fn create_chat(
authorization: &CredentialsOrApiKey,
name: &str,
opts: CreateChatOptions,
) -> Result<CreatedChat> {
let mut body = Map::new();
body.insert("name".to_string(), Value::from(name));
if let Some(audience) = opts.audience.filter(|audience| !audience.is_empty()) {
body.insert("audience".to_string(), json!(audience));
}
if let Some(repository) = &opts.repository {
body.insert("repository".to_string(), Value::from(repository.id));
}
let response = authorized(
client().post(format!("{}/chats", super::get_url())),
authorization,
opts.group.as_ref(),
)
.json(&body)
.send()
.await?;
Ok(ok(response).await?.json().await?)
}
pub async fn delete_chat(
authorization: &CredentialsOrApiKey,
id: &str,
opts: GroupOptions,
) -> Result<()> {
let response = authorized(
client().delete(format!("{}/chat", super::get_url())),
authorization,
opts.group.as_ref(),
)
.header("Chat", id)
.send()
.await?;
ok(response).await?;
Ok(())
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct MovedChat {
pub id: String,
pub name: String,
pub group_id: String,
pub remapped: bool,
}
pub async fn move_chat_to_group(
authorization: &CredentialsOrApiKey,
id: &str,
group_id: &str,
) -> Result<MovedChat> {
let response = authorized(
client().post(format!("{}/chat/move", super::get_url())),
authorization,
None,
)
.header("Chat", id)
.json(&json!({ "groupId": group_id }))
.send()
.await?;
Ok(ok(response).await?.json().await?)
}
pub async fn rename_chat(
authorization: &CredentialsOrApiKey,
id: &str,
name: &str,
opts: GroupOptions,
) -> Result<()> {
let response = authorized(
client().post(format!("{}/chat/rename", super::get_url())),
authorization,
opts.group.as_ref(),
)
.header("Chat", id)
.json(&json!({ "name": name }))
.send()
.await?;
ok(response).await?;
Ok(())
}
#[derive(Debug, Clone, Default)]
pub struct AgentGenerateOptions {
pub tools: Option<Vec<Tool>>,
}
#[derive(Clone)]
pub struct Agent {
room: Room,
parent: Weak<AntChatState>,
pub id: String,
pub persona: Identity,
pub repository: Option<u64>,
}
impl Agent {
pub fn parent(&self) -> Option<AntChatRoom> {
self.parent.upgrade().map(|state| AntChatRoom {
room: self.room.clone(),
state,
})
}
pub fn set_repository(&self, repository: Option<&Repository>) {
self.room.post(&json!({
"event": "set-agent-repository",
"agentId": self.id,
"repository": repository.map(|repository| repository.id),
}));
}
fn chat_id(&self) -> String {
self.parent().map(|room| room.chat_id()).unwrap_or_default()
}
fn access(&self) -> (Option<Group>, Option<String>) {
match self.room.authorization() {
Authorization::AccessCode { access_code, .. } => (None, Some(access_code.clone())),
Authorization::Server { group, .. } => (
group
.as_ref()
.map(|group| Group::from_json(&json!({ "id": group }))),
None,
),
}
}
pub async fn observe(&self, content: &str) -> Result<Memory> {
let (group, access_code) = self.access();
observe_agent(
self.room.get_authorization(),
&self.chat_id(),
&self.id,
content,
AgentOptions { group, access_code },
)
.await
}
pub async fn generate(
&self,
messages: &[Content],
opts: AgentGenerateOptions,
) -> Result<BoxStream<'static, StreamEvent>> {
let (group, access_code) = self.access();
generate_agent(
self.room.get_authorization(),
&self.chat_id(),
&self.id,
messages,
GenerateOptions {
group,
access_code,
tools: opts.tools,
},
)
.await
}
pub fn to_json(&self) -> Value {
json!({ "id": self.id, "persona": self.persona })
}
pub fn from_json(json: &Value, parent: &AntChatRoom) -> Option<Agent> {
Some(Agent {
room: parent.room.clone(),
parent: Arc::downgrade(&parent.state),
id: match &json["id"] {
Value::String(id) => id.clone(),
id => id.to_string(),
},
persona: serde_json::from_value(json["persona"].clone()).ok()?,
repository: json["repository"]
.as_f64()
.filter(|repository| *repository > 0.0)
.map(|repository| repository as u64),
})
}
}
type RepositoryWatcher = Arc<dyn Fn(Option<u64>) + Send + Sync>;
#[derive(Default)]
struct AntChat {
chat_id: String,
name: String,
agents: HashMap<String, Agent>,
repository: Option<u64>,
owner: String,
}
struct AntChatState {
chat: Mutex<AntChat>,
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 ArchitectChat {
pub room: ParrotChatRoom,
pub me: Presence,
pub chat_id: String,
}
#[derive(Default)]
pub struct ConnectOptions {
pub group: Option<Group>,
pub hooks: Option<Arc<dyn Hooks>>,
pub server: Option<String>,
}
#[derive(Clone)]
pub struct AntChatRoom {
room: Room,
state: Arc<AntChatState>,
}
pub use self::AntChatRoom as ChatRoom;
impl Deref for AntChatRoom {
type Target = Room;
fn deref(&self) -> &Room {
&self.room
}
}
fn positive(value: &Value) -> Option<u64> {
value
.as_f64()
.filter(|repository| *repository > 0.0)
.map(|repository| repository as u64)
}
impl AntChatRoom {
fn chat(&self) -> MutexGuard<'_, AntChat> {
lock(&self.state.chat)
}
pub fn chat_id(&self) -> String {
self.chat().chat_id.clone()
}
pub fn name(&self) -> String {
self.chat().name.clone()
}
pub fn agents(&self) -> HashMap<String, Agent> {
self.chat().agents.clone()
}
pub fn repository(&self) -> Option<u64> {
self.chat().repository
}
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<()> {
self.post(&json!({ "event": "set-repository", "repository": repository.map(|repository| repository.id) }));
Ok(())
}
pub fn watch_repository(
&self,
listener: impl Fn(Option<u64>) + Send + Sync + 'static,
) -> Box<dyn FnOnce() + Send + Sync> {
let id = self.state.next_watcher.fetch_add(1, Ordering::Relaxed);
lock(&self.state.watchers).push((id, Arc::new(listener)));
let state = Arc::downgrade(&self.state);
Box::new(move || {
if let Some(state) = state.upgrade() {
lock(&state.watchers).retain(|(other, _)| *other != id);
}
})
}
fn apply_repository(&self, raw: &Value) {
let repository = positive(raw);
{
let mut chat = self.chat();
if chat.repository == repository {
return;
}
chat.repository = repository;
}
let watchers: Vec<RepositoryWatcher> = lock(&self.state.watchers)
.iter()
.map(|(_, listener)| listener.clone())
.collect();
for listener in watchers {
listener(repository);
}
}
pub fn hydrate(&self, state: &Value) {
{
let mut chat = self.chat();
if let Some(id) = state["id"].as_str() {
chat.chat_id = id.to_string();
}
if let Some(name) = state["name"].as_str() {
chat.name = name.to_string();
}
if let Some(owner) = state["owner"].as_str() {
chat.owner = owner.to_string();
}
}
self.apply_repository(&state["repository"]);
let agents: HashMap<String, Agent> = state["agents"]
.as_array()
.into_iter()
.flatten()
.filter_map(|agent| Agent::from_json(agent, self))
.map(|agent| (agent.id.clone(), agent))
.collect();
self.chat().agents = agents;
}
pub fn handle_event(&self, packet: &Value) -> bool {
let pick = |key: &str| {
if packet["data"][key].is_null() {
&packet[key]
} else {
&packet["data"][key]
}
};
match packet["event"].as_str().unwrap_or_default() {
"upsert-agent" => {
if let Some(agent) = Agent::from_json(pick("agent"), self) {
self.chat().agents.insert(agent.id.clone(), agent);
}
true
}
"remove-agent" => {
let id = match pick("id") {
Value::Null => String::new(),
Value::String(id) => id.clone(),
id => id.to_string(),
};
if !id.is_empty() {
self.chat().agents.remove(&id);
}
true
}
"update-chat" => {
let chat = pick("chat");
if let Some(name) = chat["name"].as_str() {
self.chat().name = name.to_string();
}
if chat.get("repository").is_some() {
self.apply_repository(&chat["repository"]);
}
true
}
_ => false,
}
}
pub fn upsert_agent(&self, identity: Identity) -> Agent {
let agent = {
let mut chat = self.chat();
let preferred = identity.id.trim().to_string();
let id = if !preferred.is_empty() && !chat.agents.contains_key(&preferred) {
preferred
} else {
let mut n = 0;
while chat.agents.contains_key(&n.to_string()) {
n += 1;
}
n.to_string()
};
let agent = Agent {
room: self.room.clone(),
parent: Arc::downgrade(&self.state),
id,
persona: identity,
repository: None,
};
chat.agents.insert(agent.id.clone(), agent.clone());
agent
};
self.post(&json!({ "event": "upsert-agent", "agent": agent.to_json() }));
agent
}
pub fn remove_agent(&self, id: &str) {
self.chat().agents.remove(id);
self.post(&json!({ "event": "remove-agent", "id": id }));
}
pub async fn get_chat(&self, hooks: Option<Arc<dyn RoomHooks>>) -> Result<ArchitectChat> {
let authorization = self.get_authorization();
let request = authorized(
client().post(format!("{}/chat/ensure", super::get_url())),
authorization,
None,
);
let request = match self.authorization() {
Authorization::AccessCode { access_code, .. } => {
request.header("Access-Code", access_code)
}
Authorization::Server { group, .. } => {
let request = request.header("Chat", self.chat_id());
match group {
Some(group) => request.header("Group", group),
None => request,
}
}
};
let json: Value = ok(request.json(&json!({})).send().await?)
.await?
.json()
.await?;
let chat_id = json["chatId"].as_str().unwrap_or_default().to_string();
let code = json["code"].as_str().unwrap_or_default().to_string();
if chat_id.is_empty() || code.is_empty() {
return Err(Error::Message("Invalid ensure response.".to_string()));
}
let target = match self.authorization() {
Authorization::AccessCode { .. } => ChatTarget::Code { code },
Authorization::Server { .. } => ChatTarget::Reference {
reference: json["reference"]
.as_str()
.filter(|reference| !reference.is_empty())
.map(str::to_string)
.unwrap_or_else(|| format!("parrot:chat:{chat_id}")),
},
};
let (room, me) = connect_room(authorization, &target, hooks).await?;
Ok(ArchitectChat { room, me, chat_id })
}
pub async fn connect(
authorization: &CredentialsOrApiKey,
target_id: &str,
opts: ConnectOptions,
) -> Result<(AntChatRoom, Presence)> {
AntChatRoom::open(
Authorization::Server {
authorization: authorization.clone(),
server: opts.server.unwrap_or_else(|| target_id.to_string()),
group: opts.group.as_ref().map(|group| group.id.clone()),
},
opts.hooks,
)
.await
}
pub async fn join(
authorization: &CredentialsOrApiKey,
access_code: &str,
hooks: Option<Arc<dyn Hooks>>,
) -> Result<(AntChatRoom, Presence)> {
AntChatRoom::open(
Authorization::AccessCode {
authorization: authorization.clone(),
access_code: access_code.to_string(),
},
hooks,
)
.await
}
async fn open(
auth: Authorization,
hooks: Option<Arc<dyn Hooks>>,
) -> Result<(AntChatRoom, Presence)> {
let state = Arc::new(AntChatState {
chat: Mutex::new(AntChat::default()),
watchers: Mutex::new(Vec::new()),
next_watcher: AtomicU64::new(0),
});
let me = connect_server(
auth,
&format!("{}/chat", super::get_url()),
Arc::new(AntChatHooks {
state: state.clone(),
user: hooks.unwrap_or_else(|| Arc::new(())),
}),
)
.await?;
Ok((
AntChatRoom {
room: me.room().clone(),
state,
},
me,
))
}
}
struct AntChatHooks {
state: Arc<AntChatState>,
user: Arc<dyn Hooks>,
}
impl AntChatHooks {
fn room(&self, room: &Room) -> AntChatRoom {
AntChatRoom {
room: room.clone(),
state: self.state.clone(),
}
}
}
impl Hooks for AntChatHooks {
fn create_room(&self, room: &Room, state: &Value) {
lock(&self.state.chat).chat_id = room.id().to_string();
self.user.create_room(room, state);
}
fn create_presence(&self, room: &Room, presence: &Presence) {
self.user.create_presence(room, presence);
}
fn remove_presence(&self, room: &Room, presence: &Presence) {
self.user.remove_presence(room, presence);
}
fn on_connection(&self, room: &Room, state: &Value) {
self.room(room).hydrate(state);
self.user.on_connection(room, state);
}
fn on_event(&self, room: &Room, packet: &Value) -> bool {
let handled = self.room(room).handle_event(packet);
self.user.on_event(room, packet) || handled
}
fn on_presence(&self, room: &Room) {
self.user.on_presence(room);
}
fn on_closed(&self, room: &Room, reason: Option<&str>) {
self.user.on_closed(room, reason);
}
}
#[derive(Debug, Clone, Default)]
pub struct AgentOptions {
pub group: Option<Group>,
pub access_code: Option<String>,
}
fn scoped(
request: reqwest::RequestBuilder,
chat_id: &str,
group: Option<&Group>,
access_code: Option<&str>,
) -> reqwest::RequestBuilder {
match access_code.filter(|code| !code.is_empty()) {
Some(access_code) => request.header("Access-Code", access_code),
None => {
let request = request.header("Chat", chat_id);
match group {
Some(group) => request.header("Group", &group.id),
None => request,
}
}
}
}
pub async fn observe_agent(
authorization: &CredentialsOrApiKey,
chat_id: &str,
agent_id: &str,
content: &str,
opts: AgentOptions,
) -> Result<Memory> {
let request = authorized(
client().post(format!("{}/chat/agent/observe", super::get_url())),
authorization,
None,
);
let response = scoped(
request,
chat_id,
opts.group.as_ref(),
opts.access_code.as_deref(),
)
.json(&json!({ "agentId": agent_id, "content": content }))
.send()
.await?;
Ok(ok(response).await?.json().await?)
}
#[derive(Debug, Clone, Default)]
pub struct GenerateOptions {
pub group: Option<Group>,
pub access_code: Option<String>,
pub tools: Option<Vec<Tool>>,
}
pub(crate) fn socket_auth(
authorization: &CredentialsOrApiKey,
chat_header: (&str, &str),
group: Option<&Group>,
access_code: Option<&str>,
) -> String {
let mut headers = Map::new();
headers.insert(
"Authorization".to_string(),
Value::from(match authorization {
CredentialsOrApiKey::Credentials(credentials) => format!("Token {}", credentials.token),
CredentialsOrApiKey::ApiKey(key) => format!("ApiKey {}", key.id),
}),
);
match access_code.filter(|code| !code.is_empty()) {
Some(access_code) => {
headers.insert("Access-Code".to_string(), Value::from(access_code));
}
None => {
headers.insert(chat_header.0.to_string(), Value::from(chat_header.1));
if let Some(group) = group {
headers.insert("Group".to_string(), Value::from(group.id.as_str()));
}
}
}
encode(&Value::Object(headers).to_string())
}
pub async fn generate_agent(
authorization: &CredentialsOrApiKey,
chat_id: &str,
agent_id: &str,
messages: &[Content],
opts: GenerateOptions,
) -> Result<BoxStream<'static, StreamEvent>> {
let auth = socket_auth(
authorization,
("Chat", chat_id),
opts.group.as_ref(),
opts.access_code.as_deref(),
);
let url = format!(
"{}/chat/agent/generate?authorization={auth}",
websocket(&super::get_url())
);
let tools = opts.tools.unwrap_or_default();
let messages = serialize_messages(authorization, messages).await?;
let functions: Vec<&crate::parrot::generative::Function> =
tools.iter().map(|tool| &tool.function).collect();
let generate = json!({ "event": "generate", "agentId": agent_id, "messages": messages, "tools": functions });
agent_stream(url, generate, tools).await
}
#[cfg(test)]
mod tests {
use serde_json::{Value, json};
use tokio::sync::mpsc;
use super::*;
use crate::authentification::ApiKey;
fn persona(id: &str) -> Value {
json!({
"id": id, "background": "Nurse", "dialect": "Southern",
"demographic": {
"age": 30, "sex": "MALE", "race": "BLACK", "ethnicity": [], "religion": "CHRISTIAN",
"birthplace": [0, 0], "location": [0, 0], "marital": "MARRIED", "education": "BACHELOR",
"occupation": "nurse", "income": 60000
}
})
}
#[test]
fn ant_chat_rooms_track_agents_and_repository() {
let (ws, mut outbox) = mpsc::unbounded_channel();
let room = AntChatRoom {
room: Room::new(
"http://localhost/chat".to_string(),
ws,
Authorization::Server {
authorization: CredentialsOrApiKey::ApiKey(ApiKey::default()),
server: "c1".to_string(),
group: None,
},
"c1".to_string(),
),
state: Arc::new(AntChatState {
chat: Mutex::new(AntChat::default()),
watchers: Mutex::new(Vec::new()),
next_watcher: AtomicU64::new(0),
}),
};
let seen = Arc::new(Mutex::new(Vec::new()));
let sink = seen.clone();
let _stop = room.watch_repository(move |repository| sink.lock().unwrap().push(repository));
room.hydrate(&json!({
"id": "c1", "name": "Panel", "owner": "group:5", "repository": 9,
"agents": [{ "id": "0", "persona": persona("p0"), "repository": 3 }, { "id": "bad" }]
}));
assert_eq!(room.group().unwrap().id, "5");
assert_eq!(room.agents().len(), 1);
assert_eq!(room.agents()["0"].repository, Some(3));
assert_eq!(room.agents()["0"].parent().unwrap().chat_id(), "c1");
let identity: Identity = serde_json::from_value(persona("0")).unwrap();
let agent = room.upsert_agent(identity);
assert_eq!(agent.id, "1");
let Some(Message::Text(frame)) = outbox.blocking_recv() else {
panic!("expected a frame");
};
assert_eq!(
serde_json::from_str::<Value>(frame.as_str()).unwrap()["event"],
"upsert-agent"
);
assert!(room.handle_event(&json!({ "event": "remove-agent", "data": { "id": "0" } })));
assert!(room.handle_event(
&json!({ "event": "update-chat", "chat": { "name": "Jury", "repository": null } })
));
assert_eq!(room.agents().len(), 1);
assert_eq!(room.name(), "Jury");
assert_eq!(*seen.lock().unwrap(), vec![Some(9), None]);
}
}