rho-coding-agent 2.34.0

A fast Rust agent harness with a small footprint and opinionated defaults
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
use agent_client_protocol::schema::v1::{
    ContentBlock, ContentChunk, ImageContent, MessageId, SessionId, SessionNotification,
    SessionUpdate, ToolCall, ToolCallContent, ToolCallId, ToolCallStatus, ToolCallUpdate,
    ToolCallUpdateFields, ToolKind,
};
use pretty_assertions::assert_eq;
use rho_sdk::model::{self, AbortedAssistant, AssistantMessage, Message, ToolResult};
use serde_json::json;

use super::history;
use crate::{
    agent::{AgentCapabilities, ToolCapability},
    config::Config,
    diagnostics::RuntimeDiagnostics,
    session::tree::{DisplayRowOrigin, NodeId, ProjectedMessage},
    tools::sdk_registry::{AppToolSet, ToolSetOptions},
};

fn call_block(id: &str) -> model::ContentBlock {
    named_call_block(id, "read", json!({"path": "a.png"}))
}

fn named_call_block(id: &str, name: &str, arguments: serde_json::Value) -> model::ContentBlock {
    model::ContentBlock::ToolCall(model::ToolCall {
        id: id.into(),
        name: name.into(),
        arguments,
    })
}

/// Replays `messages` as if each was saved as its own display row.
fn raw_replay(messages: &[Message]) -> Vec<SessionNotification> {
    history(
        &SessionId::new("s1"),
        &saved_rows(messages),
        std::path::Path::new(""),
        &AppToolSet::disabled(),
    )
}

fn saved_rows(messages: &[Message]) -> Vec<ProjectedMessage> {
    messages
        .iter()
        .enumerate()
        .map(|(row, message)| ProjectedMessage {
            origin: Some(DisplayRowOrigin {
                node: NodeId::from_string("node").unwrap(),
                row,
            }),
            message: message.clone(),
        })
        .collect()
}

/// Replay with ACP identities canonicalized by first appearance: tool calls
/// as `0`, `1`, ... and messages as `m0`, `m1`, ... Pairing is retained, and
/// duplicate announcements or updates to unknown calls are rejected.
fn replay(messages: &[Message]) -> Vec<SessionNotification> {
    let mut notifications = raw_replay(messages);
    let mut ids = std::collections::HashMap::new();
    let mut message_ids = std::collections::HashMap::new();
    for notification in &mut notifications {
        let id = match &mut notification.update {
            SessionUpdate::ToolCall(call) => {
                let next = ids.len().to_string();
                assert!(ids.insert(call.tool_call_id.clone(), next).is_none());
                &mut call.tool_call_id
            }
            SessionUpdate::ToolCallUpdate(update) => &mut update.tool_call_id,
            SessionUpdate::UserMessageChunk(chunk)
            | SessionUpdate::AgentMessageChunk(chunk)
            | SessionUpdate::AgentThoughtChunk(chunk) => {
                let id = chunk
                    .message_id
                    .take()
                    .expect("replayed chunk has a message ID");
                let next = format!("m{}", message_ids.len());
                chunk.message_id = Some(message_ids.entry(id).or_insert(next).clone().into());
                continue;
            }
            _ => continue,
        };
        *id = ToolCallId::new(ids.get(id).expect("previously announced call").clone());
    }
    notifications
}

fn chunk(text: &str, message_id: &'static str) -> ContentChunk {
    ContentChunk::new(ContentBlock::from(text)).message_id(MessageId::from(message_id))
}

fn expected(updates: Vec<SessionUpdate>) -> Vec<SessionNotification> {
    updates
        .into_iter()
        .map(|update| {
            SessionNotification::new(SessionId::new("s1"), update).meta(serde_json::Map::from_iter(
                [("isReplay".into(), json!(true))],
            ))
        })
        .collect()
}

fn tool(id: &str) -> ToolCall {
    ToolCall::new(ToolCallId::new(id), "read")
        .name("read")
        .status(ToolCallStatus::Pending)
        .raw_input(json!({"path": "a.png"}))
}

// Covers: parallel calls must keep their ids and order, and tool-image
// supplements must update the same card without erasing output or failed status.
// Owner: ACP replay mapping (the stdio test covers persistence of ordinary results)
#[test]
fn replay_pairs_out_of_order_results_and_accumulates_images() {
    for (ok, status) in [
        (true, ToolCallStatus::Completed),
        (false, ToolCallStatus::Failed),
    ] {
        let image = model::ImageContent {
            data: "YWJj".into(),
            mime_type: "image/png".into(),
        };
        let content = vec![ToolCallContent::from("output")];
        let mut with_image = content.clone();
        with_image.push(ToolCallContent::from(ContentBlock::Image(
            ImageContent::new("YWJj", "image/png"),
        )));
        let messages = vec![
            Message::user_text("read images"),
            Message::Assistant(vec![
                call_block("a"),
                model::ContentBlock::Text("between".into()),
                call_block("b"),
            ]),
            Message::ToolResult(ToolResult {
                id: "b".into(),
                ok,
                content: "output".into(),
            }),
            Message::tool_image_supplement("read", "b", vec![image]).unwrap(),
            Message::ToolResult(ToolResult {
                id: "a".into(),
                ok: true,
                content: String::new(),
            }),
        ];
        assert_eq!(
            replay(&messages),
            expected(vec![
                SessionUpdate::UserMessageChunk(chunk("read images", "m0")),
                SessionUpdate::ToolCall(tool("0")),
                SessionUpdate::AgentMessageChunk(chunk("between", "m1")),
                SessionUpdate::ToolCall(tool("1")),
                SessionUpdate::ToolCallUpdate(ToolCallUpdate::new(
                    ToolCallId::new("1"),
                    ToolCallUpdateFields::new()
                        .status(status)
                        .content(content)
                        .raw_output(json!("output"))
                )),
                SessionUpdate::ToolCallUpdate(ToolCallUpdate::new(
                    ToolCallId::new("1"),
                    ToolCallUpdateFields::new()
                        .status(status)
                        .content(with_image)
                )),
                SessionUpdate::ToolCallUpdate(ToolCallUpdate::new(
                    ToolCallId::new("0"),
                    ToolCallUpdateFields::new()
                        .status(ToolCallStatus::Completed)
                        .content(vec![])
                        .raw_output(json!(""))
                )),
            ])
        );
    }
}

// Covers: interrupted history must not leave a spinning card, including calls
// in enriched/aborted assistants; partial results must never update unknown ids.
// Owner: ACP replay mapping
#[test]
fn replay_closes_incomplete_calls_and_opens_orphan_results() {
    for message in [
        Message::Assistant(vec![call_block("a")]),
        Message::EnrichedAssistant(Box::new(AssistantMessage::from_content(vec![call_block(
            "a",
        )]))),
        Message::AbortedAssistant(Box::new(AbortedAssistant {
            content: vec![call_block("a")],
            ..Default::default()
        })),
    ] {
        assert_eq!(
            replay(&[message]),
            expected(vec![
                SessionUpdate::ToolCall(tool("0")),
                SessionUpdate::ToolCallUpdate(ToolCallUpdate::new(
                    ToolCallId::new("0"),
                    ToolCallUpdateFields::new().status(ToolCallStatus::Failed)
                )),
            ])
        );
    }
    for (ok, status) in [
        (true, ToolCallStatus::Completed),
        (false, ToolCallStatus::Failed),
    ] {
        assert_eq!(
            replay(&[Message::ToolResult(ToolResult {
                id: "orphan".into(),
                ok,
                content: "output".into()
            })]),
            expected(vec![SessionUpdate::ToolCall(
                ToolCall::new(ToolCallId::new("0"), "tool")
                    .status(status)
                    .content(vec![ToolCallContent::from("output")])
                    .raw_output(json!("output"))
            )])
        );
    }
}

// Covers: a reused provider ID must close the superseded unfinished occurrence,
// and later results/images and end-of-history closure must target the new cards.
// Owner: ACP replay mapping; the stdio test covers ordinary completed reuse.
#[test]
fn replay_closes_superseded_occurrences_without_retargeting_their_images() {
    let image = model::ImageContent {
        data: "YWJj".into(),
        mime_type: "image/png".into(),
    };
    let image_content =
        ToolCallContent::from(ContentBlock::Image(ImageContent::new("YWJj", "image/png")));
    let messages = vec![
        Message::Assistant(vec![call_block("reused")]),
        Message::tool_image_supplement("read", "reused", vec![image.clone()]).unwrap(),
        Message::Assistant(vec![call_block("reused")]),
        Message::ToolResult(ToolResult {
            id: "reused".into(),
            ok: false,
            content: "second output".into(),
        }),
        Message::tool_image_supplement("read", "reused", vec![image]).unwrap(),
        Message::Assistant(vec![call_block("reused")]),
    ];
    assert_eq!(
        replay(&messages),
        expected(vec![
            SessionUpdate::ToolCall(tool("0")),
            SessionUpdate::ToolCallUpdate(ToolCallUpdate::new(
                ToolCallId::new("0"),
                ToolCallUpdateFields::new()
                    .status(ToolCallStatus::Pending)
                    .content(vec![image_content.clone()])
            )),
            SessionUpdate::ToolCallUpdate(ToolCallUpdate::new(
                ToolCallId::new("0"),
                ToolCallUpdateFields::new().status(ToolCallStatus::Failed)
            )),
            SessionUpdate::ToolCall(tool("1")),
            SessionUpdate::ToolCallUpdate(ToolCallUpdate::new(
                ToolCallId::new("1"),
                ToolCallUpdateFields::new()
                    .status(ToolCallStatus::Failed)
                    .content(vec![ToolCallContent::from("second output")])
                    .raw_output(json!("second output"))
            )),
            SessionUpdate::ToolCallUpdate(ToolCallUpdate::new(
                ToolCallId::new("1"),
                ToolCallUpdateFields::new()
                    .status(ToolCallStatus::Failed)
                    .content(vec![ToolCallContent::from("second output"), image_content])
            )),
            SessionUpdate::ToolCall(tool("2")),
            SessionUpdate::ToolCallUpdate(ToolCallUpdate::new(
                ToolCallId::new("2"),
                ToolCallUpdateFields::new().status(ToolCallStatus::Failed)
            )),
        ])
    );
}

// Covers: replayed chunks carry message IDs that split where live ones do
// (text after a tool call, a reasoning summary), come in live order (the
// summary before the text it led to), give equal text saved twice two IDs,
// and come out the same when the same history replays again.
// Owner: ACP replay mapping; the stdio test covers reloading a saved session.
#[test]
fn replay_message_ids_split_at_boundaries_and_repeat_across_replays() {
    let assistant = AssistantMessage {
        reasoning_summary: Some("why".into()),
        ..AssistantMessage::from_content(vec![
            model::ContentBlock::Text("before".into()),
            call_block("a"),
            model::ContentBlock::Text("after".into()),
            model::ContentBlock::Text(" more".into()),
        ])
    };
    let messages = vec![
        Message::user_text("continue"),
        Message::assistant(assistant),
        Message::ToolResult(ToolResult {
            id: "a".into(),
            ok: true,
            content: String::new(),
        }),
        Message::user_text("continue"),
    ];
    let chunks = |notifications: Vec<SessionNotification>| {
        notifications
            .into_iter()
            .filter_map(|notification| match notification.update {
                SessionUpdate::UserMessageChunk(chunk)
                | SessionUpdate::AgentMessageChunk(chunk)
                | SessionUpdate::AgentThoughtChunk(chunk) => Some(chunk),
                _ => None,
            })
            .collect::<Vec<_>>()
    };
    assert_eq!(
        chunks(replay(&messages)),
        vec![
            chunk("continue", "m0"),
            chunk("why", "m1"),
            chunk("before", "m2"),
            chunk("after", "m3"),
            chunk(" more", "m3"),
            chunk("continue", "m4"),
        ]
    );
    assert_eq!(chunks(raw_replay(&messages)), chunks(raw_replay(&messages)));
}

// Covers: a replayed call of a registered tool gets the kind its tool reports
// at start, as a live call does, including a tool that builds its metadata
// while preparing (`sessions`); an unknown tool stays `other`. The tools are
// ones every platform registers.
// Owner: ACP replay mapping; saved history keeps no tool metadata.
#[test]
fn replayed_calls_take_their_kind_from_the_session_tools() {
    let config = Config::default();
    let tool_set = AppToolSet::new(
        &config,
        RuntimeDiagnostics::new(&config),
        ToolSetOptions::new(AgentCapabilities::new(
            [
                ToolCapability::ReadFile,
                ToolCapability::Grep,
                ToolCapability::Sessions,
            ]
            .into(),
        )),
    );
    let messages = saved_rows(&[Message::assistant(AssistantMessage::from_content(vec![
        named_call_block("a", "read_file", json!({"path": "src/lib.rs"})),
        named_call_block("b", "grep", json!({"pattern": "fn main"})),
        named_call_block("s", "sessions", json!({"action": "search", "query": "x"})),
        named_call_block("c", "not_a_tool", json!({})),
    ]))]);
    let kinds: Vec<ToolKind> = history(
        &SessionId::new("s1"),
        &messages,
        std::path::Path::new(""),
        &tool_set,
    )
    .into_iter()
    .filter_map(|notification| match notification.update {
        SessionUpdate::ToolCall(call) => Some(call.kind),
        _ => None,
    })
    .collect();
    assert_eq!(
        kinds,
        vec![
            ToolKind::Read,
            ToolKind::Search,
            ToolKind::Read,
            ToolKind::Other
        ]
    );
}

// Covers: a process call's title says what it runs, as a shell call's does:
// a start is titled by its bare command, which Zed shows as an execute
// card's command, and a poll or stop names the process it acts on. Replay
// and live calls share the title, from the metadata the real tool reports.
// Owner: ACP tool titles, through the registered process tool
#[test]
fn process_call_titles_name_what_they_run() {
    let config = Config::default();
    let tool_set = AppToolSet::new(
        &config,
        RuntimeDiagnostics::new(&config),
        ToolSetOptions::new(AgentCapabilities::new([ToolCapability::Process].into())),
    );
    let command = "cd /work/app && .venv/bin/python -m unittest tests.test_app";
    let messages = saved_rows(&[Message::assistant(AssistantMessage::from_content(vec![
        named_call_block(
            "a",
            "process",
            json!({"action": "start", "command": command}),
        ),
        named_call_block(
            "b",
            "process",
            json!({"action": "poll", "process_id": "process-1"}),
        ),
        named_call_block(
            "c",
            "process",
            json!({"action": "stop", "process_id": "process-1"}),
        ),
    ]))]);
    let titles: Vec<(ToolKind, String)> = history(
        &SessionId::new("s1"),
        &messages,
        std::path::Path::new("/work"),
        &tool_set,
    )
    .into_iter()
    .filter_map(|notification| match notification.update {
        SessionUpdate::ToolCall(call) => Some((call.kind, call.title)),
        _ => None,
    })
    .collect();
    assert_eq!(
        titles,
        vec![
            (ToolKind::Execute, command.to_owned()),
            (ToolKind::Execute, "process(poll process-1)".to_owned()),
            (ToolKind::Execute, "process(stop process-1)".to_owned()),
        ]
    );
}