Skip to content

A self-improving RLM agent for coding workflows and long-running autonomous tasks.

Rust
37.2 KB
Raw Blame
//! Custom-message chat rows: the decorated transcript surfaces for
//! `role: "custom"` wire messages (TS `agent-message.ts`,
//! `injected-prompt-message.ts`, `compaction-outcome-message.ts`,
//! `refinement-outcome-message.ts`, `shell-completion.ts`, and the generic
//! `custom-message.ts` panel) plus the user-message skill-invocation card
//! (TS `skill-invocation-message.ts`, parsed out of a user message's
//! `<skill>` block). Decode maps every custom type to the component
//! the TS dispatch (`createDisplayedCustomMessageComponent` /
//! `buildConversationComponents`) picks; rendering ports each component's
//! row geometry and theme colors.
//!
//! Rendering lives in the sibling modules (`render` for most components,
//! `injected_prompt` for the injected-prompt rows, `refinement` for the
//! refinement-outcome component).
//!
//! The dispatch follows the TS live path
//! (`createDisplayedCustomMessageComponent`): non-display rows render
//! nothing, every displayed type without a dedicated component (engine
//! bookkeeping like `harness_digest`, unknown types) renders the generic
//! `[<customType>]` panel. (The TS replay path `buildConversationComponents`
//! drops unknown types instead; the live interactive path is the TUI ground
//! truth, and the Rust engine persists those types with `display: false`.)
//!
//! Divergence (the operator's 2026-10-01 directive: "the factory child
//! status notices should be like subagent messages not user messages"): the
//! RLM child status notices (`rlm_child_terminal_notice` /
//! `rlm_child_failure`) render in the `agent_message` component's class —
//! child-originated mail, attributed to the exited subagent — where the TS
//! dispatch classes them as injected-prompt rows (turn prompts). The
//! notices still drive their turn (the daemon's `followUp` notice action is
//! unchanged); only the transcript row's class moves.

pub(crate) mod geometry;
pub(crate) use geometry::agent_message_body_count;
pub(crate) mod injected_prompt;
pub(crate) mod refinement;
pub(crate) mod render;
pub mod skill_invocation;

pub use skill_invocation::{skill_invocation_entries, SkillInvocationRow};

use injected_prompt::injected_prompt_row;
pub use injected_prompt::{InjectedPromptKind, InjectedPromptRow};

use crate::chat::{ChatEntry, StatusKind};
use crate::theme::ThemeColor;
use serde_json::Value;

/// Custom types with a dedicated component (pa-core owns the engine-side
/// vocabulary, the render dispatch owns these).
pub const AGENT_MESSAGE_CUSTOM_TYPE: &str = "agent_message";
pub const HEARTBEAT_PROMPT_CUSTOM_TYPE: &str = "heartbeat_prompt";
pub const GOAL_CONTEXT_CUSTOM_TYPE: &str = "goal_context";
pub const IPYTHON_STATE_RESTORED_CUSTOM_TYPE: &str = "ipython_state_restored";
pub const PYTHON_SKILLS_UNAVAILABLE_CUSTOM_TYPE: &str = "python_skills_unavailable";
pub const RLM_CHILD_FAILURE_CUSTOM_TYPE: &str = "rlm_child_failure";
pub const RLM_CHILD_TERMINAL_NOTICE_CUSTOM_TYPE: &str = "rlm_child_terminal_notice";
pub const ASYNC_BASH_COMPLETION_CUSTOM_TYPE: &str = "async_bash_completion";
pub const COMPACTION_OUTCOME_CUSTOM_TYPE: &str = "compaction_outcome";
pub const REFINEMENT_OUTCOME_CUSTOM_TYPE: &str = "refinement_outcome";
/// The durable single-line outcome of one provider-retry episode (SANCTIONED DIVERGENCE,
/// operator ruling 2026-09-23: one terminal row per episode instead of TS's per-attempt error
/// rows). Wire twin of `pa_core::session_engine::messages::PROVIDER_RETRY_OUTCOME_CUSTOM_TYPE`.
pub const PROVIDER_RETRY_OUTCOME_CUSTOM_TYPE: &str = "provider_retry_outcome";
/// Wire twin of `pa_core::prompts::model_prompts::MODEL_PROMPT_ERROR_CUSTOM_TYPE`.
pub const MODEL_PROMPT_ERROR_CUSTOM_TYPE: &str = "model_prompt_error";

/// Which agent-message side a row renders: the received transcript rows, or the
/// sent/queued ipython cell receipts. The direction word folds into the
/// viewer-relative arrow (`↓` received, `↑` sent/queued), so the variants carry no label.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum AgentMessageDirection {
    /// The transcript custom-message rows (this chat received the mail).
    Received,
    /// A delivered receipt in ipython cell output.
    Sent,
    /// An undelivered receipt in ipython cell output.
    Queued,
}

/// The shared summary-line label: the direction word folds into the
/// viewer-relative arrow, so every direction carries the same label.
pub(crate) const AGENT_MESSAGE_LABEL: &str = "Agent message";

/// One agent-message summary row: `✉ Agent message · <arrow> <counterpart>` plus
/// the guttered body when expanded. The `✉` mail envelope is a sanctioned
/// divergence (Kevin directive 2026-09-24) from the TS `◆` diamond; the
/// collapsed row carries no preview.
#[derive(Debug, Clone, PartialEq)]
pub struct AgentMessageRow {
    /// Which side renders: it drives the viewer-relative arrow (`↑`
    /// sent/queued, `↓` received).
    pub direction: AgentMessageDirection,
    /// The counterpart agent's display name (session name, then the id
    /// fallbacks, then `unknown`); the relationship words never render.
    pub counterpart: String,
    /// `details.message` (the body shown expanded; never a collapsed
    /// preview).
    pub message: String,
}

/// One background-shell completion row, standalone form (the TS live path attaches
/// the completion to a tool card, which the Rust engine never emits).
#[derive(Debug, Clone, PartialEq)]
pub struct ShellCompletionRow {
    pub pid: Option<i64>,
    pub exit_code: Option<i64>,
    /// Raw content (`[bash-done pid:N exit:M] ...`).
    pub content: String,
}

/// One refinement outcome row (TS `RefinementOutcomeMessageComponent`).
#[derive(Debug, Clone, PartialEq)]
pub struct RefinementOutcomeRow {
    /// `◆ <header>` (`Harness refined` or the full outcome line).
    pub header: String,
    /// Summary text (collapsed: two-line clamp).
    pub summary: String,
    /// `<outcome> · Refinement <id> · <scope>[ · rollback of <id>]` (dim).
    pub meta: String,
    pub edits: Vec<RefinementEditRow>,
}

/// One applied-edit section of a refinement outcome.
#[derive(Debug, Clone, PartialEq)]
pub struct RefinementEditRow {
    /// Label spans: the verb (or the whole failed line) carries its color.
    pub label: Vec<LabelPart>,
    pub reason: Option<String>,
    /// Expanded detail fields (label + plain value or removed/added change).
    pub fields: Vec<EditField>,
}

/// One label span: text plus an optional theme color.
#[derive(Debug, Clone, PartialEq)]
pub struct LabelPart {
    pub text: String,
    pub color: Option<ThemeColor>,
}

/// One edit field (TS `EditFieldRows`): plain value rows or a -/+ change.
#[derive(Debug, Clone, PartialEq)]
pub struct EditField {
    pub label: String,
    pub value: Vec<String>,
    pub change: Option<(Vec<String>, Vec<String>)>,
}

/// One generic custom row: the bold `[<customType>]` label header with
/// the guttered markdown body in `customMessageText` — every display-true
/// custom type without a dedicated component renders this way.
#[derive(Debug, Clone, PartialEq)]
pub struct CustomPanelRow {
    pub custom_type: String,
    pub content: String,
}

/// The transcript entries for one `custom`-role message, mirroring the TS
/// dispatch order: slash rows, compaction and refinement outcomes, agent
/// messages (the received agent-message rows and the RLM child status
/// notices, the same class), shell completions, injected prompts, then the
/// generic panel. Non-display rows render nothing.
pub fn custom_message_entries(message: &Value) -> Vec<ChatEntry> {
    use pa_types::slash_commands::{
        SESSION_SLASH_COMMAND_CUSTOM_TYPE, SESSION_SLASH_COMMAND_RESULT_CUSTOM_TYPE,
    };
    let custom_type = message
        .get("customType")
        .and_then(Value::as_str)
        .unwrap_or("");
    let display = message
        .get("display")
        .and_then(Value::as_bool)
        .unwrap_or(true);
    if !display {
        return Vec::new();
    }
    let content = crate::snapshot::message_text(message);
    let details = message.get("details").unwrap_or(&Value::Null);
    match custom_type {
        SESSION_SLASH_COMMAND_CUSTOM_TYPE | SESSION_SLASH_COMMAND_RESULT_CUSTOM_TYPE => {
            slash_row_entries(message, custom_type, &content, details)
        }
        COMPACTION_OUTCOME_CUSTOM_TYPE => vec![compaction_outcome_entry(message, details)],
        PROVIDER_RETRY_OUTCOME_CUSTOM_TYPE => {
            // The ONE line a retry episode leaves in the chat: the row
            // text the daemon carried, the tone from the verdict.
            vec![ChatEntry::Status {
                text: content,
                kind: if details.get("success").and_then(Value::as_bool) == Some(true) {
                    crate::chat::StatusKind::Info
                } else {
                    crate::chat::StatusKind::Error
                },
            }]
        }
        MODEL_PROMPT_ERROR_CUSTOM_TYPE => vec![ChatEntry::Status {
            text: content,
            kind: crate::chat::StatusKind::Warning,
        }],
        REFINEMENT_OUTCOME_CUSTOM_TYPE => refinement::refinement_outcome_entries(message, details),
        AGENT_MESSAGE_CUSTOM_TYPE => agent_message_entry(details).map_or_else(
            || vec![generic_panel_entry(custom_type, message)],
            |entry| vec![entry],
        ),
        ASYNC_BASH_COMPLETION_CUSTOM_TYPE => vec![ChatEntry::ShellCompletion(Box::new(
            shell_completion_row(message, details),
        ))],
        HEARTBEAT_PROMPT_CUSTOM_TYPE
        | GOAL_CONTEXT_CUSTOM_TYPE
        | IPYTHON_STATE_RESTORED_CUSTOM_TYPE
        | PYTHON_SKILLS_UNAVAILABLE_CUSTOM_TYPE => {
            vec![ChatEntry::InjectedPrompt(Box::new(injected_prompt_row(
                custom_type,
                message,
                details,
            )))]
        }
        // The RLM child status notices are child-originated mail — the
        // spawned subagent's exit status (a factory's children included) —
        // so they render in the same quiet, counterpart-attributed
        // `Agent message` class the children's own `agent_message` rows
        // use (the operator's 2026-10-01 directive: "the factory child
        // status notices should be like subagent messages not user
        // messages"), not as turn-prompt rows. The notice text rides as
        // the row body, so nothing is lost.
        RLM_CHILD_FAILURE_CUSTOM_TYPE | RLM_CHILD_TERMINAL_NOTICE_CUSTOM_TYPE => {
            vec![ChatEntry::AgentMessage(Box::new(rlm_child_status_row(
                message, details,
            )))]
        }
        // Everything else - engine bookkeeping (`harness_digest`,
        // `refinement_notice`, worker recovery) and unknown types - renders
        // the generic panel, exactly like the TS live dispatch fallthrough
        // (those types persist with `display: false` and render nothing).
        _ => vec![generic_panel_entry(custom_type, message)],
    }
}

/// TS `CustomMessageComponent` fallthrough: the `[<customType>]` guttered
/// panel row.
fn generic_panel_entry(custom_type: &str, message: &Value) -> ChatEntry {
    ChatEntry::CustomPanel(Box::new(CustomPanelRow {
        custom_type: custom_type.to_string(),
        content: custom_content_text(message),
    }))
}

/// The session-command echo/result rows: the echo decodes to the user-block slash
/// row (the typed command IS user input); the result row to the status-row class.
fn slash_row_entries(
    message: &Value,
    custom_type: &str,
    content: &str,
    details: &Value,
) -> Vec<ChatEntry> {
    use pa_types::slash_commands::SESSION_SLASH_COMMAND_CUSTOM_TYPE;
    let is_command_row = custom_type == SESSION_SLASH_COMMAND_CUSTOM_TYPE;
    let content_is_text = match message.get("content") {
        Some(Value::String(_)) => true,
        Some(Value::Array(blocks)) => {
            blocks.len() == 1
                && matches!(
                    blocks[0].get("type").and_then(Value::as_str),
                    Some("text") | None
                )
        }
        _ => false,
    };
    let command_details_valid = details.get("command").is_some_and(|command| {
        command.get("name").is_some()
            && command.get("args").is_some()
            && command.get("text").is_some()
    });
    if !content_is_text || (is_command_row && !command_details_valid) {
        return vec![ChatEntry::User {
            text: "[Malformed session command message]".to_string(),
        }];
    }
    if is_command_row {
        vec![ChatEntry::SlashCommand {
            text: content.to_string(),
        }]
    } else {
        // The outcome row is system output, never user text (operator ruling
        // 2026-09-25): it renders in the status-row class, the severity driving the tone.
        let kind = match details.get("severity").and_then(Value::as_str) {
            Some("error") => StatusKind::Error,
            Some("warning") => StatusKind::Warning,
            _ => StatusKind::Info,
        };
        vec![ChatEntry::Status {
            text: content.to_string(),
            kind,
        }]
    }
}

/// TS `isCompactionOutcomeMessage` envelope: content string + a known
/// reason/outcome pair; anything else is the malformed notice.
fn compaction_outcome_entry(message: &Value, details: &Value) -> ChatEntry {
    let valid = message.get("content").is_some_and(Value::is_string)
        && matches!(
            details.get("reason").and_then(Value::as_str),
            Some("threshold" | "overflow" | "requested")
        )
        && matches!(
            details.get("outcome").and_then(Value::as_str),
            Some("skipped" | "cancelled" | "failed")
        );
    if !valid {
        return ChatEntry::Status {
            text: "[Malformed compaction outcome message]".to_string(),
            kind: StatusKind::Error,
        };
    }
    let outcome = details
        .get("outcome")
        .and_then(Value::as_str)
        .unwrap_or("failed");
    ChatEntry::Status {
        text: crate::snapshot::message_text(message),
        kind: if outcome == "skipped" {
            StatusKind::Warning
        } else {
            StatusKind::Error
        },
    }
}

/// String `details.id` + string `details.message` (no emptiness check);
/// anything else falls through to the generic box.
fn agent_message_entry(details: &Value) -> Option<ChatEntry> {
    details.get("id").and_then(Value::as_str)?;
    let message = details.get("message").and_then(Value::as_str)?;
    let from = details.get("from").unwrap_or(&Value::Null);
    let counterpart = ["sessionName", "activeSessionId", "clientId", "sessionId"]
        .iter()
        .find_map(|key| {
            from.get(*key)
                .and_then(Value::as_str)
                .map(str::to_string)
                .filter(|name| !name.trim().is_empty())
        })
        .unwrap_or_else(|| "unknown".to_string());
    Some(ChatEntry::AgentMessage(Box::new(AgentMessageRow {
        direction: AgentMessageDirection::Received,
        counterpart,
        message: message.to_string(),
    })))
}

/// One RLM child status notice (`rlm_child_terminal_notice` /
/// `rlm_child_failure`) as the subagent-mail row: the child that exited is
/// the mail's counterpart, the notice text is the body (the full content,
/// header included, so the outcome wording rides intact).
fn rlm_child_status_row(message: &Value, details: &Value) -> AgentMessageRow {
    let content = custom_content_text(message);
    AgentMessageRow {
        direction: AgentMessageDirection::Received,
        counterpart: rlm_child_session_name(details, &content),
        message: content,
    }
}

/// The child's session name: the `sessionName` details key, falling back to
/// the `child:<name>]` token of the content header (the pre-details wire
/// rows), then the agent-message row's `unknown`.
fn rlm_child_session_name(details: &Value, content: &str) -> String {
    details
        .get("sessionName")
        .and_then(Value::as_str)
        .filter(|name| !name.is_empty())
        .map(str::to_string)
        .or_else(|| {
            content
                .split_once("child:")
                .and_then(|(_, rest)| rest.split(']').next())
                .map(str::trim)
                .filter(|name| !name.is_empty())
                .map(str::to_string)
        })
        .unwrap_or_else(|| "unknown".to_string())
}

/// TS `readShellCompletion` + `ShellCompletionComponent.render`: a valid
/// completion needs an object details block with a positive-integer `pid`,
/// a string `command`, and an integer `exitCode`; anything else renders the
/// default finished row (the expanded raw text follows the same validity).
fn shell_completion_row(message: &Value, details: &Value) -> ShellCompletionRow {
    let pid = details.get("pid").and_then(Value::as_i64);
    let command = details.get("command").and_then(Value::as_str);
    let exit_code = details.get("exitCode").and_then(Value::as_i64);
    let valid = details.is_object()
        && pid.is_some_and(|pid| pid > 0)
        && command.is_some()
        && exit_code.is_some();
    if valid {
        ShellCompletionRow {
            pid,
            exit_code,
            content: custom_content_text(message),
        }
    } else {
        ShellCompletionRow {
            pid: None,
            exit_code: None,
            content: match message.get("content") {
                Some(Value::String(_)) => custom_content_text(message),
                Some(value) => serde_json::to_string(value).unwrap_or_default(),
                None => String::new(),
            },
        }
    }
}

/// TS `readCustomText`: content string or blocks joined with newlines
/// (text blocks keep their text, every non-text block renders `[image]`).
pub(crate) fn custom_content_text(message: &Value) -> String {
    match message.get("content") {
        Some(Value::String(text)) => text.clone(),
        Some(Value::Array(blocks)) => blocks
            .iter()
            .map(|block| {
                if block.get("type").and_then(Value::as_str) == Some("text") {
                    block
                        .get("text")
                        .and_then(Value::as_str)
                        .unwrap_or("")
                        .to_string()
                } else {
                    "[image]".to_string()
                }
            })
            .collect::<Vec<_>>()
            .join("\n"),
        _ => String::new(),
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::{Line, Span};
    use serde_json::json;

    fn decoded(message: &serde_json::Value) -> Vec<ChatEntry> {
        custom_message_entries(message)
    }

    #[test]
    fn non_display_rows_render_nothing() {
        // TS skips display=false rows everywhere (harness digests,
        // refinement notices, worker recovery are bookkeeping).
        for custom_type in [
            "harness_digest",
            "refinement_notice",
            "prime-agent.worker_recovery",
            AGENT_MESSAGE_CUSTOM_TYPE,
        ] {
            let entries = decoded(&json!({
                "role": "custom",
                "customType": custom_type,
                "content": "kept out of the transcript",
                "display": false,
                "details": { "id": "agentmsg_1", "message": "body" },
            }));
            assert!(entries.is_empty(), "{custom_type} rendered {entries:?}");
        }
    }

    #[test]
    fn bookkeeping_types_render_the_generic_box_when_displayed() {
        // A stray display=true bookkeeping row falls through to the
        // generic box (in practice these persist with display=false).
        for custom_type in [
            "harness_digest",
            "refinement_notice",
            "prime-agent.worker_recovery",
            "ipython_state",
            "thread_goal_state",
        ] {
            let entries = decoded(&json!({
                "role": "custom",
                "customType": custom_type,
                "content": "digest",
                "display": true,
            }));
            assert!(
                matches!(
                    entries.as_slice(),
                    [ChatEntry::CustomPanel(row)]
                        if row.custom_type == custom_type
                            && row.content == "digest"
                ),
                "{custom_type} rendered {entries:?}"
            );
        }
    }

    #[test]
    fn agent_message_decodes_counterpart_and_body() {
        let entries = decoded(&json!({
            "role": "custom",
            "customType": AGENT_MESSAGE_CUSTOM_TYPE,
            "content": "[agent-message from child:model-probe]\n\nready",
            "display": true,
            "details": {
                "id": "agentmsg_1",
                "message": "ready",
                "from": {
                    "sessionName": "model-probe",
                    "sessionId": "sess-1",
                    "activeSessionId": "aaa111",
                    "runtimeKind": "subagent",
                },
                "fromRelationship": "child",
            },
        }));
        let [ChatEntry::AgentMessage(row)] = entries.as_slice() else {
            panic!("agent message row: {entries:?}");
        };
        assert_eq!(row.counterpart, "model-probe");
        assert_eq!(row.message, "ready");
    }

    #[test]
    fn agent_message_counterpart_falls_back_to_ids() {
        // The name leg: session name, then active session id, client id, session
        // id, then "unknown" (the relationship word never reaches the row).
        let base = |from: serde_json::Value| {
            decoded(&json!({
                "role": "custom",
                "customType": AGENT_MESSAGE_CUSTOM_TYPE,
                "content": "[agent-message from x]\n\nhi",
                "display": true,
                "details": {
                    "id": "agentmsg_2",
                    "message": "hi",
                    "from": from,
                    "fromRelationship": "child",
                },
            }))
        };
        let entry = |entries: Vec<ChatEntry>| match entries.as_slice() {
            [ChatEntry::AgentMessage(row)] => row.counterpart.clone(),
            other => panic!("agent message row: {other:?}"),
        };
        assert_eq!(
            entry(base(
                json!({ "activeSessionId": "aaa111", "sessionId": "s1" })
            )),
            "aaa111"
        );
        assert_eq!(
            entry(base(json!({ "clientId": "client-9", "sessionId": "s1" }))),
            "client-9"
        );
        assert_eq!(entry(base(json!({ "sessionId": "s1" }))), "s1");
        assert_eq!(entry(base(json!(null))), "unknown");
        assert_eq!(
            entry(base(json!({ "sessionName": "model-probe" }))),
            "model-probe"
        );
        // Without valid id/message details the row is not an agent message;
        // it falls through to the generic box.
        let entries = decoded(&json!({
            "role": "custom",
            "customType": AGENT_MESSAGE_CUSTOM_TYPE,
            "content": "[agent-message from x]",
            "display": true,
            "details": { "id": 1, "message": null },
        }));
        assert!(matches!(entries.as_slice(), [ChatEntry::CustomPanel(_)]));
    }

    #[test]
    fn injected_prompt_kinds_decode() {
        let heartbeat = decoded(&json!({
            "role": "custom",
            "customType": HEARTBEAT_PROMPT_CUSTOM_TYPE,
            "content": "[heartbeat: every 10m run#0]\n\nnudge",
            "display": true,
            "details": { "jobId": "j1", "schedule": "every 10m", "runCount": 0 },
        }));
        assert!(matches!(
            heartbeat.as_slice(),
            [ChatEntry::InjectedPrompt(boxed)]
                if matches!(boxed.kind, InjectedPromptKind::Heartbeat { ref schedule }
                    if schedule.as_deref() == Some("every 10m"))
        ));
        let goal = decoded(&json!({
            "role": "custom",
            "customType": GOAL_CONTEXT_CUSTOM_TYPE,
            "content": "[goal: continuation]",
            "display": true,
            "details": { "kind": "continuation", "objective": "ship it" },
        }));
        assert!(matches!(
            goal.as_slice(),
            [ChatEntry::InjectedPrompt(boxed)]
                if matches!(&boxed.kind,
                    InjectedPromptKind::Goal { kind, objective }
                        if kind.as_deref() == Some("continuation")
                            && objective.as_deref() == Some("ship it"))
        ));
        let restored = decoded(&json!({
            "role": "custom",
            "customType": IPYTHON_STATE_RESTORED_CUSTOM_TYPE,
            "content": "[python-state-restored]",
            "display": true,
            "details": { "restored": false },
        }));
        assert!(matches!(
            restored.as_slice(),
            [ChatEntry::InjectedPrompt(boxed)]
                if matches!(boxed.kind, InjectedPromptKind::KernelRestored { restored: false })
        ));
        // The kernel-state row carries no expandable body.
        let restored = decoded(&json!({
            "role": "custom",
            "customType": IPYTHON_STATE_RESTORED_CUSTOM_TYPE,
            "content": "[python-state-restored]",
            "display": true,
            "details": { "restored": true },
        }));
        assert!(matches!(
            restored.as_slice(),
            [ChatEntry::InjectedPrompt(boxed)] if boxed.body.is_none()
        ));
    }

    /// The RLM child status notices decode to the subagent-mail class
    /// (the operator's 2026-10-01 directive: "the factory child status
    /// notices should be like subagent messages not user messages"): the
    /// row carries the child as its counterpart and the notice text as
    /// the body, and it never renders as a turn-prompt (injected) or
    /// user row — the class assertion is the mutation pin (routing the
    /// types back through the injected-prompt arm fails it).
    #[test]
    fn rlm_child_notice_rows_decode_to_the_agent_message_class() {
        let notices = [
            (
                RLM_CHILD_FAILURE_CUSTOM_TYPE,
                "[child-failed child:lane]\n\nboom",
                json!({ "childId": "sub-1", "sessionName": "lane", "error": "boom" }),
            ),
            (
                RLM_CHILD_TERMINAL_NOTICE_CUSTOM_TYPE,
                "[child-exited: no-reply child:lane]\n\nLast assistant text: done",
                json!({ "childId": "sub-2", "sessionName": "lane", "kind": "completed_without_reply" }),
            ),
            (
                RLM_CHILD_TERMINAL_NOTICE_CUSTOM_TYPE,
                "[child-exited: cancelled child:cancel-worker]\n\nDeleted by parent",
                json!({ "childId": "sub-3", "sessionName": "cancel-worker", "kind": "cancelled", "reason": "Deleted by parent" }),
            ),
        ];
        for (custom_type, content, details) in notices {
            let entries = decoded(&json!({
                "role": "custom",
                "customType": custom_type,
                "content": content,
                "display": true,
                "details": details,
            }));
            let row = match entries.as_slice() {
                [ChatEntry::AgentMessage(row)] => row,
                other => panic!("{custom_type} must decode to the agent-message class: {other:?}"),
            };
            assert_eq!(row.direction, AgentMessageDirection::Received);
            assert_eq!(row.counterpart, details["sessionName"]);
            // The content rides intact as the body (outcome wording and
            // the child's last text included).
            assert_eq!(row.message, content);
            assert!(
                !matches!(
                    entries.as_slice(),
                    [ChatEntry::InjectedPrompt(_) | ChatEntry::User { .. }]
                ),
                "{custom_type} must not render as a turn-prompt/user row"
            );
        }
        // The pre-details wire rows keep their identity: the name comes
        // from the `child:<name>]` content token.
        let entries = decoded(&json!({
            "role": "custom",
            "customType": RLM_CHILD_FAILURE_CUSTOM_TYPE,
            "content": "[child-failed child:legacy-worker]\n\nspawn failed",
            "display": true,
            "details": serde_json::Value::Null,
        }));
        assert!(matches!(
            entries.as_slice(),
            [ChatEntry::AgentMessage(row)]
                if row.counterpart == "legacy-worker"
                    && row.message == "[child-failed child:legacy-worker]\n\nspawn failed"
        ));
    }

    /// The unavailable-skills row decodes the failed names and keeps the
    /// full report as its expandable body.
    #[test]
    fn python_skills_unavailable_row_decodes() {
        let unavailable = decoded(&json!({
            "role": "custom",
            "customType": PYTHON_SKILLS_UNAVAILABLE_CUSTOM_TYPE,
            "content": "[python-skills-unavailable]\n\n- websearch: No module named 'websearch'",
            "display": true,
            "details": { "skills": ["websearch", "edit"] },
        }));
        assert!(matches!(
            unavailable.as_slice(),
            [ChatEntry::InjectedPrompt(boxed)]
                if matches!(&boxed.kind,
                    InjectedPromptKind::PythonSkillsUnavailable { skills }
                        if skills == &vec!["websearch".to_string(), "edit".to_string()])
                    && boxed.body.as_deref() == Some("[python-skills-unavailable]\n\n- websearch: No module named 'websearch'")
        ));
    }

    #[test]
    fn shell_completion_decodes_details() {
        let entries = decoded(&json!({
            "role": "custom",
            "customType": ASYNC_BASH_COMPLETION_CUSTOM_TYPE,
            "content": "[bash-done pid:4371 exit:0]\n\nCommand: \"ls\"",
            "display": true,
            "details": { "pid": 4371, "command": "ls", "exitCode": 0 },
        }));
        assert!(matches!(
            entries.as_slice(),
            [ChatEntry::ShellCompletion(row)]
                if row.pid == Some(4371) && row.exit_code == Some(0)
        ));
        // An invalid details block keeps the default finished row and the JSON
        // content fallback.
        let entries = decoded(&json!({
            "role": "custom",
            "customType": ASYNC_BASH_COMPLETION_CUSTOM_TYPE,
            "content": [{ "type": "text", "text": "[bash-done]" }],
            "display": true,
            "details": { "pid": -1, "exitCode": 3 },
        }));
        assert!(matches!(
            entries.as_slice(),
            [ChatEntry::ShellCompletion(row)]
                if row.pid.is_none() && row.exit_code.is_none()
        ));
    }

    #[test]
    fn agent_message_accepts_empty_string_details() {
        // TS `isAgentSessionMessage` checks only `typeof id === "string"` and
        // `typeof message === "string"`; empty strings still decode as agent-message rows.
        let entries = decoded(&json!({
            "role": "custom",
            "customType": AGENT_MESSAGE_CUSTOM_TYPE,
            "content": "[agent-message from x]",
            "display": true,
            "details": { "id": "", "message": "" },
        }));
        assert!(matches!(entries.as_slice(), [ChatEntry::AgentMessage(_)]));
    }

    #[test]
    fn compaction_outcome_maps_to_status_rows() {
        let skipped = decoded(&json!({
            "role": "custom",
            "customType": COMPACTION_OUTCOME_CUSTOM_TYPE,
            "content": "Compaction skipped: below threshold",
            "display": true,
            "details": { "reason": "threshold", "outcome": "skipped" },
        }));
        assert_eq!(
            skipped,
            vec![ChatEntry::Status {
                text: "Compaction skipped: below threshold".to_string(),
                kind: StatusKind::Warning,
            }]
        );
        let failed = decoded(&json!({
            "role": "custom",
            "customType": COMPACTION_OUTCOME_CUSTOM_TYPE,
            "content": "Compaction failed",
            "display": true,
            "details": { "reason": "requested", "outcome": "failed" },
        }));
        assert_eq!(
            failed,
            vec![ChatEntry::Status {
                text: "Compaction failed".to_string(),
                kind: StatusKind::Error,
            }]
        );
        let malformed = decoded(&json!({
            "role": "custom",
            "customType": COMPACTION_OUTCOME_CUSTOM_TYPE,
            "content": "Compaction?",
            "display": true,
            "details": { "reason": "wat" },
        }));
        assert_eq!(
            malformed,
            vec![ChatEntry::Status {
                text: "[Malformed compaction outcome message]".to_string(),
                kind: StatusKind::Error,
            }]
        );
    }

    #[test]
    fn unknown_displayed_types_render_the_generic_box() {
        let entries = decoded(&json!({
            "role": "custom",
            "customType": "autonomous_status",
            "content": "[autonomous-status: on]",
            "display": true,
            "details": { "enabled": true },
        }));
        assert!(matches!(
            entries.as_slice(),
            [ChatEntry::CustomPanel(row)]
                if row.custom_type == "autonomous_status"
                    && row.content == "[autonomous-status: on]"
        ));
    }

    /// Flattened rows with the trailing padding trimmed (whole-vector
    /// equality against the painted transcript text).
    fn plain_rows(rows: &[Line]) -> Vec<String> {
        rows.iter()
            .map(|row| {
                row.iter()
                    .map(|span| span.content.as_str())
                    .collect::<String>()
                    .trim_end()
                    .to_string()
            })
            .collect()
    }

    /// One gutter for every expandable chat body: the dim gutter row sits right
    /// below the header, the rest on the four-column indent, and the collapsed rows stay bare.
    #[test]
    fn expandable_bodies_hang_on_one_gutter() {
        use crate::chat::Detail;
        use crate::compaction_row::render_compaction_summary;
        let theme = crate::theme::Theme::builtin("prime", crate::theme::ColorMode::TrueColor);
        let gutter = Span::styled(
            crate::branch::BRANCH_GUTTER.to_string(),
            theme.fg_style(ThemeColor::Dim),
        );
        // 57 columns wrap at the branch content width 56: one full row
        // plus one.
        let body = "w".repeat(57);
        let head = format!(" {}{}", crate::branch::BRANCH_GUTTER, "w".repeat(56));
        let tail = format!("{}w", crate::branch::BRANCH_INDENT);
        let skill = SkillInvocationRow {
            name: "review".to_string(),
            content: body.clone(),
        };
        let goal = InjectedPromptRow {
            kind: InjectedPromptKind::Goal {
                kind: Some("continuation".to_string()),
                objective: Some("Ship.".to_string()),
            },
            body: Some(body.clone()),
        };
        let shell = ShellCompletionRow {
            pid: None,
            exit_code: Some(0),
            content: body.clone(),
        };
        let panel = CustomPanelRow {
            custom_type: "notice".to_string(),
            content: body.clone(),
        };
        let compacted = format!(" {body}");
        // (collapsed rows + their expected text, expanded rows, expanded
        // header text)
        let cases = vec![
            (
                Some((
                    skill_invocation::render_skill_invocation(
                        &skill,
                        Detail::Overview,
                        &theme,
                        60,
                        false,
                    ),
                    vec![" [skill] review"],
                )),
                skill_invocation::render_skill_invocation(&skill, Detail::All, &theme, 60, false),
                vec![" [skill] review"],
            ),
            (
                Some((
                    injected_prompt::render_injected_prompt(&goal, Detail::Overview, &theme, 60),
                    vec!["", " Goal continuation \u{b7} Ship."],
                )),
                injected_prompt::render_injected_prompt(&goal, Detail::All, &theme, 60),
                vec!["", " Goal continuation \u{b7} Ship."],
            ),
            (
                Some((
                    render::render_shell_completion(&shell, Detail::Overview, &theme, 60, false),
                    vec![" \u{2713} Background shell command finished"],
                )),
                render::render_shell_completion(&shell, Detail::All, &theme, 60, false),
                vec![" \u{2713} Background shell command finished"],
            ),
            (
                None,
                render::render_custom_panel(&panel, &theme, 60),
                vec!["", " [notice]"],
            ),
            (
                Some((
                    render_compaction_summary(&body, 480, None, false, &theme, 60),
                    vec![" \u{25c6} Context compacted", compacted.as_str()],
                )),
                render_compaction_summary(&body, 480, None, true, &theme, 60),
                vec![" \u{25c6} Context compacted \u{b7} Compacted from 480 tokens"],
            ),
        ];
        for (collapsed, expanded, header) in cases {
            if let Some((rows, text)) = collapsed {
                assert_eq!(plain_rows(&rows), text, "{rows:?}");
            }
            let mut text = header.clone();
            text.extend([head.as_str(), tail.as_str()]);
            assert_eq!(plain_rows(&expanded), text, "{expanded:?}");
            assert_eq!(expanded[header.len()][1], gutter, "{expanded:?}");
        }
    }
}