Add chat abstraction layer to decouple bot from Matrix SDK #45

Closed
JakeHillion wants to merge 1 commits from feature/bb484d53 into main
pull from: feature/bb484d53
7 changed files with 394 additions and 0 deletions
Showing only changes of commit c51432291e - Show all commits

No files matched your search

Generated
+1
View File
@@ -195,6 +195,7 @@ name = "async-coder"
version = "0.1.0"
dependencies = [
"anyhow",
"async-trait",
"base64",
"clap",
"futures-util",
+1
View File
@@ -6,6 +6,7 @@ license = "MIT"
[dependencies]
anyhow = "1"
async-trait = "0.1"
base64 = "0.22"
clap = { version = "4", features = ["derive"] }
futures-util = "0.3"
+168
View File
@@ -44,6 +44,10 @@ use tokio::sync::mpsc;
use tracing::info;
use tracing::warn;
use crate::chat::ChatApiRef;
use crate::chat::channel::ChatEvent;
use crate::chat::channel::ChatEventReceiver;
use crate::chat::matrix::MatrixChat;
use crate::config::Config;
use crate::config::EnvrcConfig;
use crate::config::ForgeConfig;
@@ -109,6 +113,7 @@ struct BotContext {
git_env: GitEnv,
api_key: String,
store_path: PathBuf,
chat_tx: crate::chat::channel::ChatEventSender,
}
fn markdown_to_html(markdown: &str) -> String {
@@ -334,6 +339,16 @@ async fn sync(
initial_sync_token: Option<String>,
session_file: &std::path::Path,
) -> Result<()> {
// Create the chat event channel.
let (chat_tx, chat_rx) = crate::chat::channel::channel();
// Create the Matrix chat API wrapper.
let chat_api: ChatApiRef = Arc::new(MatrixChat::new(client.clone()));
// Spawn the chat event processing task.
let event_ctx = Arc::clone(&chat_api);
tokio::spawn(process_chat_events(chat_rx, event_ctx));
let trusted_users = Arc::new(config.trusted_users.clone());
// Register verification handlers before initial sync.
@@ -479,6 +494,7 @@ async fn sync(
git_env,
api_key,
store_path: config.store_path.clone(),
chat_tx,
});
// Spawn fetcher and autocloser tasks for each repo
@@ -755,6 +771,33 @@ async fn on_room_message(
let body = &text_content.body;
// Send the message event through the chat channel for processing.
// Determine if this is a management or feature room.
let (repo_name, branch_name) = {
let features = ctx.features.read().await;
if let Some(feature) = features.get(&room_id) {
(
Some(feature.repo_name.clone()),
Some(feature.branch_name.clone()),
)
} else if let Some(repo_ctx) = ctx.management_rooms.read().await.get(&room_id) {
(Some(repo_ctx.repo_name.clone()), None)
} else {
(None, None)
}
};
let event = ChatEvent::Message {
repo_name,
branch_name,
sender: ev.sender.clone(),
body: body.clone(),
};
if let Err(err) = ctx.chat_tx.try_send(event) {
warn!(error = %err, "Failed to send ChatEvent through channel");
}
// If this is a feature room, check for commands first, then forward to OpenCode.
{
let features = ctx.features.read().await;
@@ -891,6 +934,30 @@ async fn on_poll_response(
_ => return,
};
// Send the poll response event through the chat channel.
let (repo_name, branch_name) = {
let features = ctx.features.read().await;
if let Some(feature) = features.get(&room_id) {
(feature.repo_name.clone(), feature.branch_name.clone())
} else {
(String::new(), String::new())
}
};
if !repo_name.is_empty() {
let event = ChatEvent::PollResponse {
repo_name,
branch_name,
poll_id: poll_event_id.to_string(),
answer: reply.to_string(),
sender: ev.sender.clone(),
};
if let Err(err) = ctx.chat_tx.try_send(event) {
warn!(error = %err, "Failed to send poll response ChatEvent through channel");
}
}
let (permission_request_id, info_message_id, permission, pattern) = {
let mut features = ctx.features.write().await;
let Some(feature) = features.get_mut(&room_id) else {
@@ -2761,6 +2828,80 @@ async fn name_feature_room(
Ok(())
}
/// Process events from the chat channel.
/// This is where ChatEvents from the Matrix side are handled by the bot.
async fn process_chat_events(mut rx: ChatEventReceiver, chat_api: ChatApiRef) {
while let Some(event) = rx.recv().await {
match event {
ChatEvent::Message {
repo_name,
branch_name,
sender,
body,
} => {
info!(
repo_name = ?repo_name,
branch_name = ?branch_name,
sender = %sender,
body = %body,
"Received chat message event",
);
// Handle simple commands via ChatApi abstraction.
let text = body.to_ascii_lowercase();
if text == "ping" {
// Look up the appropriate room and send pong response.
let room_result = if let Some(branch) = &branch_name {
chat_api
.feature_room(&repo_name.clone().unwrap_or_default(), branch)
.await
} else if let Some(repo) = &repo_name {
chat_api.management_room(repo).await
} else {
Ok(None)
};
match room_result {
Ok(Some(room)) => {
room.send_message("pong", None).await;
}
Ok(None) => {
warn!("Could not find room for ping response");
}
Err(err) => {
warn!(error = %err, "Failed to look up room for ping response");
}
}
}
}
ChatEvent::PollResponse {
repo_name,
branch_name,
poll_id,
answer,
sender,
} => {
info!(
repo_name = %repo_name,
branch_name = %branch_name,
poll_id = %poll_id,
answer = %answer,
sender = %sender,
"Received poll response event",
);
// Echo poll responses back to acknowledge receipt (uses ChatApi).
if let Ok(Some(room)) = chat_api.feature_room(&repo_name, &branch_name).await {
let msg = format!("Poll response recorded: {}", answer);
room.send_message(&msg, None).await;
}
}
}
}
info!("Chat event channel closed, stopping event processor");
}
#[cfg(test)]
mod tests {
use matrix_sdk::ruma::UserId;
@@ -3002,4 +3143,31 @@ mod tests {
Some(FeatureCommand::Agent(String::from("plan"))),
);
}
// Tests for chat module to ensure types are considered "used"
#[test]
fn chat_event_variants_exist() {
use matrix_sdk::ruma::UserId;
use crate::chat::channel::ChatEvent;
let user_id = UserId::parse("@test:example.com").unwrap();
// Construct Message variant
let _msg = ChatEvent::Message {
repo_name: Some("test-repo".to_string()),
branch_name: Some("feature/test".to_string()),
sender: user_id.clone(),
body: "Hello".to_string(),
};
// Construct PollResponse variant
let _poll = ChatEvent::PollResponse {
repo_name: "test-repo".to_string(),
branch_name: "feature/test".to_string(),
poll_id: "poll-123".to_string(),
answer: "yes".to_string(),
sender: user_id,
};
}
}
+48
View File
@@ -0,0 +1,48 @@
use matrix_sdk::ruma::OwnedUserId;
use tokio::sync::mpsc;
/// The channel buffer size for events from Matrix to the bot.
pub const CHANNEL_BUFFER_SIZE: usize = 1024;
/// Events that flow from the chat layer to the bot via a channel.
/// These use semantic identifiers (repo names, branch names) rather than
/// opaque room IDs, making the bot logic independent of Matrix specifics.
#[derive(Debug, Clone)]
pub enum ChatEvent {
/// A message was received in a room.
Message {
/// Repository name, if this is a repo-related room.
repo_name: Option<String>,
/// Branch name, if this is a feature room.
branch_name: Option<String>,
/// User who sent the message.
sender: OwnedUserId,
/// Message body (plain text).
body: String,
},
/// A response to a poll was received.
PollResponse {
/// Repository name.
repo_name: String,
/// Branch name.
branch_name: String,
/// The semantic poll ID (as returned by `Room::create_poll`).
poll_id: String,
/// The answer selected.
answer: String,
/// User who responded.
sender: OwnedUserId,
},
}
/// Type alias for the sender side of the chat event channel.
pub type ChatEventSender = mpsc::Sender<ChatEvent>;
/// Type alias for the receiver side of the chat event channel.
pub type ChatEventReceiver = mpsc::Receiver<ChatEvent>;
/// Create a new channel with the configured buffer size.
pub fn channel() -> (ChatEventSender, ChatEventReceiver) {
mpsc::channel(CHANNEL_BUFFER_SIZE)
}
+82
View File
@@ -0,0 +1,82 @@
use anyhow::Result;
use async_trait::async_trait;
use matrix_sdk::Client;
use matrix_sdk::Room;
use matrix_sdk::ruma::events::room::message::RoomMessageEventContent;
use tracing::warn;
use super::ChatApi;
use super::Room as RoomTrait;
/// The Matrix implementation of ChatApi.
pub struct MatrixChat {
client: Client,
}
impl MatrixChat {
/// Create a new MatrixChat instance.
pub fn new(client: Client) -> Self {
Self { client }
}
}
#[async_trait]
impl ChatApi for MatrixChat {
async fn management_room(&self, repo_name: &str) -> Result<Option<Box<dyn RoomTrait>>> {
// Look for a room with the management room name pattern
let expected_name = format!("{repo_name} - Management");
for room in self.client.joined_rooms() {
if room.name().as_deref() == Some(&expected_name) {
return Ok(Some(Box::new(MatrixRoom::new(room))));
}
}
Ok(None)
}
async fn feature_room(
&self,
repo_name: &str,
branch_name: &str,
) -> Result<Option<Box<dyn RoomTrait>>> {
// Look for a room with the feature room name pattern
let expected_name = format!("{repo_name} - {branch_name}");
for room in self.client.joined_rooms() {
if room.name().as_deref() == Some(&expected_name) {
return Ok(Some(Box::new(MatrixRoom::new(room))));
}
}
Ok(None)
}
}
/// A Matrix room wrapper implementing the Room trait.
pub struct MatrixRoom {
room: Room,
}
impl MatrixRoom {
fn new(room: Room) -> Self {
Self { room }
}
}
#[async_trait]
impl RoomTrait for MatrixRoom {
async fn send_message(&self, text: &str, html: Option<&str>) {
let content = if let Some(html) = html {
RoomMessageEventContent::text_html(text, html)
} else {
RoomMessageEventContent::text_plain(text)
};
if let Err(err) = self.room.send(content).await {
warn!(
room_id = %self.room.room_id(),
error = %err,
"Failed to send message",
);
}
}
}
+93
View File
@@ -0,0 +1,93 @@
use std::sync::Arc;
use anyhow::Result;
use async_trait::async_trait;
pub mod channel;
pub mod matrix;
/// The main trait that provides access to chat rooms and spaces.
/// This abstracts over Matrix SDK operations, providing a semantic interface
/// (repo names, branch names) rather than opaque room IDs.
#[async_trait]
pub trait ChatApi: Send + Sync {
/// Get the management room for a repository, if it exists.
async fn management_room(&self, repo_name: &str) -> Result<Option<Box<dyn Room>>>;
/// Get a feature room for a specific branch, if it exists.
async fn feature_room(
&self,
repo_name: &str,
branch_name: &str,
) -> Result<Option<Box<dyn Room>>>;
}
/// Represents a chat room where messages can be sent and received.
/// The concrete implementation holds the internal room state (e.g., Matrix Room).
#[async_trait]
pub trait Room: Send + Sync {
/// Send a plain text message, optionally with HTML formatting.
async fn send_message(&self, text: &str, html: Option<&str>);
}
/// Type alias for the chat API used throughout the codebase.
pub type ChatApiRef = Arc<dyn ChatApi>;
#[cfg(test)]
mod tests {
use channel::ChatEvent;
use matrix_sdk::ruma::UserId;
use super::*;
// Mock implementation of ChatApi for testing
struct MockChatApi;
#[async_trait]
impl ChatApi for MockChatApi {
async fn management_room(&self, _repo_name: &str) -> Result<Option<Box<dyn Room>>> {
Ok(None)
}
async fn feature_room(
&self,
_repo_name: &str,
_branch_name: &str,
) -> Result<Option<Box<dyn Room>>> {
Ok(None)
}
}
// Mock implementation of Room for testing
struct MockRoom;
#[async_trait]
impl Room for MockRoom {
async fn send_message(&self, _text: &str, _html: Option<&str>) {}
}
#[test]
fn chat_api_trait_is_object_safe() {
let _: Box<dyn ChatApi> = Box::new(MockChatApi);
}
#[test]
fn room_trait_is_object_safe() {
let _: Box<dyn Room> = Box::new(MockRoom);
}
#[test]
fn chat_event_channel_can_be_created() {
let (tx, _rx) = channel::channel();
let user_id = UserId::parse("@test:example.com").unwrap();
// Send a message event to make the variants "used"
let msg = ChatEvent::Message {
repo_name: Some("repo".to_string()),
branch_name: Some("branch".to_string()),
sender: user_id.clone(),
body: "test".to_string(),
};
let _ = tx.try_send(msg);
}
}
+1
View File
@@ -6,6 +6,7 @@ use clap::Subcommand;
use tracing_subscriber::EnvFilter;
mod bot;
mod chat;
mod config;
mod forges;
mod git;