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
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
//! #2937: the final request, made visible. Measurement only — nothing here
//! changes or prunes what is sent.
//!
//! Each wire loop calls [`ReportSink::observe_request`] with the exact system
//! texts and tools it is about to send, so the report is read off the real
//! request and cannot drift from it. Assemblers may [`ReportSink::annotate`]
//! the pieces they join into a system message (label + source); the report
//! locates each piece in the sent text and reports every remaining byte as an
//! explicit `(unattributed)` component, so the component sizes always sum to
//! the exact message length.
//!
//! Sizes are characters. Token counts are not shown: the backend reports
//! usage only after a request, and the loop's pre-send figure is an estimate.
use serde_json::Value;
use std::path::PathBuf;
use std::sync::Mutex;
/// A named piece of a system message, registered by whoever assembled it.
#[derive(Clone, Debug)]
pub struct Annotation {
pub label: String,
pub source: String,
pub text: String,
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Component {
pub label: String,
pub source: String,
pub chars: usize,
}
#[derive(Clone, Debug)]
pub struct SystemMessage {
pub text: String,
pub components: Vec<Component>,
}
#[derive(Clone, Debug)]
pub struct ToolSize {
pub name: String,
pub chars: usize,
/// The full provider-format schema, exactly as dispatched.
pub schema: Value,
}
#[derive(Clone, Debug)]
pub struct RequestReport {
pub system: Vec<SystemMessage>,
pub tools: Vec<ToolSize>,
/// Length of the serialized `tools` array; exceeds the sum of `tools` by
/// the array's brackets and commas. Zero when the provider omitted the
/// tools key entirely (distinguished from `Some(&[])` which serialises as
/// `[]`, 2 chars).
pub tools_array_chars: usize,
/// True when the provider sent no tools field at all (distinct from an
/// empty `[]` array).
pub tools_omitted: bool,
}
const UNATTRIBUTED: &str = "(unattributed)";
fn chars(s: &str) -> usize {
s.chars().count()
}
fn components_of(text: &str, notes: &[Annotation]) -> Vec<Component> {
let mut found: Vec<(usize, usize, &Annotation)> = notes
.iter()
.filter(|n| !n.text.is_empty())
.filter_map(|n| text.find(&n.text).map(|at| (at, n.text.len(), n)))
.collect();
// Earliest first; at equal starts the longer piece wins.
found.sort_by_key(|&(at, len, _)| (at, std::cmp::Reverse(len)));
let mut out = Vec::new();
let mut cursor = 0;
let mut push = |label: &str, source: &str, piece: &str| {
out.push(Component {
label: label.into(),
source: source.into(),
chars: chars(piece),
});
};
for (at, len, note) in found {
if at < cursor {
continue; // overlaps a piece already placed
}
if at > cursor {
push(
UNATTRIBUTED,
"separators and unlabelled text",
&text[cursor..at],
);
}
push(¬e.label, ¬e.source, &text[at..at + len]);
cursor = at + len;
}
if cursor < text.len() || text.is_empty() {
push(
UNATTRIBUTED,
"separators and unlabelled text",
&text[cursor..],
);
}
out
}
impl RequestReport {
/// Build from raw system texts and tools (provider format). Preferred over
/// `build` when the caller already has provider-specific values.
///
/// `tools = None` means the provider omitted the tools field entirely
/// (e.g. a cap-exit summary); `tools = Some(&[])` means an explicit empty
/// array was sent.
pub fn build_from_parts(
system_texts: &[&str],
tools: Option<&[Value]>,
notes: &[Annotation],
) -> Self {
let card = Annotation {
label: "active-prompt card".into(),
source: "agentic::prompt_read::active_prompt_card".into(),
text: String::new(),
};
let system = system_texts
.iter()
.map(|text| {
let mut ns = notes.to_vec();
if text.starts_with(super::prompt_read::ACTIVE_PROMPT_PREFIX) {
ns.push(Annotation {
text: text.to_string(),
..card.clone()
});
}
SystemMessage {
text: text.to_string(),
components: components_of(text, &ns),
}
})
.collect();
let sized = |t: &Value| ToolSize {
name: t["function"]["name"]
.as_str()
.or_else(|| t["name"].as_str())
.unwrap_or("?")
.to_string(),
chars: chars(&t.to_string()),
schema: t.clone(),
};
let (tool_sizes, tools_array_chars, tools_omitted) = match tools {
None => (vec![], 0, true),
Some(arr) => (
arr.iter().map(sized).collect(),
chars(&Value::Array(arr.to_vec()).to_string()),
false,
),
};
Self {
system,
tools: tool_sizes,
tools_array_chars,
tools_omitted,
}
}
/// Convenience: extract system messages from an OpenAI-format message list.
pub fn build(messages: &[Value], tools: Option<&[Value]>, notes: &[Annotation]) -> Self {
let texts: Vec<&str> = messages
.iter()
.filter(|m| m["role"] == "system")
.filter_map(|m| m["content"].as_str())
.collect();
Self::build_from_parts(&texts, tools, notes)
}
pub fn system_chars(&self) -> usize {
self.system.iter().map(|m| chars(&m.text)).sum()
}
pub fn to_markdown(&self) -> String {
let mut out = String::from("# Request prompt report\n\nSizes are characters (the backend reports tokens only after a request).\n");
for (i, m) in self.system.iter().enumerate() {
out.push_str(&format!(
"\n## System message {} ({} chars)\n\n| component | source | chars |\n|---|---|---:|\n",
i + 1,
chars(&m.text)
));
for c in &m.components {
out.push_str(&format!("| {} | {} | {} |\n", c.label, c.source, c.chars));
}
}
if self.tools_omitted {
out.push_str("\n## Tools (omitted by provider — no tools field sent)\n\n");
} else {
out.push_str(&format!(
"\n## Tools ({} tools, {} chars as sent)\n\n| tool | chars |\n|---|---:|\n",
self.tools.len(),
self.tools_array_chars
));
}
if !self.tools_omitted {
for t in &self.tools {
out.push_str(&format!("| {} | {} |\n", t.name, t.chars));
}
}
out.push_str(&format!(
"\nTotal: system {} + tools {} = {} chars\n",
self.system_chars(),
self.tools_array_chars,
self.system_chars() + self.tools_array_chars
));
for (i, m) in self.system.iter().enumerate() {
out.push_str(&format!(
"\n## System message {} text\n\n~~~~text\n{}\n~~~~\n",
i + 1,
m.text
));
}
// Full schemas as dispatched — the central inspection requirement.
if !self.tools.is_empty() {
out.push_str("\n## Tool schemas (as sent)\n");
for t in &self.tools {
out.push_str(&format!(
"\n### {}\n\n```json\n{}\n```\n",
t.name,
serde_json::to_string_pretty(&t.schema).unwrap_or_default()
));
}
}
out
}
}
/// Raised by [`ReportSink::observe_request`] after a successful dump write
/// when the caller asked to stop before sending.
#[derive(Debug)]
pub struct RequestDumped(pub PathBuf);
impl std::fmt::Display for RequestDumped {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "request report written to {}", self.0.display())
}
}
impl std::error::Error for RequestDumped {}
/// Session-owned capture state. One per interactive/headless session;
/// child/auxiliary calls get `None` or their own independent sink so sessions
/// cannot cross-contaminate each other's reports, dumps, or show-next flags.
pub struct ReportSink {
state: Mutex<SinkState>,
}
impl std::fmt::Debug for ReportSink {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let s = self
.state
.lock()
.unwrap_or_else(std::sync::PoisonError::into_inner);
f.debug_struct("ReportSink")
.field("show_next", &s.show_next)
.field("has_last", &s.last.is_some())
.field("dump_path", &s.dump.as_ref().map(|(p, _)| p))
.finish()
}
}
#[derive(Default)]
struct SinkState {
notes: Vec<Annotation>,
last: Option<RequestReport>,
show_next: bool,
dump: Option<(PathBuf, bool)>,
}
impl Default for ReportSink {
fn default() -> Self {
Self {
state: Mutex::new(SinkState::default()),
}
}
}
impl ReportSink {
pub fn new() -> Self {
Self::default()
}
/// Create a sink that writes the first request's report to `path` and
/// stops before sending (prepare-only / `--dump-request` mode).
pub fn prepare_and_dump(path: PathBuf) -> Self {
let state = SinkState {
dump: Some((path, true)),
..Default::default()
};
Self {
state: Mutex::new(state),
}
}
fn s(&self) -> std::sync::MutexGuard<'_, SinkState> {
self.state
.lock()
.unwrap_or_else(std::sync::PoisonError::into_inner)
}
/// Name a piece of the system message being assembled.
/// A later piece with the same label replaces the earlier one.
pub fn annotate(&self, label: &str, source: &str, text: &str) {
let mut s = self.s();
s.notes.retain(|n| n.label != label);
s.notes.push(Annotation {
label: label.into(),
source: source.into(),
text: text.into(),
});
}
/// Arm: print the report just before the next request is sent.
pub fn arm_show_next(&self) {
self.s().show_next = true;
}
/// Consume the show-next flag; returns true if it was set.
pub fn take_show_flag(&self) -> bool {
std::mem::take(&mut self.s().show_next)
}
/// Arm a prepare-only capture: the next `observe_request` stores the
/// report and returns `RequestDumped` without writing any file (the empty
/// path is the sentinel). Used by the TUI `/context request` command to
/// trigger a real turn-preparation pass through the provider path.
pub fn arm_capture_next(&self) {
self.s().dump = Some((PathBuf::new(), true));
}
/// Disarm a pending capture without consuming it. Called by the capture-turn
/// RAII guard on any early exit so the next real turn is not intercepted.
/// Idempotent: safe to call after `observe_request` already consumed the arm.
pub fn disarm_capture(&self) {
self.s().dump = None;
}
/// The report for the most recent request, if one has been built.
pub fn last_report(&self) -> Option<RequestReport> {
self.s().last.clone()
}
/// Snapshot of current annotations — lets the TUI command handler build a
/// fresh report without submitting a turn.
pub fn snapshot_notes(&self) -> Vec<Annotation> {
self.s().notes.clone()
}
/// Called at the final body-construction boundary of each provider, every
/// round and summary send. Builds and stores the report from the exact
/// provider-format values dispatched. `tools = None` means the provider
/// omitted the tools field (e.g. cap-exit summary); `tools = Some(arr)`
/// means an explicit array (possibly empty). Returns `Err(RequestDumped)`
/// when dump-and-stop mode is armed and the write succeeded; propagates
/// write errors as-is (a failed write is never silently reported as
/// success).
pub fn observe_request(
&self,
system_texts: &[&str],
tools: Option<&[Value]>,
) -> anyhow::Result<()> {
let notes = self.s().notes.clone();
let report = RequestReport::build_from_parts(system_texts, tools, ¬es);
let mut s = self.s();
let dump = s.dump.take();
if let Some((path, stop)) = dump {
// Empty path is the sentinel for arm_capture_next: store without writing.
if !path.as_os_str().is_empty() {
std::fs::write(&path, report.to_markdown())?;
}
s.last = Some(report);
if stop {
return Err(RequestDumped(path).into());
}
} else {
s.last = Some(report);
}
Ok(())
}
}
#[cfg(test)]
mod tests {
use super::*;
use serde_json::json;
fn note(label: &str, text: &str) -> Annotation {
Annotation {
label: label.into(),
source: format!("src::{label}"),
text: text.into(),
}
}
/// The component sizes of every system message sum to the exact length of
/// the text sent, whether pieces are annotated, overlapping, missing from
/// the text, or absent altogether; and the tool sizes plus the array's
/// framing equal the serialized array.
#[test]
fn component_sizes_sum_to_what_is_sent() {
let card = format!("{}\nid: 1", super::super::prompt_read::ACTIVE_PROMPT_PREFIX);
let messages = vec![
json!({"role": "system", "content": "héllo identity\n\nWorkspace: /w\n\nrules"}),
json!({"role": "system", "content": card}),
json!({"role": "user", "content": "do it"}),
];
let tools = vec![
json!({"type": "function", "function": {"name": "a", "parameters": {}}}),
json!({"type": "function", "function": {"name": "bb", "parameters": {"x": 1}}}),
];
let notes = [
note("identity", "héllo identity"),
note("workspace", "Workspace: /w"),
note("inner", "Workspace"), // overlaps "workspace": dropped
note("ghost", "not in the text"),
];
let r = RequestReport::build(&messages, Some(&tools), ¬es);
assert_eq!(r.system.len(), 2);
for m in &r.system {
let sum: usize = m.components.iter().map(|c| c.chars).sum();
assert_eq!(sum, m.text.chars().count(), "{:?}", m.components);
}
let labels: Vec<&str> = r.system[0]
.components
.iter()
.map(|c| c.label.as_str())
.collect();
assert_eq!(
labels,
["identity", UNATTRIBUTED, "workspace", UNATTRIBUTED]
);
assert_eq!(r.system[1].components[0].label, "active-prompt card");
let tool_sum: usize = r.tools.iter().map(|t| t.chars).sum();
assert_eq!(r.tools_array_chars, tool_sum + r.tools.len() + 1);
assert_eq!(r.tools[1].name, "bb");
assert!(r.to_markdown().contains("| bb |"));
// #2937: full schema must appear in the markdown output
assert!(r.to_markdown().contains("\"name\": \"bb\""));
}
#[test]
fn empty_request_reports_zero() {
// Some(&[]) = explicit empty array sent => 2 chars for `[]`
let r = RequestReport::build(&[], Some(&[]), &[]);
assert_eq!((r.system_chars(), r.tools_array_chars), (0, 2));
assert!(!r.tools_omitted);
}
/// Two independent ReportSink instances cannot cross-contaminate: separate
/// last reports, separate show-next flags, separate dump arms.
#[test]
fn session_isolation() {
let sink_a = ReportSink::new();
let sink_b = ReportSink::new();
// Annotate on A does not affect B.
sink_a.annotate("key", "src", "val");
assert!(sink_b.s().notes.is_empty());
// arm_show_next is independent.
sink_a.arm_show_next();
assert!(!sink_b.take_show_flag());
assert!(sink_a.take_show_flag());
// observe on A populates A's last but not B's.
sink_a
.observe_request(&["hello"], Some(&[json!({"name": "t1"})]))
.unwrap();
assert!(sink_a.last_report().is_some());
assert!(sink_b.last_report().is_none());
}
/// observe_request includes the full schema JSON in to_markdown().
#[test]
fn schema_in_markdown() {
let sink = ReportSink::new();
let tool = json!({"type": "function", "function": {"name": "my_tool", "description": "does stuff", "parameters": {"type": "object", "properties": {"arg": {"type": "string"}}}}});
sink.observe_request(&["sys text"], Some(&[tool])).unwrap();
let md = sink.last_report().unwrap().to_markdown();
// Should contain the description from the schema
assert!(
md.contains("does stuff"),
"schema body missing from markdown"
);
assert!(md.contains("my_tool"), "tool name missing");
}
/// A failed dump write propagates as an error; last is not set to a stale
/// value, and the sink remains usable.
#[test]
fn dump_failure_propagates() {
// Use a directory path as the dump target — fs::write to a dir fails.
let dir = std::env::temp_dir();
let sink = ReportSink::prepare_and_dump(dir.clone());
let err = sink
.observe_request(&["sys"], Some(&[]))
.expect_err("should fail writing to a directory");
// The error is NOT a RequestDumped (write failed before we could stop).
assert!(
err.downcast_ref::<RequestDumped>().is_none(),
"write failure should not look like a successful dump"
);
// last_report is None — we never stored a stale report.
assert!(sink.last_report().is_none());
}
/// None tools (omitted) vs Some(&[]) (empty array) are distinguishable.
#[test]
fn tools_omitted_vs_empty() {
let r_omitted = RequestReport::build_from_parts(&["sys"], None, &[]);
assert!(r_omitted.tools_omitted);
assert_eq!(r_omitted.tools_array_chars, 0);
assert!(r_omitted.to_markdown().contains("omitted by provider"));
let r_empty = RequestReport::build_from_parts(&["sys"], Some(&[]), &[]);
assert!(!r_empty.tools_omitted);
assert_eq!(r_empty.tools_array_chars, 2);
assert!(r_empty.to_markdown().contains("0 tools, 2 chars"));
}
/// arm_show_next is consumed exactly once by take_show_flag.
#[test]
fn show_flag_consumed_once() {
let sink = ReportSink::new();
sink.arm_show_next();
sink.observe_request(&["sys"], Some(&[])).unwrap();
assert!(
sink.take_show_flag(),
"flag should be set after arm_show_next"
);
assert!(
!sink.take_show_flag(),
"flag should be clear after first consumption"
);
}
/// snapshot_notes returns annotations without draining them.
#[test]
fn snapshot_notes_independent() {
let sink = ReportSink::new();
sink.annotate("k1", "s1", "v1");
sink.annotate("k2", "s2", "v2");
let snap = sink.snapshot_notes();
assert_eq!(snap.len(), 2);
// Notes still in sink after snapshot.
assert_eq!(sink.snapshot_notes().len(), 2);
}
/// #2937 P6: disarm_capture leaves the sink clean so the next real turn's
/// observe_request returns Ok rather than RequestDumped. The RAII guard
/// calls this on every capture-turn exit path.
#[test]
fn disarm_capture_prevents_next_observe_from_intercepting() {
let sink = ReportSink::new();
sink.arm_capture_next();
sink.disarm_capture();
let result = sink.observe_request(&["system text"], None);
assert!(
result.is_ok(),
"disarmed sink must not intercept the next observe_request"
);
// The report is still stored (observe_request always updates last).
assert!(sink.last_report().is_some());
}
/// arm_capture_next stores the report and raises RequestDumped without
/// writing a file (empty-path sentinel).
#[test]
fn arm_capture_next_stores_without_file() {
let sink = ReportSink::new();
sink.arm_capture_next();
let err = sink
.observe_request(&["system text"], Some(&[]))
.unwrap_err();
let dumped = err
.chain()
.find_map(|e| e.downcast_ref::<RequestDumped>())
.expect("RequestDumped in error chain");
// Path must be empty — no file was written.
assert!(
dumped.0.as_os_str().is_empty(),
"arm_capture_next path should be empty sentinel"
);
// Report is stored despite no file write.
assert!(sink.last_report().is_some(), "last_report should be set");
}
/// Responses loop tools fix: None when body has no tools field (empty
/// catalog), not Some(&[]).
#[test]
fn tools_none_when_body_field_absent() {
// Simulate what build_body produces for an empty catalog: no "tools" key.
let body = serde_json::json!({"instructions": "do it"});
// The fixed code: body.get("tools").and_then(...).map(...)
let send_tools: Option<&[serde_json::Value]> = body
.get("tools")
.and_then(|v| v.as_array())
.map(|a| a.as_slice());
assert!(send_tools.is_none(), "absent tools key must yield None");
// With an explicit empty array it yields Some(&[]).
let body2 = serde_json::json!({"instructions": "do it", "tools": []});
let send_tools2: Option<&[serde_json::Value]> = body2
.get("tools")
.and_then(|v| v.as_array())
.map(|a| a.as_slice());
assert!(
send_tools2.is_some(),
"explicit empty array must yield Some"
);
assert_eq!(send_tools2.unwrap().len(), 0);
}
/// Responses summary fix: reading body["instructions"] vs the outer variable.
#[test]
fn summary_reads_composed_instructions() {
// Simulate: outer `instructions` variable has the original text, but
// build_body composes it with an extra system note in `input`, yielding
// a longer body["instructions"].
let outer_instructions = "base system text";
let body = serde_json::json!({"instructions": "base system text\n\nextra note injected"});
let body_instr = body["instructions"].as_str().unwrap_or("");
// body_instr is longer than outer_instructions — the fix captures the correct one.
assert!(
body_instr.len() > outer_instructions.len(),
"body instructions should be longer (has injected note)"
);
assert!(
body_instr.contains("extra note injected"),
"body instructions should contain injected content"
);
}
/// Annotating identity and persona-overlay labels before observe_request
/// makes those labels appear in the report's system component breakdown.
#[test]
fn identity_and_persona_annotations_appear_in_report() {
let sink = ReportSink::new();
let identity = "You are a helpful assistant.";
let persona_overlay = "\nActive persona: shinobi\nBe stealthy.";
sink.annotate("identity", "build_system_prompt_with_persona", identity);
sink.annotate(
"persona-overlay",
"build_system_prompt_with_persona",
persona_overlay,
);
let system_text = format!("{identity}\n\nWorkspace: /w{persona_overlay}");
sink.observe_request(&[system_text.as_str()], None).unwrap();
let report = sink.last_report().expect("last_report after observe");
let labels: Vec<&str> = report.system[0]
.components
.iter()
.map(|c| c.label.as_str())
.collect();
assert!(
labels.contains(&"identity"),
"report should have 'identity' component; got {labels:?}"
);
assert!(
labels.contains(&"persona-overlay"),
"report should have 'persona-overlay' component; got {labels:?}"
);
}
/// arm_capture_next + observe_request returns a typed RequestDumped error
/// (not a generic failure), and last_report() is populated before the error
/// fires. The TUI Err(e) handler uses downcast_ref to distinguish this from a
/// real provider failure and skips persist_incomplete_turn.
#[test]
fn request_dumped_is_typed_clean_stop() {
let sink = ReportSink::new();
sink.arm_capture_next();
let err = sink
.observe_request(&["You are a helpful agent."], None)
.unwrap_err();
// The error chain must contain RequestDumped so the TUI can detect it.
let has_dumped = err
.chain()
.any(|c| c.downcast_ref::<RequestDumped>().is_some());
assert!(
has_dumped,
"arm_capture_next should yield RequestDumped; got {err}"
);
// The report must be stored before the error fires so last_report() works.
assert!(
sink.last_report().is_some(),
"last_report must be set even after RequestDumped"
);
}
/// Registering only the workspace suffix (not the full ctx that starts with
/// identity text) lets both "identity" and "workspace-header" appear as
/// distinct components. If the full ctx were registered, the longer span
/// would win at offset 0 and drop the identity label.
#[test]
fn workspace_header_does_not_shadow_identity() {
let sink = ReportSink::new();
let identity = "You are a helpful agent.";
let workspace_suffix = "\n\nWorkspace: /home/test\nThis is the runtime root.\n";
let ctx = format!("{identity}{workspace_suffix}");
// Production code: annotate identity, then annotate only the workspace
// suffix (not the full ctx).
sink.annotate("identity", "build_system_prompt_with_persona", identity);
sink.annotate(
"workspace-header",
"build_system_prompt_with_persona",
workspace_suffix,
);
sink.observe_request(&[ctx.as_str()], None).unwrap();
let report = sink.last_report().expect("last_report after observe");
let labels: Vec<&str> = report.system[0]
.components
.iter()
.map(|c| c.label.as_str())
.collect();
assert!(
labels.contains(&"identity"),
"identity should appear; got {labels:?}"
);
assert!(
labels.contains(&"workspace-header"),
"workspace-header should appear; got {labels:?}"
);
}
/// #2937 P2-3: when the TUI sees Err(RequestDumped) the lifecycle selection
/// logic must choose TurnCompleted, not TurnFailed. This test mirrors the
/// is_request_dumped_result pre-computation in chat.rs so it acts as a
/// regression if the detection pattern is changed.
#[test]
fn request_dumped_lifecycle_selection_maps_to_turn_completed() {
use crate::lifecycle::{self, LifecycleEvent};
use std::sync::{Arc, Mutex};
let events: Arc<Mutex<Vec<LifecycleEvent>>> = Arc::new(Mutex::new(Vec::new()));
let ev = events.clone();
let _sub = lifecycle::subscribe(move |e| ev.lock().unwrap().push(e.event.clone()));
// Mirror the detection + emit logic from chat.rs P2-3.
let response: anyhow::Result<()> = Err(RequestDumped(String::new().into()).into());
let is_request_dumped_result = response.as_ref().err().is_some_and(|e| {
e.chain()
.any(|c| c.downcast_ref::<RequestDumped>().is_some())
});
lifecycle::emit(if is_request_dumped_result || response.is_ok() {
LifecycleEvent::TurnCompleted
} else {
LifecycleEvent::TurnFailed { reason: None }
});
let captured = events.lock().unwrap().clone();
assert!(
captured
.iter()
.any(|e| matches!(e, LifecycleEvent::TurnCompleted)),
"RequestDumped must emit TurnCompleted; got {captured:?}"
);
assert!(
!captured
.iter()
.any(|e| matches!(e, LifecycleEvent::TurnFailed { .. })),
"RequestDumped must NOT emit TurnFailed; got {captured:?}"
);
}
}