Skip to content

armgit / macro

Public Imported from GitHub
0

Macro is a unified workspace for teams: email, chat, docs, tasks, agents, calls, and CRM — @-linked together with shared AI memory.

27.4 KB
Raw Blame
//! A chat agent's mention is answered in its thread by one message: posted
//! as a pending reply when the turn is announced, resolved into the answer
//! when that turn ends. The announcer is a recorder here, so what is checked
//! is what the domain asked of it and when.

use super::*;
mod conversations;
use crate::domain::model::{
    HeldToolCall, ReplyOutcome, ResolvedReply, TaskAssignmentOrigin, ToolApprovalChange,
};
use crate::domain::notifications::PlannedNotification;

/// A mention of a bot whose sessions the in-memory runtime serves.
fn chat_open_command() -> OpenSession {
    let mut command = open_command();
    command.runtime.kind = AgentKind::InMemory;
    command.runtime.harness = "macro-inmem".to_owned();
    command
}

fn assignment_open_command() -> OpenSession {
    let mut command = chat_open_command();
    command.origin = SessionOrigin::TaskAssignment(TaskAssignmentOrigin {
        trigger_origin: trigger_context::TriggerOrigin::Unknown,
        parent: messages::domain::models::MessageParent::parse("document", "task-1").unwrap(),
        discussion_id: macro_uuid::generate_uuid_v7(),
        actor: sender(),
        prompt: "Private assignment instructions".to_owned(),
        context: None,
    });
    command
}

#[tokio::test]
async fn assignment_instructions_reach_system_and_prompt_only_runtimes() {
    for (kind, harness) in [
        (AgentKind::InMemory, "macro-inmem"),
        (AgentKind::SandboxedCoder, "opencode"),
    ] {
        let composer = PromptComposerMock::default();
        let context = PromptContextMock::default();
        let ((service, repo, containers, _, _), _) =
            harness_with_signals(context.clone(), composer.clone());
        let mut command = assignment_open_command();
        command.runtime.kind = kind;
        command.runtime.harness = harness.to_owned();
        let id = AgentSessionId::new();
        session_with_a_running_turn(&service, &containers, id, command).await;

        let instructions = repo.get(id).await.unwrap().instructions.unwrap();
        assert!(instructions.contains(r#""documentId":"task-1""#));
        assert!(instructions.contains("unless the user explicitly asks you to"));
        let calls = composer.calls();
        assert_eq!(calls.len(), 1);
        assert_eq!(
            calls[0].1.as_deref(),
            kind.folds_instructions().then_some(instructions.as_str())
        );
        assert_eq!(calls[0].2, None);
        assert!(!context.authorized().is_empty());
    }
}

#[tokio::test]
async fn revoked_task_access_blocks_assignment_before_provisioning() {
    let (service, repo, containers, announcer, _) = harness_with_edges(
        PromptContextMock::unauthorized("task access revoked"),
        PromptComposerMock::default(),
    );
    let id = AgentSessionId::new();
    let result = service
        .execute(id, HarnessCommand::Open(assignment_open_command()))
        .await;
    assert!(matches!(result, Err(HarnessError::PromptContext(_))));
    assert!(repo.get(id).await.is_err());
    assert_eq!(containers.spawned(), 0);
    assert!(announcer.announced().is_empty());
    assert!(service.inner.egress.provisioned().is_empty());
}

#[tokio::test]
async fn task_assignment_keeps_the_coder_staff_gate() {
    let (service, repo, containers, announcer, _) = harness();
    let mut command = assignment_open_command();
    command.bot_id = bot_id::MACRO_CODER_BOT_ID;
    command.runtime.kind = AgentKind::SandboxedCoder;
    let id = AgentSessionId::new();
    assert!(
        service
            .execute(id, HarnessCommand::Open(command))
            .await
            .is_err()
    );
    assert!(repo.get(id).await.is_err());
    assert_eq!(containers.spawned(), 0);
    assert!(announcer.announced().is_empty());
}

/// Open a chat session and leave its first turn running.
async fn chat_session_with_a_running_turn(
    service: &TestHarness,
    containers: &MockContainerManager,
    id: AgentSessionId,
) -> ContainerMock {
    session_with_a_running_turn(service, containers, id, chat_open_command()).await
}

/// Open the session `command` asks for and leave its first turn running.
async fn session_with_a_running_turn(
    service: &TestHarness,
    containers: &MockContainerManager,
    id: AgentSessionId,
    command: OpenSession,
) -> ContainerMock {
    let open = service.execute(id, HarnessCommand::Open(command));
    let drive = async {
        loop {
            if containers.spawned() == 1 {
                break;
            }
            tokio::task::yield_now().await;
        }
        let container = containers
            .container(session_of(containers))
            .expect("the spawned container is findable");
        complete_session_handshake(&container).await;
        // initialize, session/new, and the opening prompt.
        container.agent().wait_for_requests(3).await;
        container
    };
    let (opened, container) = tokio::join!(open, drive);
    opened.expect("the chat session opens");
    container
}

/// The agent streams one text part of its answer.
fn says(agent: &FakeAgent, text: &str) {
    agent.sends_raw(
        RawJsonRpcMessage::notification(
            "session/update".to_owned(),
            serde_json::json!({
                "sessionId": "acp-test",
                "update": {
                    "sessionUpdate": "agent_message_chunk",
                    "content": {"type": "text", "text": text}
                }
            }),
        )
        .expect("notification params are an object"),
    );
}

/// Wait until `condition` holds; signals reach the harness asynchronously.
async fn eventually(what: &str, condition: impl Fn() -> bool) {
    tokio::time::timeout(std::time::Duration::from_secs(5), async {
        while !condition() {
            tokio::time::sleep(std::time::Duration::from_millis(5)).await;
        }
    })
    .await
    .unwrap_or_else(|_| panic!("timed out waiting until {what}"));
}

fn runs(agent: &FakeAgent, id: &str, status: &str, command: &str) {
    agent.sends_raw(
        RawJsonRpcMessage::notification(
            "session/update".to_owned(),
            serde_json::json!({
                "sessionId": "acp-test",
                "update": {
                    "sessionUpdate": "tool_call",
                    "toolCallId": id,
                    "title": "Bash",
                    "kind": "execute",
                    "status": status,
                    "rawInput": {"command": command}
                }
            }),
        )
        .expect("notification params are an object"),
    );
}

fn finishes(agent: &FakeAgent, id: &str) {
    agent.sends_raw(
        RawJsonRpcMessage::notification(
            "session/update".to_owned(),
            serde_json::json!({
                "sessionId": "acp-test",
                "update": {"sessionUpdate": "tool_call_update", "toolCallId": id, "status": "completed"}
            }),
        )
        .expect("notification params are an object"),
    );
}

fn one_resolved(announcer: &AnnouncerMock) -> ResolvedReply {
    match announcer.resolved().as_slice() {
        [resolved] => resolved.clone(),
        other => panic!("expected exactly one resolved reply, got {other:#?}"),
    }
}

#[tokio::test]
async fn a_chat_mention_is_announced_as_a_pending_reply_and_resolved_with_the_answer() {
    let ((service, _, containers, announcer, _), turns) =
        harness_with_signals(PromptContextMock::default(), PromptComposerMock::default());
    let id = AgentSessionId::new();
    let container = chat_session_with_a_running_turn(&service, &containers, id).await;
    let agent = container.agent();

    says(&agent, "Hello there.");
    agent.completes_prompt().await;
    // Opened, TurnStarted, TurnEnded, Settled: the reply resolves before
    // the turn's end is published, so once it is, the resolve has happened.
    turns.lifecycle_published(4).await;

    let announced = announcer.announced();
    assert_eq!(announced.len(), 1);
    assert!(!announced[0].is_coding);
    let pending = announcer.announced_messages()[0];
    let resolved = one_resolved(&announcer);
    assert!(!resolved.is_coding);
    assert_eq!(resolved.message_id, pending.message_id);
    // The same bot, into the same parent, for the same person who asked.
    assert_eq!(resolved.bot_id, announced[0].bot_id);
    assert_eq!(resolved.origin_parent, announced[0].origin_parent);
    assert_eq!(resolved.triggered_by, sender());
    assert_eq!(
        resolved.outcome,
        ReplyOutcome::Answered("Hello there.".to_owned())
    );
}

/// The patched reply notifies the thread as a post, so `settled` on top
/// would tell the same people twice.
#[tokio::test]
async fn a_chat_turn_settles_without_a_settled_notification() {
    let ((service, _, containers, _, _), turns) =
        harness_with_signals(PromptContextMock::default(), PromptComposerMock::default());
    let id = AgentSessionId::new();
    let container = chat_session_with_a_running_turn(&service, &containers, id).await;

    says(&container.agent(), "Hello there.");
    container.agent().completes_prompt().await;
    turns.lifecycle_published(4).await;

    assert!(
        matches!(
            turns.lifecycle().last(),
            Some(AgentSessionLifecycleEvent::Settled(_))
        ),
        "the fact is still published: {:#?}",
        turns.lifecycle()
    );
    assert!(
        turns.notifier.notified().is_empty(),
        "nobody is notified twice: {:#?}",
        turns.notifier.notified()
    );
}

#[tokio::test]
async fn a_silent_chat_turn_resolves_as_empty_rather_than_spinning() {
    let ((service, _, containers, announcer, _), turns) =
        harness_with_signals(PromptContextMock::default(), PromptComposerMock::default());
    let id = AgentSessionId::new();
    let container = chat_session_with_a_running_turn(&service, &containers, id).await;

    container.agent().completes_prompt().await;
    turns.lifecycle_published(4).await;

    assert_eq!(one_resolved(&announcer).outcome, ReplyOutcome::Empty);
}

#[tokio::test]
async fn a_chat_session_that_dies_mid_turn_resolves_its_reply_as_failed() {
    let ((service, _, containers, announcer, _), turns) =
        harness_with_signals(PromptContextMock::default(), PromptComposerMock::default());
    let id = AgentSessionId::new();
    let container = chat_session_with_a_running_turn(&service, &containers, id).await;

    container.disconnects();
    // Opened, TurnStarted, Stopped - and no TurnEnded to resolve on.
    turns.lifecycle_published(3).await;

    assert!(
        matches!(
            turns.lifecycle().last(),
            Some(AgentSessionLifecycleEvent::Stopped(_))
        ),
        "{:#?}",
        turns.lifecycle()
    );
    let resolved = one_resolved(&announcer);
    assert_eq!(resolved.outcome, ReplyOutcome::Failed);
    assert_eq!(
        resolved.message_id,
        announcer.announced_messages()[0].message_id
    );
}

/// Two mentions in quick succession are two messages, each resolved when
/// its own turn ends - not both when the queue finally drains.
#[tokio::test]
async fn each_turns_reply_resolves_when_that_turn_ends() {
    let ((service, _, containers, announcer, _), turns) =
        harness_with_signals(PromptContextMock::default(), PromptComposerMock::default());
    let id = AgentSessionId::new();
    let container = chat_session_with_a_running_turn(&service, &containers, id).await;
    let agent = container.agent();

    // A channel follow-up on a running turn steers: it is announced at once
    // and cancels the turn in progress.
    let outcome = service
        .execute(
            id,
            HarnessCommand::Deliver(forward_message("actually, this")),
        )
        .await
        .expect("the follow-up is accepted");
    assert_eq!(outcome, CommandOutcome::Queued);
    assert_eq!(
        announcer.announced().len(),
        2,
        "both mentions have a message"
    );
    assert!(announcer.resolved().is_empty(), "nothing has ended yet");

    // The first turn ends: only its reply resolves, and the second dispatches.
    says(&agent, "First answer.");
    agent.completes_prompt().await;
    // Opened, TurnStarted, TurnEnded (first), TurnStarted (second).
    turns.lifecycle_published(4).await;
    let messages = announcer.announced_messages();
    let resolved = announcer.resolved();
    assert_eq!(resolved.len(), 1, "{resolved:#?}");
    assert_eq!(resolved[0].message_id, messages[0].message_id);
    assert_eq!(
        resolved[0].outcome,
        ReplyOutcome::Answered("First answer.".to_owned())
    );

    says(&agent, "Second answer.");
    agent.completes_prompt().await;
    turns.lifecycle_published(6).await;
    let resolved = announcer.resolved();
    assert_eq!(resolved.len(), 2, "{resolved:#?}");
    assert_eq!(resolved[1].message_id, messages[1].message_id);
    assert_eq!(resolved[1].triggered_by, staff_sender());
    assert_eq!(
        resolved[1].outcome,
        ReplyOutcome::Answered("Second answer.".to_owned())
    );
}

/// The domain does not know a coding kind has nothing to patch - that is the
/// announcer's call - so it asks for every announced turn, naming the kind,
/// and the audience still hears `settled` for a coder.
#[tokio::test]
async fn a_coding_turn_is_offered_to_the_announcer_as_a_coder_and_still_notifies() {
    let ((service, _, containers, announcer, _), turns) =
        harness_with_signals(PromptContextMock::default(), PromptComposerMock::default());
    let id = AgentSessionId::new();
    let container = live_sandboxed_coder_session(&service, &containers, id).await;
    drop(container);
    turns.lifecycle_published(4).await;

    let resolved = one_resolved(&announcer);
    assert!(resolved.is_coding);
    assert_eq!(
        resolved.message_id,
        announcer.announced_messages()[0].message_id
    );
    assert!(
        matches!(
            turns.notifier.notified().as_slice(),
            [PlannedNotification::Settled(_)]
        ),
        "{:#?}",
        turns.notifier.notified()
    );
}

/// The shape of the reply is the persona's to choose, not the runtime's: a
/// bot that says it chats is answered with a reply even on a coding runtime,
/// and its thread hears the answer through that reply rather than `settled`.
#[tokio::test]
async fn a_persona_that_chose_to_chat_gets_a_reply_on_a_coding_runtime() {
    let ((service, _, containers, announcer, _), turns) = harness_with_coding_choice(false);
    let id = AgentSessionId::new();
    let mut command = open_command();
    command.bot_id = bot_id::MACRO_CODER_BOT_ID;
    mention_origin_mut(&mut command).sender = staff_sender();
    let container = session_with_a_running_turn(&service, &containers, id, command).await;
    let agent = container.agent();

    says(&agent, "Done.");
    agent.completes_prompt().await;
    turns.lifecycle_published(4).await;

    let announced = announcer.announced();
    assert_eq!(announced.len(), 1);
    assert!(!announced[0].is_coding);
    let resolved = one_resolved(&announcer);
    assert!(!resolved.is_coding);
    assert_eq!(resolved.outcome, ReplyOutcome::Answered("Done.".to_owned()));
    assert!(
        turns.notifier.notified().is_empty(),
        "{:#?}",
        turns.notifier.notified()
    );
}

/// And the other way: a bot that says it codes is announced as a chip on
/// the in-memory runtime, and its audience hears `settled`.
#[tokio::test]
async fn a_persona_that_chose_to_code_gets_a_chip_on_the_in_memory_runtime() {
    let ((service, _, containers, announcer, _), turns) = harness_with_coding_choice(true);
    let id = AgentSessionId::new();
    let container = chat_session_with_a_running_turn(&service, &containers, id).await;
    let agent = container.agent();

    says(&agent, "Hello there.");
    agent.completes_prompt().await;
    turns.lifecycle_published(4).await;

    assert!(announcer.announced()[0].is_coding);
    assert!(one_resolved(&announcer).is_coding);
    assert!(
        matches!(
            turns.notifier.notified().as_slice(),
            [PlannedNotification::Settled(_)]
        ),
        "{:#?}",
        turns.notifier.notified()
    );
}

/// A question the agent asks through ACP is held for the session view; the
/// thread's spinner has no way of knowing that on its own.
mod elicitation {
    use super::*;
    use agent_client_protocol::schema::v1::{
        CreateElicitationRequest, ElicitationFormMode, ElicitationSchema, ElicitationSessionScope,
        RequestId,
    };
    use agent_runtime_protocol::domain::action::{ElicitationAnswer, ElicitationRequestId};

    fn ask(agent: &FakeAgent, request_id: i64, question: &str) {
        let request = CreateElicitationRequest::new(
            ElicitationFormMode::new(
                ElicitationSessionScope::new(SessionId::new("acp-test")),
                ElicitationSchema::new(),
            ),
            question,
        );
        let (method, params) = request
            .to_untyped_message()
            .expect("an elicitation serializes")
            .into_parts();
        agent.sends_raw(
            RawJsonRpcMessage::request(method, params, RequestId::Number(request_id))
                .expect("elicitation params are an object"),
        );
    }

    /// Raised: the reply says it is waiting and what for. Cleared: the reply
    /// is pending again. Ended: the reply is the answer. One message, three
    /// patches, and no `waiting_for_input` notification on top of the first -
    /// the patch already told the thread.
    #[tokio::test]
    async fn a_question_is_told_in_the_thread_and_withdrawn_when_answered() {
        let ((service, _, containers, announcer, _), turns) =
            harness_with_signals(PromptContextMock::default(), PromptComposerMock::default());
        let id = AgentSessionId::new();
        let container = chat_session_with_a_running_turn(&service, &containers, id).await;
        let agent = container.agent();
        let pending = announcer.announced_messages()[0].message_id;

        ask(&agent, 7, "Which inbox should I send from?");
        // Opened, TurnStarted, WaitingForInput.
        turns.lifecycle_published(3).await;
        let resolved = announcer.resolved();
        assert_eq!(resolved.len(), 1, "{resolved:#?}");
        assert_eq!(resolved[0].message_id, pending);
        assert_eq!(resolved[0].session_id, id);
        assert_eq!(
            resolved[0].outcome,
            ReplyOutcome::NeedsInput {
                question: "Which inbox should I send from?".to_owned(),
            }
        );
        assert!(
            turns.notifier.notified().is_empty(),
            "the patch is the notification: {:#?}",
            turns.notifier.notified()
        );

        service
            .execute(
                id,
                HarnessCommand::Deliver(DeliverAction::control(ControlEvent {
                    action: AgentAction::respond_elicitation(
                        ElicitationRequestId::Number(7),
                        ElicitationAnswer::Decline,
                    ),
                    action_id: None,
                    actor: Some(sender()),
                    context: None,
                })),
            )
            .await
            .expect("the answer is delivered");
        // InputReceived.
        turns.lifecycle_published(4).await;
        let resolved = announcer.resolved();
        assert_eq!(resolved.len(), 2, "{resolved:#?}");
        assert_eq!(resolved[1].message_id, pending);
        assert_eq!(resolved[1].outcome, ReplyOutcome::Resumed);

        says(&agent, "Sent from your primary inbox.");
        agent.completes_prompt().await;
        // TurnEnded, Settled.
        turns.lifecycle_published(6).await;
        let resolved = announcer.resolved();
        assert_eq!(resolved.len(), 3, "{resolved:#?}");
        assert_eq!(resolved[2].message_id, pending);
        assert_eq!(
            resolved[2].outcome,
            ReplyOutcome::Answered("Sent from your primary inbox.".to_owned())
        );
    }
}

/// Tool calls held for the owner's approval: the reply names the oldest one
/// waiting, says nothing new while a later one joins it, moves on to the
/// next when the oldest settles, and is pending again once none wait.
#[tokio::test]
async fn held_tool_calls_are_told_in_the_thread_until_none_wait() {
    let ((service, _, containers, announcer, _), turns) =
        harness_with_signals(PromptContextMock::default(), PromptComposerMock::default());
    let id = AgentSessionId::new();
    let container = chat_session_with_a_running_turn(&service, &containers, id).await;
    let agent = container.agent();
    let pending = announcer.announced_messages()[0].message_id;
    let list_entities = HeldToolCall {
        approval_id: "approval-1".to_owned(),
        server_slug: "macro".to_owned(),
        server_name: "Macro".to_owned(),
        tool_name: "ListEntities".to_owned(),
    };
    let create_issue = HeldToolCall {
        approval_id: "approval-2".to_owned(),
        server_slug: "linear".to_owned(),
        server_name: "Linear".to_owned(),
        tool_name: "create_issue".to_owned(),
    };

    for change in [
        ToolApprovalChange::Held(list_entities.clone()),
        ToolApprovalChange::Held(create_issue.clone()),
        ToolApprovalChange::Settled {
            approval_id: "approval-1".to_owned(),
        },
        ToolApprovalChange::Settled {
            approval_id: "approval-2".to_owned(),
        },
    ] {
        service
            .execute(id, HarnessCommand::ToolApproval(change))
            .await
            .expect("a held call change is handled");
    }

    let resolved = announcer.resolved();
    assert_eq!(
        resolved
            .iter()
            .map(|reply| (reply.message_id, reply.outcome.clone()))
            .collect::<Vec<_>>(),
        [
            (pending, ReplyOutcome::AwaitingApproval(list_entities)),
            (pending, ReplyOutcome::AwaitingApproval(create_issue)),
            (pending, ReplyOutcome::Resumed),
        ]
    );
    assert!(
        turns.notifier.notified().is_empty(),
        "{:#?}",
        turns.notifier.notified()
    );

    says(&agent, "Here are your files.");
    agent.completes_prompt().await;
    turns.lifecycle_published(4).await;
    let resolved = announcer.resolved();
    assert_eq!(resolved.len(), 4, "{resolved:#?}");
    assert_eq!(
        resolved[3].outcome,
        ReplyOutcome::Answered("Here are your files.".to_owned())
    );
}

/// A call settled after its turn ended - the release on turn end - has no
/// reply left to change.
#[tokio::test]
async fn a_held_call_settled_after_its_turn_changes_nothing() {
    let ((service, _, containers, announcer, _), turns) =
        harness_with_signals(PromptContextMock::default(), PromptComposerMock::default());
    let id = AgentSessionId::new();
    let container = chat_session_with_a_running_turn(&service, &containers, id).await;
    let agent = container.agent();
    says(&agent, "Done.");
    agent.completes_prompt().await;
    turns.lifecycle_published(4).await;

    service
        .execute(
            id,
            HarnessCommand::ToolApproval(ToolApprovalChange::Settled {
                approval_id: "approval-1".to_owned(),
            }),
        )
        .await
        .expect("a late settle is handled");

    assert_eq!(
        one_resolved(&announcer).outcome,
        ReplyOutcome::Answered("Done.".to_owned())
    );
}

#[tokio::test]
async fn task_assignment_links_the_session_without_copying_its_answer_to_discussion() {
    let ((service, repo, containers, announcer, _), turns) =
        harness_with_signals(PromptContextMock::default(), PromptComposerMock::default());
    let mut command = assignment_open_command();
    command.runtime.instructions = "Diagnose first.".to_owned();
    let root_id = command.origin.announcement().message_id;
    let id = AgentSessionId::new();
    let container = session_with_a_running_turn(&service, &containers, id, command).await;
    let instructions = repo.get(id).await.unwrap().instructions.unwrap();
    assert!(instructions.starts_with("Diagnose first."));
    assert!(instructions.contains(r#""documentId":"task-1""#));
    assert!(instructions.contains("Update its description"));
    assert!(instructions.contains("Update its status"));
    assert!(instructions.contains("unless the user explicitly asks you to"));
    let announced = announcer.announced();
    assert_eq!(announced.len(), 1);
    assert!(announced[0].reuse_origin_message);
    assert!(announced[0].shows_session_link());
    assert_eq!(announced[0].origin_message_id, root_id);
    assert!(
        announced[0]
            .prompted_content
            .contains("Private assignment instructions")
    );
    says(&container.agent(), "Task completed.");
    container.agent().completes_prompt().await;
    turns.lifecycle_published(4).await;
    assert!(announcer.resolved().is_empty());

    let mut follow_up = forward_message("Please post a summary here.");
    let origin = follow_up.announce.as_mut().unwrap();
    origin.parent = MessageParent::parse("document", "task-1").unwrap();
    origin.thread_id = root_id;
    service
        .execute(id, HarnessCommand::Deliver(follow_up))
        .await
        .unwrap();
    container.agent().wait_for_requests(4).await;
    assert!(!announcer.announced()[1].shows_session_link());
    says(&container.agent(), "Here is the requested summary.");
    container.agent().completes_prompt().await;
    turns.lifecycle_published(7).await;
    assert_eq!(
        one_resolved(&announcer).outcome,
        ReplyOutcome::Answered("Here is the requested summary.".to_owned())
    );
}

#[tokio::test]
async fn a_thread_reply_grows_in_place_with_its_steps_and_resolves_with_them() {
    use agent_fold::domain::model::SegmentKind;
    let ((service, _, containers, announcer, _), turns) =
        harness_with_signals(PromptContextMock::default(), PromptComposerMock::default());
    let id = AgentSessionId::new();
    let container = chat_session_with_a_running_turn(&service, &containers, id).await;
    let agent = container.agent();
    let pending = announcer.announced_messages()[0].message_id;

    says(&agent, "Looking into it.");
    runs(&agent, "t1", "in_progress", "rg TODO");
    eventually("the pending reply shows the passage and its steps", || {
        announcer
            .presented()
            .iter()
            .any(|reply| reply.segments.len() == 2)
    })
    .await;
    assert!(
        announcer
            .presented()
            .iter()
            .all(|reply| !reply.segments.is_empty()),
        "the pending reply is not rewritten before there is something to add"
    );
    let grown = announcer.presented().last().unwrap().clone();
    assert_eq!(grown.message_id, pending, "the thread reply grows in place");
    assert!(grown.pending && grown.link && !grown.notify);
    assert_eq!(
        grown
            .segments
            .iter()
            .map(|s| s.segment.kind)
            .collect::<Vec<_>>(),
        [SegmentKind::Prose, SegmentKind::Activity]
    );
    assert!(
        announcer
            .typed()
            .iter()
            .any(|typing| typing.active && typing.thread_id.is_some()),
        "the bot types in the thread"
    );

    finishes(&agent, "t1");
    says(&agent, "Found three.");
    agent.completes_prompt().await;
    turns.lifecycle_published(4).await;
    let resolved = one_resolved(&announcer);
    assert_eq!(resolved.message_id, pending);
    assert_eq!(
        resolved
            .segments
            .iter()
            .map(|s| (s.segment.kind, s.text.as_deref()))
            .collect::<Vec<_>>(),
        [
            (SegmentKind::Prose, Some("Looking into it.")),
            (SegmentKind::Activity, None),
            (SegmentKind::Prose, Some("Found three.")),
        ]
    );
    assert!(matches!(announcer.typed().last(), Some(typing) if !typing.active));
}