trusty-code 0.5.1

Per-project Claude-Code-compatible MPM orchestration harness (bin: tcode) — an original coding harness, tracked under epic #2052.
Documentation
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
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
//! Tests for `engine.rs` and its sibling modules (`engine_state.rs`,
//! `session_events.rs`, `workstream_subscription.rs`) — issue #3415.
//!
//! Why: kept as a sibling `_tests.rs` file (not inline in `engine.rs`), per
//! this crate's established convention (`serve/http.rs` -> `http_tests.rs`,
//! `workstreams/sse.rs` -> `sse_tests.rs`) — a `_tests.rs` suffix is scored
//! against the 1500-SLOC TEST cap (issue #610/#1131), not the 500-SLOC
//! PRODUCTION cap, so splitting tests out of `engine.rs` is what keeps that
//! file itself under cap without shrinking coverage.

use tokio::sync::mpsc::unbounded_channel;

use super::*;
use crate::events::{Event, SessionEventEnvelope};
use crate::tui_client::session_events::{
    forward_session_event, is_retryable_status, terminal_stream_failure_event,
};
use crate::tui_client::workstream_subscription::parse_workstream_envelope;
use trusty_code_tui::{StatuslineSegment, WorkstreamSummary};

fn envelope(event: Event) -> SessionEventEnvelope {
    SessionEventEnvelope::new("s-1".to_string(), 1, chrono::Utc::now(), event)
}

#[test]
fn forward_message_emits_assistant_output_chunk_not_done() {
    let (tx, mut rx) = unbounded_channel();
    let terminal = forward_session_event(
        envelope(Event::Message {
            session_id: "s-1".into(),
            text: "hi".into(),
        }),
        &tx,
    );
    assert!(!terminal);
    assert_eq!(
        rx.try_recv().expect("event"),
        ReplEvent::AssistantOutput {
            chunk: "hi".into(),
            done: false,
            is_error: false,
        }
    );
}

#[test]
fn forward_tool_started_emits_tool_invocation_with_call_id() {
    let (tx, mut rx) = unbounded_channel();
    let terminal = forward_session_event(
        envelope(Event::ToolStarted {
            session_id: "s-1".into(),
            agent: "pm".into(),
            agent_id: String::new(),
            tool: "bash".into(),
            call_id: "call-1".into(),
            args_preview: "ls".into(),
        }),
        &tx,
    );
    assert!(!terminal);
    match rx.try_recv().expect("event") {
        ReplEvent::ToolInvocation {
            id,
            tool_name,
            result,
            ..
        } => {
            assert_eq!(id, "call-1");
            assert_eq!(tool_name, "bash");
            assert!(result.is_none());
        }
        other => panic!("unexpected {other:?}"),
    }
}

#[test]
fn forward_tool_finished_carries_result_and_shares_call_id() {
    let (tx, mut rx) = unbounded_channel();
    forward_session_event(
        envelope(Event::ToolFinished {
            session_id: "s-1".into(),
            agent: "pm".into(),
            agent_id: String::new(),
            tool: "bash".into(),
            call_id: "call-1".into(),
            success: true,
            result_preview: "done".into(),
        }),
        &tx,
    );
    match rx.try_recv().expect("event") {
        ReplEvent::ToolInvocation { id, result, .. } => {
            assert_eq!(id, "call-1");
            assert_eq!(result.as_deref(), Some("done"));
        }
        other => panic!("unexpected {other:?}"),
    }
}

#[test]
fn forward_session_done_is_terminal() {
    let (tx, mut rx) = unbounded_channel();
    let terminal = forward_session_event(
        envelope(Event::SessionDone {
            session_id: "s-1".into(),
            status: "finished".into(),
        }),
        &tx,
    );
    assert!(terminal);
    assert_eq!(
        rx.try_recv().expect("event"),
        ReplEvent::AssistantOutput {
            chunk: String::new(),
            done: true,
            is_error: false,
        }
    );
}

#[test]
fn forward_session_done_failed_marks_is_error() {
    let (tx, mut rx) = unbounded_channel();
    forward_session_event(
        envelope(Event::SessionDone {
            session_id: "s-1".into(),
            status: "failed".into(),
        }),
        &tx,
    );
    assert_eq!(
        rx.try_recv().expect("event"),
        ReplEvent::AssistantOutput {
            chunk: String::new(),
            done: true,
            is_error: true,
        }
    );
}

#[test]
fn forward_session_cancelled_is_terminal() {
    let (tx, mut rx) = unbounded_channel();
    let terminal = forward_session_event(
        envelope(Event::SessionCancelled {
            session_id: "s-1".into(),
        }),
        &tx,
    );
    assert!(terminal);
    assert!(rx.try_recv().is_ok());
}

#[test]
fn forward_unrelated_event_is_ignored() {
    let (tx, mut rx) = unbounded_channel();
    let terminal = forward_session_event(envelope(Event::Ping), &tx);
    assert!(!terminal);
    assert!(rx.try_recv().is_err());
}

/// tcode streaming epic #3696 Slice 2: a non-final `AgentMessageDelta`
/// (`done: false`) must forward as an `AssistantOutput` chunk with
/// `done: false`, reusing the SAME append machinery `Message`/`AgentMessage`
/// use (`trusty-code-tui reduce.rs`'s `streaming_idx`-keyed append) — no new
/// rendering path.
#[test]
fn forward_agent_message_delta_not_done_appends() {
    let (tx, mut rx) = unbounded_channel();
    let terminal = forward_session_event(
        envelope(Event::AgentMessageDelta {
            session_id: "s-1".into(),
            agent: "coder".into(),
            agent_id: "agent-1".into(),
            turn_id: "turn-1".into(),
            delta: "Hello".into(),
            done: false,
        }),
        &tx,
    );
    assert!(!terminal);
    assert_eq!(
        rx.try_recv().expect("event"),
        ReplEvent::AssistantOutput {
            chunk: "Hello".into(),
            done: false,
            is_error: false,
        }
    );
}

/// The final delta (`done: true`) for a turn must forward `done: true` (so
/// `apply_assistant_output` finalizes the streaming bubble) — and, unlike
/// `SessionDone`, is NOT terminal for the SSE pump itself: one agent's turn
/// finishing doesn't mean the whole session stream is over.
#[test]
fn forward_agent_message_delta_done_finalizes() {
    let (tx, mut rx) = unbounded_channel();
    let terminal = forward_session_event(
        envelope(Event::AgentMessageDelta {
            session_id: "s-1".into(),
            agent: "coder".into(),
            agent_id: "agent-1".into(),
            turn_id: "turn-1".into(),
            delta: " world".into(),
            done: true,
        }),
        &tx,
    );
    assert!(
        !terminal,
        "an agent turn finishing must not end the SSE pump"
    );
    assert_eq!(
        rx.try_recv().expect("event"),
        ReplEvent::AssistantOutput {
            chunk: " world".into(),
            done: true,
            is_error: false,
        }
    );
}

/// Two agents streaming concurrently and sharing a `turn_id` (the Slice 0
/// contract's defensive `(agent_id, turn_id)` grouping scenario,
/// `events.rs:436-456`) must each forward as their OWN independent
/// `AssistantOutput` message, in call order — `forward_session_event` never
/// accumulates or merges chunks itself; it is a stateless 1:1 mapper.
///
/// NOTE (see PR description / module doc comment on the `AgentMessageDelta`
/// arm): this proves `forward_session_event` doesn't merge them. It does
/// NOT prove the two stay visually separate once downstream in
/// `trusty-code-tui` — `ReplEvent::AssistantOutput` carries no `agent_id`/
/// `turn_id`, and `ReplApp::streaming_idx` is a single unkeyed
/// `Option<usize>`, so today the reducer WOULD interleave them into one
/// chat bubble. That gap lives in `trusty-code-tui` (out of this crate's file
/// scope) and is tracked as a follow-up, not fixed in this slice.
#[test]
fn forward_agent_message_delta_distinct_agent_ids_not_merged() {
    let (tx, mut rx) = unbounded_channel();
    forward_session_event(
        envelope(Event::AgentMessageDelta {
            session_id: "s-1".into(),
            agent: "coder".into(),
            agent_id: "agent-1".into(),
            turn_id: "turn-shared".into(),
            delta: "from-agent-1".into(),
            done: false,
        }),
        &tx,
    );
    forward_session_event(
        envelope(Event::AgentMessageDelta {
            session_id: "s-1".into(),
            agent: "reviewer".into(),
            agent_id: "agent-2".into(),
            turn_id: "turn-shared".into(),
            delta: "from-agent-2".into(),
            done: false,
        }),
        &tx,
    );
    assert_eq!(
        rx.try_recv().expect("event"),
        ReplEvent::AssistantOutput {
            chunk: "from-agent-1".into(),
            done: false,
            is_error: false,
        },
        "agent-1's delta must forward as its own message, not merged with agent-2's"
    );
    assert_eq!(
        rx.try_recv().expect("event"),
        ReplEvent::AssistantOutput {
            chunk: "from-agent-2".into(),
            done: false,
            is_error: false,
        },
        "agent-2's delta must forward as its own message, not merged with agent-1's"
    );
}

#[test]
fn workstream_subcommand_parses_list_and_activate() {
    assert_eq!(workstream_subcommand("/workstream list"), Some("list"));
    assert_eq!(
        workstream_subcommand("/ws activate abc-123"),
        Some("activate abc-123")
    );
    assert_eq!(workstream_subcommand("/workstream"), Some(""));
    assert_eq!(workstream_subcommand("/workstreamx foo"), None);
    assert_eq!(workstream_subcommand("hello"), None);
}

#[test]
fn parse_workstream_envelope_round_trips_activation_changed() {
    let json = serde_json::json!({
        "session_id": "",
        "event_type": "workstream_activation_changed",
        "payload": {
            "type": "workstream_activation_changed",
            "new_active_id": "ws-2",
            "prior_id": "ws-1",
        },
    })
    .to_string();
    let env = parse_workstream_envelope(&json).expect("parse");
    match env.payload {
        Event::WorkstreamActivationChanged {
            new_active_id,
            prior_id,
        } => {
            assert_eq!(new_active_id.as_deref(), Some("ws-2"));
            assert_eq!(prior_id.as_deref(), Some("ws-1"));
        }
        other => panic!("unexpected {other:?}"),
    }
}

/// `pump_session_events` giving up after exhausting reconnects must produce
/// a `done: true, is_error: true` `AssistantOutput` — the epic #3411
/// deferred-verification item: a `ConnectionLost` alone never clears
/// `ReplApp::busy`, so this is what actually rules out a silent stall (a
/// stuck spinner with no visible error) once the last reconnect attempt
/// fails.
#[test]
fn terminal_stream_failure_event_is_a_done_error_output() {
    let event = terminal_stream_failure_event("daemon unreachable".to_string());
    assert_eq!(
        event,
        ReplEvent::AssistantOutput {
            chunk: "connection lost: daemon unreachable".to_string(),
            done: true,
            is_error: true,
        }
    );
}

#[test]
fn is_retryable_status_covers_502_and_503_only() {
    assert!(is_retryable_status(reqwest::StatusCode::BAD_GATEWAY));
    assert!(is_retryable_status(
        reqwest::StatusCode::SERVICE_UNAVAILABLE
    ));
    assert!(!is_retryable_status(reqwest::StatusCode::NOT_FOUND));
}

/// The caches must start empty before `setup()` populates them —
/// `TuiEngine::commands()`/`picker()` must degrade to "nothing yet," never
/// panic, when queried before `setup()` runs.
#[test]
fn caches_are_empty_before_setup() {
    let engine = CodeEngine::with_daemon_url(reqwest::Client::new(), "http://127.0.0.1:1", None);
    assert!(engine.commands().is_empty());
    assert!(engine.picker("workstream").is_none());
}

/// `picker("workstream")` must carry the exact dispatch command
/// `workstream_subcommand` parses back — proves the picker-selection
/// round trip (`"{dispatch_command} {selected.id}"`) actually reaches
/// `handle_workstream_command`'s `activate <id>` branch, not some other
/// unparsed string.
#[test]
fn workstream_picker_dispatch_command_round_trips_through_workstream_subcommand() {
    let dispatch_command = "/workstream activate";
    let resubmitted = format!("{dispatch_command} ws-1");
    assert_eq!(workstream_subcommand(&resubmitted), Some("activate ws-1"));
}

/// An unknown picker name must be `None`, not an empty-but-`Some` request —
/// this engine has exactly one picker.
#[test]
fn picker_unknown_name_is_none() {
    let engine = CodeEngine::with_daemon_url(reqwest::Client::new(), "http://127.0.0.1:1", None);
    assert!(engine.picker("model").is_none());
}

/// `EngineState::statusline_segments` must mirror the `active_workstream`
/// cache exactly: no segment before any workstream is known, one
/// `StatuslineSegment::Workstream` once it is, and — critically — an EMPTY
/// list again (not a stale segment left behind) once deactivated. This is
/// the seam `setup`/`run_workstream_subscription` push through
/// `ReplEvent::StatuslineUpdate` so the status line's "WS: name (id)"
/// segment (DOC-50 §5.3, Slice 6) tracks the daemon's actual active
/// workstream, clearing on deactivation rather than showing stale text.
#[test]
fn statusline_segments_reflect_active_workstream_and_clear_on_none() {
    let state = EngineState::new(
        RpcHttpClient::new(reqwest::Client::new(), "http://127.0.0.1:1".to_string()),
        None,
    );
    assert!(
        state.statusline_segments().is_empty(),
        "no active workstream observed yet -> no segments"
    );

    *state.active_workstream.lock().unwrap() = Some(WorkstreamSummary {
        id: "ws-1".to_string(),
        name: "Feature X".to_string(),
    });
    assert_eq!(
        state.statusline_segments(),
        vec![StatuslineSegment::Workstream {
            id: "ws-1".to_string(),
            name: "Feature X".to_string(),
        }]
    );

    *state.active_workstream.lock().unwrap() = None;
    assert!(
        state.statusline_segments().is_empty(),
        "deactivation must clear the segment, not leave a stale one"
    );
}

/// Regression test for issue #3494: a daemon that accepts the TCP
/// connection but never sends response headers must not hang
/// `pump_session_events`'s initial `GET /sessions/{id}/events` forever —
/// before this fix, `.send().await` had no per-request bound and would wait
/// indefinitely, completely bypassing `SESSION_STREAM_MAX_RECONNECTS`.
///
/// Uses a raw `TcpListener` that accepts every connection and then holds it
/// open without ever writing a byte — the exact "TCP accepted, headers
/// never sent" trigger the issue describes (a `wiremock` mock always
/// completes the HTTP handshake, so it can't reproduce this). If
/// `CONNECT_TIMEOUT` were removed, `.send().await` would still be pending
/// when the outer bound below elapses, and no `ConnectionLost` would ever
/// arrive — this test would fail deterministically on a timeout rather than
/// hang the test binary, same rationale as
/// `tests/tui_client_engine.rs`'s exhausted-reconnects test.
///
/// Deliberately does NOT wait for `pump_session_events` to exhaust all
/// `SESSION_STREAM_MAX_RECONNECTS` (every attempt would hang the same way,
/// ~1 minute total) — observing the FIRST `ConnectionLost` is sufficient
/// proof the connect attempt is bounded by `CONNECT_TIMEOUT`, not infinite.
///
/// The `CONNECT_TIMEOUT` wait itself runs on Tokio's virtual clock, but only
/// after the accept is confirmed on the real one — see the `tokio::time::pause()`
/// call below for why the ordering is load-bearing and a blanket
/// `start_paused = true` is not a valid substitute here.
#[tokio::test]
async fn events_connect_hang_is_bounded_by_connect_timeout_not_infinite() {
    let std_listener = std::net::TcpListener::bind("127.0.0.1:0").expect("bind ephemeral port");
    std_listener.set_nonblocking(true).expect("set_nonblocking");
    let listener = tokio::net::TcpListener::from_std(std_listener).expect("tokio listener");
    let addr = listener.local_addr().expect("local_addr");

    let (accepted_tx, mut accepted_rx) = unbounded_channel();
    // Accept connections forever, never writing/closing — `mem::forget`
    // keeps each accepted socket's fd open (dropping it would close the
    // connection, which reqwest would see as a fast, distinct failure mode,
    // not the hang this test targets).
    let accept_task = tokio::spawn(async move {
        while let Ok((stream, _)) = listener.accept().await {
            let _ = accepted_tx.send(());
            std::mem::forget(stream);
        }
    });

    let state = EngineState::new(
        RpcHttpClient::new(reqwest::Client::new(), format!("http://{addr}")),
        None,
    );
    let (tx, mut rx) = unbounded_channel();

    let pump_task = tokio::spawn(async move { state.pump_session_events("s-1", &tx).await });

    // Wait — on the REAL clock — until the listener has actually accepted the
    // connection. This is what makes the pause below safe: the "TCP accepted,
    // headers never sent" precondition is established for real, not assumed.
    // A blind `#[tokio::test(start_paused = true)]` here is NOT equivalent —
    // measured, it lost the accept on 6 of 10 runs (Tokio auto-advances the
    // clock while the handshake is still in flight), silently downgrading
    // this from the #3494 shape to a plain connect timeout while still
    // passing, since both produce a "connection failed" reason.
    accepted_rx
        .recv()
        .await
        .expect("listener must accept the pump's connection");

    // Only now switch to the virtual clock: the connection is up and the
    // daemon will never send headers, so the runtime goes idle and Tokio
    // auto-advances straight to `CONNECT_TIMEOUT` at no wall-clock cost
    // (this test was 10.0s of pure waiting).
    tokio::time::pause();

    // CONNECT_TIMEOUT (10s) plus slack — comfortably short of the ~1 minute
    // a full 5-reconnect exhaustion would take, but generous enough that
    // this never flakes on a loaded CI box.
    match tokio::time::timeout(CONNECT_TIMEOUT + Duration::from_secs(10), rx.recv()).await {
        Ok(Some(ReplEvent::ConnectionLost { reason })) => {
            assert!(
                reason.contains("connection failed"),
                "expected a transport-error ConnectionLost from the timed-out connect, got: \
                 {reason}"
            );
        }
        Ok(Some(other)) => panic!("expected ConnectionLost, got {other:?}"),
        Ok(None) => panic!("channel closed with no event — pump_session_events exited silently"),
        Err(_) => panic!(
            "no ConnectionLost observed within CONNECT_TIMEOUT + slack — the initial connect \
             attempt hung past CONNECT_TIMEOUT (issue #3494 regression)"
        ),
    }

    pump_task.abort();
    accept_task.abort();
}