foxfire-acp 0.1.6

Agent Client Protocol (ACP) client utilities and Aether protocol extensions
Documentation
//! Comments a person pins to an artifact's page, and the threads the agent answers them in.

use super::{ArtifactSet, ArtifactSlot};
use crate::chat::FoxfireMeta;
use agent_client_protocol::v2::schema::{
    ContentBlock, EmbeddedResource, EmbeddedResourceResource, SessionId, TextResourceContents,
};
use agent_client_protocol::{JsonRpcRequest, JsonRpcResponse};
use schemars::JsonSchema;
use serde::{Deserialize, Serialize};
use std::collections::{BTreeMap, BTreeSet};
use std::fmt::Write;
use std::ops::Not;

/// Where on an artifact's page a comment points.
#[derive(Debug, Clone, PartialEq, Eq, Default, Serialize, Deserialize, JsonSchema)]
#[serde(rename_all = "camelCase")]
pub struct Anchor {
    pub selector: String,
    pub element: String,
    pub label: String,
    #[serde(default)]
    pub quote: String,
    #[serde(default)]
    pub target: Target,
}

/// The part of an element a comment is about.
#[derive(Debug, Clone, Copy, PartialEq, Default, Serialize, Deserialize, JsonSchema)]
#[serde(tag = "kind", rename_all = "camelCase")]
pub enum Target {
    #[default]
    Element,
    Point {
        at: [f32; 2],
    },
    Region {
        region: [f32; 4],
    },
}

// The page clamps every fraction to 0..=1, so none is NaN.
impl Eq for Target {}

/// A comment as a prompt carries it.
#[derive(Debug, Clone, PartialEq, Eq, Default, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct ArtifactComment {
    pub number: u32,
    pub slot: ArtifactSlot,
    pub name: String,
    pub version: u32,
    pub anchor: Anchor,
    pub note: String,
    #[serde(default, skip_serializing_if = "Not::not")]
    pub follow_up: bool,
}

/// A comment and everything said about it since.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
#[serde(rename_all = "camelCase")]
pub struct CommentThread {
    pub number: u32,
    pub version: u32,
    pub anchor: Anchor,
    pub status: CommentStatus,
    pub entries: Vec<ThreadEntry>,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
#[serde(rename_all = "camelCase")]
pub struct ThreadEntry {
    pub author: Author,
    pub version: u32,
    pub note: String,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
#[serde(rename_all = "camelCase")]
pub enum Author {
    User,
    Agent,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize, JsonSchema)]
#[serde(rename_all = "camelCase")]
pub enum CommentStatus {
    Sent,
    Addressed,
    Question,
    Resolved,
}

/// Resolves a thread, or reopens it for the person to follow up.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonRpcRequest)]
#[request(method = "_foxfire/artifact_comment_resolve", response = ResolveCommentResponse)]
#[serde(rename_all = "camelCase")]
pub struct ResolveCommentParams {
    pub session_id: SessionId,
    pub number: u32,
    pub resolved: bool,
}

#[derive(Debug, Clone, PartialEq, Eq, Default, Serialize, Deserialize, JsonRpcResponse)]
pub struct ResolveCommentResponse {}

/// A session's comment threads, numbered in the order they were sent.
#[derive(Default)]
pub struct Threads {
    threads: BTreeMap<u32, (ArtifactSlot, CommentThread)>,
    last: u32,
}

#[derive(Default, Serialize, Deserialize)]
struct CommentMeta {
    #[serde(default, skip_serializing_if = "Option::is_none")]
    comment: Option<ArtifactComment>,
}

impl FoxfireMeta for CommentMeta {}

impl ArtifactComment {
    /// The content block a prompt carries this comment in.
    pub fn to_block(&self) -> ContentBlock {
        let uri = format!("{COMMENT_URI}{}/comments/{}", self.slot.as_str(), self.number);
        let resource = TextResourceContents::new(self.describe(), uri)
            .mime_type("text/markdown")
            .meta(CommentMeta { comment: Some(self.clone()) }.to_meta());
        ContentBlock::Resource(EmbeddedResource::new(EmbeddedResourceResource::TextResourceContents(resource)))
    }

    /// The comment a block carries, when it was made by [`Self::to_block`].
    pub fn from_block(block: &ContentBlock) -> Option<Self> {
        let resource = text_resource(block)?;
        comment_number(block)?;
        CommentMeta::from_meta(resource.meta.as_ref()).comment
    }

    /// What the agent reads.
    pub fn describe(&self) -> String {
        let Self { number, name, version, anchor, note, follow_up, .. } = self;
        let kind = if *follow_up { "Follow-up on comment" } else { "Comment" };
        let mut text = format!(
            "{kind} {number} on the artifact {name} (v{version}), on {} `{}` at `{}`",
            anchor.label, anchor.element, anchor.selector,
        );
        if !anchor.quote.is_empty() {
            let _ = write!(text, ", reading \"{}\"", anchor.quote);
        }
        match anchor.target {
            Target::Element => {}
            Target::Point { at: [x, y] } => {
                let _ = write!(text, ", at {:.0}% across and {:.0}% down", x * 100.0, y * 100.0);
            }
            Target::Region { region: [l, t, r, b] } => {
                let _ = write!(
                    text,
                    ", the region {:.0}% to {:.0}% across and {:.0}% to {:.0}% down",
                    l * 100.0,
                    r * 100.0,
                    t * 100.0,
                    b * 100.0,
                );
            }
        }
        text.push_str(":\n\n");
        text.push_str(if note.is_empty() { "(No note. The user is pointing at it.)" } else { note });
        text
    }
}

impl CommentThread {
    /// The person's first note on the thread.
    pub fn note(&self) -> &str {
        self.entries.first().map_or("", |entry| entry.note.as_str())
    }
}

impl Threads {
    /// Unknown thread numbers, deduplicated in numeric order.
    pub fn unknown(&self, numbers: impl Iterator<Item = u32>) -> Vec<u32> {
        numbers.filter(|n| !self.threads.contains_key(n)).collect::<BTreeSet<_>>().into_iter().collect()
    }

    /// Applies agent replies in order, returning the slots whose threads changed.
    pub fn answer(
        &mut self,
        replies: impl IntoIterator<Item = (u32, CommentStatus, String)>,
        version: impl Fn(&ArtifactSlot) -> u32,
    ) -> Vec<ArtifactSlot> {
        let mut touched = Vec::new();
        for (number, status, note) in replies {
            let Some((slot, thread)) = self.threads.get_mut(&number) else { continue };
            thread.status = status;
            thread.entries.push(ThreadEntry { author: Author::Agent, version: version(slot), note });
            if !touched.contains(slot) {
                touched.push(slot.clone());
            }
        }
        touched
    }

    /// Records prompt comments on known slots, renumbering blocks in place, and returns changed slots.
    pub fn record(&mut self, prompt: &mut [ContentBlock], known: impl Fn(&ArtifactSlot) -> bool) -> Vec<ArtifactSlot> {
        let mut touched = Vec::new();
        for block in prompt {
            let Some(comment) = ArtifactComment::from_block(block).filter(|c| known(&c.slot)) else { continue };
            if !touched.contains(&comment.slot) {
                touched.push(comment.slot.clone());
            }
            let recorded = self.receive(comment.clone());
            if recorded != comment {
                *block = recorded.to_block();
            }
        }
        touched
    }

    /// Resolves or reopens the thread and returns its slot.
    pub fn resolve(&mut self, number: u32, resolved: bool) -> Option<ArtifactSlot> {
        let (slot, thread) = self.threads.get_mut(&number)?;
        thread.status = if resolved { CommentStatus::Resolved } else { CommentStatus::Question };
        Some(slot.clone())
    }

    /// Thread numbers still waiting for the agent.
    pub fn unanswered(&self) -> Vec<u32> {
        self.threads
            .values()
            .filter_map(|(_, thread)| (thread.status == CommentStatus::Sent).then_some(thread.number))
            .collect()
    }

    /// Gives each of the set's artifacts its threads.
    pub fn attach(&self, set: &mut ArtifactSet) {
        for artifact in set.members_mut() {
            artifact.comments = self
                .threads
                .values()
                .filter(|(slot, _)| *slot == artifact.slot)
                .map(|(_, thread)| thread.clone())
                .collect();
        }
    }

    fn receive(&mut self, mut comment: ArtifactComment) -> ArtifactComment {
        let entry = ThreadEntry { author: Author::User, version: comment.version, note: comment.note.clone() };
        if comment.follow_up
            && let Some((slot, thread)) = self.threads.get_mut(&comment.number)
            && *slot == comment.slot
        {
            thread.status = CommentStatus::Sent;
            thread.entries.push(entry);
            return comment;
        }
        comment.follow_up = false;
        comment.number = comment.number.max(self.last + 1);
        self.last = comment.number;
        let thread = CommentThread {
            number: comment.number,
            version: comment.version,
            anchor: comment.anchor.clone(),
            status: CommentStatus::Sent,
            entries: vec![entry],
        };
        self.threads.insert(comment.number, (comment.slot.clone(), thread));
        comment
    }
}

/// The number of the comment a block carries, also for blocks whose metadata was lost.
pub fn comment_number(block: &ContentBlock) -> Option<u32> {
    let (_, number) = text_resource(block)?.uri.strip_prefix(COMMENT_URI)?.rsplit_once("/comments/")?;
    number.parse().ok()
}

fn text_resource(block: &ContentBlock) -> Option<&TextResourceContents> {
    match block {
        ContentBlock::Resource(EmbeddedResource {
            resource: EmbeddedResourceResource::TextResourceContents(resource),
            ..
        }) => Some(resource),
        _ => None,
    }
}

const COMMENT_URI: &str = "foxfire://artifacts/";