Skip to main content

mj_core/
transcript.rs

1//! Transcript data shared by the worker, controller state, and the chat UI.
2//!
3//! [`ChatEntry`] is what a worker snapshot carries in its transcript tail and
4//! what the chat view renders, and [`TranscriptItem`] is the materialized
5//! form controller state persists, so both live below the modules that use
6//! them rather than inside any one of them.
7//!
8//! The text helpers that read one of those shapes live here for the same
9//! reason: the database, the projection, controller state, the compactor and
10//! the review host all need the plain text of a stored message, and none of
11//! them should have to reach up into the chat view to get it.
12
13use crate::packed_text::PackedText;
14use std::sync::Arc;
15
16use agent_client_protocol::v1::schema::{
17    ContentBlock, ContentChunk, EmbeddedResourceResource, PlanEntryStatus, ToolCallStatus, ToolKind,
18};
19use anyhow::{Result, bail};
20use serde::{Deserialize, Serialize};
21
22pub const SESSION_RESTART_TEXT: &str = "[session restarted]";
23pub const SESSION_RESTART_ITEM_PREFIX: &str = "system:session-restarted:";
24pub const WORK_INTERRUPTED_ITEM_PREFIX: &str = "system:work-interrupted:";
25/// Marks where a turn the user cancelled stopped.
26pub const TURN_INTERRUPTED_TEXT: &str = "Interrupted";
27pub const TURN_INTERRUPTED_ITEM_PREFIX: &str = "system:turn-interrupted:";
28/// Marks the point where the harness resumed work with no prompt in flight.
29pub const HARNESS_TURN_TEXT: &str = "Agent continued on its own";
30pub const HARNESS_TURN_ITEM_PREFIX: &str = "harness-turn:";
31/// User replies within an existing turn, rather than prompts that start one.
32pub const ELICITATION_REPLY_ITEM_PREFIX: &str = "elicitation-reply:";
33
34/// Shared read-time join of embedded and parked terminal output.
35/// Standalone close-time records override embedded streaming records.
36pub struct TerminalOutputs<'a, R = TerminalOutputRecord> {
37    standalone: std::collections::HashMap<&'a str, &'a R>,
38    tools: std::collections::HashMap<&'a str, (&'a [R], &'a [String])>,
39    referenced: std::collections::HashSet<&'a str>,
40}
41
42pub trait TerminalRecord: Clone {
43    fn terminal_id(&self) -> &str;
44}
45impl TerminalRecord for TerminalOutputRecord {
46    fn terminal_id(&self) -> &str {
47        &self.terminal_id
48    }
49}
50impl TerminalRecord for crate::archive::CanonicalTerminalOutput {
51    fn terminal_id(&self) -> &str {
52        &self.terminal_id
53    }
54}
55impl<'a, R: TerminalRecord> TerminalOutputs<'a, R> {
56    fn new() -> Self {
57        Self {
58            standalone: Default::default(),
59            tools: Default::default(),
60            referenced: Default::default(),
61        }
62    }
63    fn tool(&mut self, id: &'a str, embedded: &'a [R], refs: &'a [String]) {
64        self.tools.insert(id, (embedded, refs));
65        self.referenced.extend(refs.iter().map(String::as_str));
66        self.referenced
67            .extend(embedded.iter().map(TerminalRecord::terminal_id));
68    }
69    pub fn for_tool(&self, stable_id: &str) -> std::borrow::Cow<'a, [R]> {
70        let Some((embedded, refs)) = self.tools.get(stable_id) else {
71            return std::borrow::Cow::Borrowed(&[]);
72        };
73        let mut seen = std::collections::HashSet::new();
74        if embedded.iter().all(|record| {
75            seen.insert(record.terminal_id()) && !self.standalone.contains_key(record.terminal_id())
76        }) && !refs
77            .iter()
78            .any(|id| self.standalone.contains_key(id.as_str()))
79        {
80            return std::borrow::Cow::Borrowed(embedded);
81        }
82        seen.clear();
83        let mut records = Vec::new();
84        for record in *embedded {
85            let id = record.terminal_id();
86            if seen.insert(id) {
87                records.push((*self.standalone.get(id).unwrap_or(&record)).clone());
88            }
89        }
90        for id in *refs {
91            if seen.insert(id.as_str())
92                && let Some(record) = self.standalone.get(id.as_str())
93            {
94                records.push((*record).clone());
95            }
96        }
97        std::borrow::Cow::Owned(records)
98    }
99    pub fn embedded_for_tool(&self, stable_id: &str) -> &[R] {
100        self.tools
101            .get(stable_id)
102            .map_or(&[], |(records, _)| *records)
103    }
104    pub fn referenced_terminal_ids(&self) -> impl Iterator<Item = &str> {
105        self.referenced.iter().copied()
106    }
107    pub fn has_standalone(&self) -> bool {
108        !self.standalone.is_empty()
109    }
110    pub fn shown_under_tool(&self, terminal_id: &str) -> bool {
111        self.referenced.contains(terminal_id)
112    }
113}
114impl<'a> TerminalOutputs<'a> {
115    pub fn of(items: impl IntoIterator<Item = &'a TranscriptItem>) -> Self {
116        let mut outputs = Self::new();
117        for item in items {
118            match &item.body {
119                TranscriptBody::Tool {
120                    terminal_outputs,
121                    terminal_refs,
122                    ..
123                } => outputs.tool(&item.stable_id, terminal_outputs, terminal_refs),
124                TranscriptBody::TerminalOutput { record } => {
125                    outputs.standalone.insert(&record.terminal_id, record);
126                }
127                _ => {}
128            }
129        }
130        outputs
131    }
132}
133impl<'a> TerminalOutputs<'a, crate::archive::CanonicalTerminalOutput> {
134    pub fn of_canonical(
135        items: impl IntoIterator<Item = &'a crate::archive::CanonicalTranscriptItem>,
136    ) -> Self {
137        let mut outputs = Self::new();
138        for item in items {
139            match &item.body {
140                crate::archive::CanonicalTranscriptBody::Tool {
141                    terminal_outputs,
142                    terminal_refs,
143                    ..
144                } => outputs.tool(&item.stable_id, terminal_outputs, terminal_refs),
145                crate::archive::CanonicalTranscriptBody::TerminalOutput { record } => {
146                    outputs.standalone.insert(&record.terminal_id, record);
147                }
148                _ => {}
149            }
150        }
151        outputs
152    }
153}
154
155/// Where a tool's compact presentation source came from.
156#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
157#[serde(rename_all = "snake_case")]
158pub enum ToolSummarySourceKind {
159    RawInput,
160    RawOutput,
161    Title,
162}
163
164/// Bounded presentation metadata derived from an ACP tool call.
165#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
166pub struct ToolCallPresentation {
167    pub summary: String,
168    pub source: PackedText,
169    pub source_kind: ToolSummarySourceKind,
170    pub tool_kind: ToolKind,
171    /// Version of the parser rules that produced `summary`. A missing value
172    /// identifies presentation metadata written before parser versioning.
173    #[serde(default)]
174    pub summary_version: u8,
175}
176
177/// An ACP call retained as JSON text. All cached interpretations are built
178/// together; replacing the call cannot leave metadata from an older update.
179#[derive(Debug, Clone, Deserialize)]
180#[serde(from = "serde_json::Value")]
181pub struct OpaqueToolCall {
182    json: PackedText,
183    metadata: Box<ToolCallMetadata>,
184}
185
186#[derive(Debug, Clone)]
187struct ToolCallMetadata {
188    raw_status: Option<Box<str>>,
189    typed_status: Option<ToolCallStatus>,
190    id: Option<Box<str>>,
191    terminal_ids: Vec<String>,
192    fallback: bool,
193    raw_result: Option<(u32, usize, [u8; 32])>,
194}
195
196impl Serialize for OpaqueToolCall {
197    fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
198        serde_json::value::RawValue::from_string(self.json.text().into_owned())
199            .expect("opaque JSON")
200            .serialize(serializer)
201    }
202}
203impl PartialEq for OpaqueToolCall {
204    fn eq(&self, other: &Self) -> bool {
205        self.json == other.json || self.value() == other.value()
206    }
207}
208impl Eq for OpaqueToolCall {}
209
210impl From<serde_json::Value> for OpaqueToolCall {
211    fn from(value: serde_json::Value) -> Self {
212        use agent_client_protocol::v1::schema::ToolCall;
213        use sha2::{Digest, Sha256};
214        let decoded = ToolCall::deserialize(&value).ok();
215        let raw_result = (|| {
216            if !matches!(
217                value.get("status").and_then(serde_json::Value::as_str),
218                Some("completed" | "failed")
219            ) {
220                return None;
221            }
222            let raw = value.get("rawOutput")?;
223            let exit = u32::try_from(raw.get("exit_code")?.as_u64()?).ok()?;
224            let output = raw.get("output")?;
225            let (len, digest) = match output {
226                serde_json::Value::String(s) => (s.len(), Sha256::digest(s.as_bytes()).into()),
227                serde_json::Value::Array(values) => {
228                    let mut hash = Sha256::new();
229                    for value in values {
230                        hash.update([u8::try_from(value.as_u64()?).ok()?]);
231                    }
232                    (values.len(), hash.finalize().into())
233                }
234                _ => return None,
235            };
236            Some((exit, len, digest))
237        })();
238        let metadata = ToolCallMetadata {
239            raw_status: value
240                .get("status")
241                .and_then(serde_json::Value::as_str)
242                .map(Into::into),
243            typed_status: decoded.as_ref().map(|call| call.status),
244            id: value
245                .get("toolCallId")
246                .and_then(serde_json::Value::as_str)
247                .map(Into::into),
248            terminal_ids: tool_call_terminal_ids(&value),
249            fallback: decoded
250                .as_ref()
251                .is_some_and(crate::acp::is_fallback_terminal_tool_call),
252            raw_result,
253        };
254        Self {
255            json: serde_json::to_string(&value)
256                .expect("JSON Value serializes")
257                .into(),
258            metadata: Box::new(metadata),
259        }
260    }
261}
262
263impl OpaqueToolCall {
264    pub fn edit<R>(&mut self, edit: impl FnOnce(&mut serde_json::Value) -> R) -> R {
265        let mut value = self.value();
266        let result = edit(&mut value);
267        *self = value.into();
268        result
269    }
270    pub fn value(&self) -> serde_json::Value {
271        serde_json::from_str(&self.json.text()).expect("opaque call contains valid JSON")
272    }
273    pub fn decode(&self) -> serde_json::Result<agent_client_protocol::v1::schema::ToolCall> {
274        serde_json::from_str(&self.json.text())
275    }
276    pub fn raw_status(&self) -> Option<&str> {
277        self.metadata.raw_status.as_deref()
278    }
279    pub fn typed_status(&self) -> ToolCallStatus {
280        self.metadata
281            .typed_status
282            .unwrap_or(ToolCallStatus::Pending)
283    }
284    pub fn typed_valid(&self) -> bool {
285        self.metadata.typed_status.is_some()
286    }
287    pub fn id(&self) -> Option<&str> {
288        self.metadata.id.as_deref()
289    }
290    pub fn terminal_ids(&self) -> &[String] {
291        &self.metadata.terminal_ids
292    }
293    pub fn is_fallback(&self) -> bool {
294        self.metadata.fallback
295    }
296    pub fn matches_raw_result(&self, record: &TerminalOutputRecord, digest: &[u8; 32]) -> bool {
297        self.metadata.raw_result.is_some_and(|(exit, len, expected)| {
298            record.exit_code == Some(exit) && record.signal.is_none() && record.output.len() == len
299                && &expected == digest
300                // Keep exact ownership even in the event of a digest collision.
301                && record.matches_tool_raw_result(&self.value())
302        })
303    }
304}
305
306/// One interpretation of ACP terminal references for opaque metadata and
307/// transient JSON readers (for example summaries and relay update fields).
308pub fn tool_call_terminal_ids(call: &serde_json::Value) -> Vec<String> {
309    use agent_client_protocol::v1::schema::ToolCallContent;
310    let Some(serde_json::Value::Array(content)) = call.get("content") else {
311        return Vec::new();
312    };
313    content.iter().filter_map(|value| match ToolCallContent::deserialize(value) {
314        Ok(ToolCallContent::Terminal(terminal)) => Some(terminal.terminal_id.0.to_string()),
315        Ok(_) => None,
316        Err(error) => { tracing::warn!(%error, "ignoring malformed tool-call content while locating terminal output"); None }
317    }).collect()
318}
319
320/// The current value of one logical transcript item. ACP structures whose
321/// schemas can grow are kept as JSON values, while logical item identity and
322/// lifecycle remain controller-owned and stable.
323#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
324#[serde(tag = "kind", rename_all = "snake_case")]
325pub enum TranscriptBody {
326    /// A complete message at the worker's durable delivery boundary.
327    Message {
328        event: Box<crate::mailbox::MailboxEvent>,
329    },
330    User {
331        content: Vec<serde_json::Value>,
332    },
333    Agent {
334        /// Complete ACP `ContentChunk` values, including message IDs, content
335        /// metadata, and non-text content blocks.
336        chunks: Vec<serde_json::Value>,
337        streaming: bool,
338    },
339    Thought {
340        /// Complete ACP `ContentChunk` values, including message IDs, content
341        /// metadata, and non-text content blocks.
342        chunks: Vec<serde_json::Value>,
343        streaming: bool,
344    },
345    Tool {
346        /// Complete current ACP `ToolCall`, updated field-for-field as
347        /// `ToolCallUpdate` notifications arrive.
348        call: OpaqueToolCall,
349        /// Output of the terminals this call's content refers to. It is a
350        /// sibling of `call` rather than part of it because `ToolCall::update`
351        /// replaces `content` wholesale, which would discard anything injected
352        /// into the stored ACP value.
353        #[serde(default, skip_serializing_if = "Vec::is_empty")]
354        terminal_outputs: Vec<TerminalOutputRecord>,
355        /// Every terminal this call has ever referred to. Agents that replace
356        /// `content` wholesale can drop a terminal reference before the
357        /// terminal is reaped, so the current call is not enough to decide
358        /// where a terminal's output belongs.
359        #[serde(default, skip_serializing_if = "Vec::is_empty")]
360        terminal_refs: Vec<String>,
361        /// Cached label data used by Rich and browser projections. Older
362        /// transcript items omit this and derive it from `call` when read.
363        #[serde(default, skip_serializing_if = "Option::is_none")]
364        presentation: Option<Box<ToolCallPresentation>>,
365    },
366    /// Terminal output that no tool call refers to yet. It becomes a
367    /// `Tool` item's `terminal_outputs` entry as soon as a call naming the
368    /// terminal arrives, and stays here permanently otherwise so output is
369    /// never dropped.
370    TerminalOutput {
371        record: TerminalOutputRecord,
372    },
373    Plan {
374        /// Complete current ACP `Plan`, including entry priorities and all
375        /// plan- and entry-level metadata.
376        plan: serde_json::Value,
377    },
378    /// A plan the harness asked the user to approve, captured where the
379    /// decision happened so it renders inline and survives restart and export.
380    ///
381    /// It is a record of the proposal, not conversation input: Hel never
382    /// replays it to a model as a user or agent message.
383    PlanProposal {
384        /// Identity of the plan review that carried this proposal.
385        proposal_id: String,
386        /// Exact proposal text the harness sent.
387        plan: String,
388    },
389    System {
390        text: String,
391    },
392}
393
394/// Append one ACP `ContentChunk` value to a transcript item's chunk list,
395/// merging it into the previous chunk when the two are the same text stream.
396///
397/// Agents stream text one token at a time, so a long turn arrives as
398/// thousands of chunks that differ only in `content.text`. Stored separately
399/// they cost far more memory than the text they carry: each chunk is its own
400/// pair of nested `serde_json::Value` maps. Merging them keeps one chunk per
401/// run of text, which is what every reader of `chunks` already reconstructs.
402///
403/// Two chunks merge only when nothing but the text differs: both are objects
404/// whose `content.type` is `"text"` with a string `content.text`, their
405/// `messageId` values are equal (both absent counts as equal), and every
406/// other top-level key (such as `meta`) and every other `content` key (such
407/// as `annotations`) is identical. Anything else is pushed as its own chunk.
408pub fn push_content_chunk(chunks: &mut Vec<serde_json::Value>, chunk: serde_json::Value) {
409    if chunks
410        .last()
411        .is_some_and(|last| text_chunks_mergeable(last, &chunk))
412    {
413        let addition = chunk
414            .get("content")
415            .and_then(|content| content.get("text"))
416            .and_then(serde_json::Value::as_str)
417            .unwrap_or_default()
418            .to_owned();
419        if let Some(serde_json::Value::Object(last)) = chunks.last_mut()
420            && let Some(serde_json::Value::Object(content)) = last.get_mut("content")
421            && let Some(serde_json::Value::String(text)) = content.get_mut("text")
422        {
423            text.push_str(&addition);
424            return;
425        }
426    }
427    chunks.push(chunk);
428}
429
430/// Collapse runs of per-token text chunks that were stored before they were
431/// merged on the way in. Rebuilds the list through [`push_content_chunk`], so
432/// it applies exactly the same merge rule and leaves chunk boundaries that
433/// carry real differences (a new message ID, non-text content, differing
434/// metadata) where they are.
435pub fn coalesce_content_chunks(chunks: &mut Vec<serde_json::Value>) {
436    if chunks.len() < 2 {
437        return;
438    }
439    let mut merged = Vec::with_capacity(chunks.len());
440    for chunk in std::mem::take(chunks) {
441        push_content_chunk(&mut merged, chunk);
442    }
443    merged.shrink_to_fit();
444    *chunks = merged;
445}
446
447/// Whether `next` carries only more text for the same stream as `last`, so
448/// the two can share one chunk. The single definition of the merge rule used
449/// by both [`push_content_chunk`] and [`coalesce_content_chunks`].
450fn text_chunks_mergeable(last: &serde_json::Value, next: &serde_json::Value) -> bool {
451    let (serde_json::Value::Object(last), serde_json::Value::Object(next)) = (last, next) else {
452        return false;
453    };
454    let (
455        Some(serde_json::Value::Object(last_content)),
456        Some(serde_json::Value::Object(next_content)),
457    ) = (last.get("content"), next.get("content"))
458    else {
459        return false;
460    };
461    let is_text = |content: &serde_json::Map<String, serde_json::Value>| {
462        content.get("type").and_then(serde_json::Value::as_str) == Some("text")
463            && content
464                .get("text")
465                .is_some_and(serde_json::Value::is_string)
466    };
467    if !is_text(last_content) || !is_text(next_content) {
468        return false;
469    }
470    // Every other top-level key, `messageId` and `meta` included, must match.
471    if last.len() != next.len()
472        || !last
473            .iter()
474            .all(|(key, value)| key == "content" || next.get(key) == Some(value))
475    {
476        return false;
477    }
478    // ... as must every other content key, such as `annotations`.
479    last_content.len() == next_content.len()
480        && last_content
481            .iter()
482            .all(|(key, value)| key == "text" || next_content.get(key) == Some(value))
483}
484
485/// What one client-run terminal produced, as hel recorded it when the child
486/// was reaped. `exit_code` and `signal` mirror ACP `TerminalExitStatus`; both
487/// are `None` when the terminal was released before a status was observed.
488#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
489pub struct TerminalOutputRecord {
490    pub terminal_id: String,
491    pub output: PackedText,
492    #[serde(default, skip_serializing_if = "is_false")]
493    pub truncated: bool,
494    #[serde(default, skip_serializing_if = "Option::is_none")]
495    pub exit_code: Option<u32>,
496    #[serde(default, skip_serializing_if = "Option::is_none")]
497    pub signal: Option<String>,
498}
499
500impl TerminalOutputRecord {
501    /// Compute once before comparing one terminal event with the tool window.
502    pub fn raw_result_digest(&self) -> [u8; 32] {
503        use sha2::{Digest, Sha256};
504        Sha256::digest(self.output.text().as_bytes()).into()
505    }
506
507    /// Whether the command ended the way a caller asked for: exit status zero
508    /// and no signal. Anything else — a nonzero exit, a signal, or no status at
509    /// all because the terminal was released before one was observed — is
510    /// abnormal, and stays visible in every render mode.
511    pub fn exited_cleanly(&self) -> bool {
512        self.exit_code == Some(0) && self.signal.is_none()
513    }
514
515    /// Whether a completed ACP tool's provider-specific raw result is this
516    /// child result. Kimi reports shell output as a byte array beside its exit
517    /// status but omits the ACP terminal reference, so the exact result is the
518    /// only ownership information it publishes.
519    pub fn matches_tool_raw_result(&self, call: &serde_json::Value) -> bool {
520        if !matches!(
521            call.get("status").and_then(serde_json::Value::as_str),
522            Some("completed" | "failed")
523        ) {
524            return false;
525        }
526        let Some(raw) = call.get("rawOutput") else {
527            return false;
528        };
529        let Some(exit_code) = raw
530            .get("exit_code")
531            .and_then(serde_json::Value::as_u64)
532            .and_then(|code| u32::try_from(code).ok())
533        else {
534            return false;
535        };
536        if self.exit_code != Some(exit_code) || self.signal.is_some() {
537            return false;
538        }
539        match raw.get("output") {
540            Some(serde_json::Value::Array(bytes)) => {
541                bytes.len() == self.output.len()
542                    && bytes
543                        .iter()
544                        .zip(self.output.text().as_bytes())
545                        .all(|(value, byte)| value.as_u64() == Some(u64::from(*byte)))
546            }
547            Some(serde_json::Value::String(output)) => output == self.output.text().as_ref(),
548            _ => false,
549        }
550    }
551}
552
553#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
554#[serde(deny_unknown_fields)]
555pub struct TranscriptItem {
556    pub stable_id: String,
557    /// Ordinal of the relay event that first created this logical item.
558    pub position: u64,
559    /// Ordinal of the most recent content chunk for an agent message. This is
560    /// `None` for every other logical item.
561    pub latest_content_event_ordinal: Option<u64>,
562    pub created_at_ms: i64,
563    pub last_changed_at_ms: i64,
564    pub body: TranscriptBody,
565}
566
567impl TranscriptItem {
568    pub fn is_work_interruption(&self) -> bool {
569        self.stable_id.starts_with(WORK_INTERRUPTED_ITEM_PREFIX)
570    }
571
572    pub fn is_session_restart(&self) -> bool {
573        self.stable_id.starts_with(SESSION_RESTART_ITEM_PREFIX)
574    }
575
576    /// The relay ordinal a reader pages by.
577    ///
578    /// An agent message is rewritten as its content streams in, and its
579    /// `latest_content_event_ordinal` is where that stopped, so paging by it
580    /// hands a caller the finished message once instead of the partial one it
581    /// was created with. Every other body is created once, so its position is
582    /// its sequence.
583    pub fn seq(&self) -> u64 {
584        self.latest_content_event_ordinal.unwrap_or(self.position)
585    }
586
587    /// A submitted prompt, excluding replies within an existing turn.
588    pub fn is_user_prompt(&self) -> bool {
589        matches!(self.body, TranscriptBody::User { .. })
590            && !self.stable_id.starts_with(ELICITATION_REPLY_ITEM_PREFIX)
591    }
592
593    /// Whether this item begins a turn: a user prompt, or the marker for a
594    /// turn the harness started on its own. The recovery boundary and the
595    /// scope of a plan update both key on the newest of these.
596    pub fn is_turn_start(&self) -> bool {
597        self.is_user_prompt() || self.stable_id.starts_with(HARNESS_TURN_ITEM_PREFIX)
598    }
599
600    pub fn is_nonempty_agent_message(&self) -> bool {
601        let TranscriptBody::Agent { chunks, .. } = &self.body else {
602            return false;
603        };
604        chunks.iter().any(|chunk| {
605            let Some(content) = chunk.get("content") else {
606                return false;
607            };
608            match content.get("type").and_then(serde_json::Value::as_str) {
609                Some("text") => content
610                    .get("text")
611                    .and_then(serde_json::Value::as_str)
612                    .is_some_and(|text| !text.trim().is_empty()),
613                Some(_) => true,
614                None => false,
615            }
616        })
617    }
618
619    pub fn validate(&self, through: u64) -> Result<()> {
620        if self.stable_id.trim().is_empty() {
621            bail!("materialized transcript item has an empty stable id");
622        }
623        if self.position == 0 || self.position > through {
624            bail!(
625                "materialized transcript item {:?} has invalid position {} at frontier {through}",
626                self.stable_id,
627                self.position
628            );
629        }
630        match (&self.body, self.latest_content_event_ordinal) {
631            (TranscriptBody::Agent { .. }, Some(ordinal))
632                if ordinal >= self.position && ordinal <= through => {}
633            (TranscriptBody::Agent { .. }, Some(ordinal)) => bail!(
634                "materialized agent message {:?} has invalid latest content ordinal {ordinal} at position {} and frontier {through}",
635                self.stable_id,
636                self.position
637            ),
638            (TranscriptBody::Agent { .. }, None) => bail!(
639                "materialized agent message {:?} has no latest content ordinal",
640                self.stable_id
641            ),
642            (_, Some(ordinal)) => bail!(
643                "non-agent transcript item {:?} has latest content ordinal {ordinal}",
644                self.stable_id
645            ),
646            (_, None) => {}
647        }
648        if let TranscriptBody::Message { event } = &self.body {
649            anyhow::ensure!(
650                !event.key.trim().is_empty()
651                    && event.message_text().is_some()
652                    && self.stable_id == message_item_id(&event.key),
653                "invalid message transcript entry {:?}",
654                self.stable_id
655            );
656        }
657        if self.last_changed_at_ms < self.created_at_ms {
658            bail!(
659                "materialized transcript item {:?} changed before it was created",
660                self.stable_id
661            );
662        }
663        Ok(())
664    }
665}
666
667#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
668pub enum ChatRole {
669    User,
670    Agent,
671    Message,
672    /// Agent reasoning stream, rendered dimmed.
673    Thought,
674    /// Tool invocation titles.
675    Tool,
676    /// Current agent plan.
677    Plan,
678    /// A plan proposal awaiting, or already given, a decision.
679    PlanProposal,
680    System,
681}
682
683#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
684pub struct ChatEntry {
685    #[serde(default)]
686    pub start_seq: u64,
687    pub seq: u64,
688    pub role: ChatRole,
689    pub text: String,
690    pub recorded_at_ms: Option<i64>,
691    /// When a finished tool call last changed, which is when it ended.
692    /// `None` for a call still running and for every other role.
693    #[serde(default, skip_serializing_if = "Option::is_none")]
694    pub tool_ended_at_ms: Option<i64>,
695    pub revision: u64,
696    pub message_id: Option<String>,
697    #[serde(default, skip_serializing_if = "Option::is_none")]
698    pub incoming_message: Option<Box<crate::mailbox::MailboxEvent>>,
699    pub tool_call_id: Option<String>,
700    pub tool_status: Option<ToolStatus>,
701    /// Compact label used by Rich and browser projections. `text` remains the
702    /// original provider title for Raw mode.
703    #[serde(default, skip_serializing_if = "Option::is_none")]
704    pub tool_summary: Option<String>,
705    /// Selected bounded source retained so partial ACP updates can preserve a
706    /// raw-command-derived summary without retaining arbitrary raw JSON.
707    #[serde(default, skip_serializing_if = "Option::is_none")]
708    pub tool_presentation: Option<ToolCallPresentation>,
709    /// ACP arguments, kept separately so result updates cannot erase them.
710    #[serde(default, skip_serializing_if = "Option::is_none")]
711    pub tool_input: Option<serde_json::Value>,
712    /// A diagnostic reported in ACP `rawOutput.error`, kept separate from
713    /// textual tool content so partial result updates can replace it.
714    #[serde(default, skip_serializing_if = "Option::is_none")]
715    pub tool_error: Option<String>,
716    pub tool_content: Vec<String>,
717    pub tool_diffstats: Vec<String>,
718    pub tool_locations: Vec<String>,
719    pub plan: Vec<PlanLine>,
720    #[serde(default, skip_serializing_if = "is_false")]
721    pub leading_omitted: bool,
722    /// Detail the decluttered feed leaves out: the entry renders only in the
723    /// raw transcript mode. Set once, when the entry is built, because Alt-T
724    /// switches render mode without rebuilding entries.
725    #[serde(default, skip_serializing_if = "is_false")]
726    pub raw_only: bool,
727    /// A completed tool call whose turn was interrupted while it ran. The
728    /// harness kept the command going and it ended later on its own, so its
729    /// completion is not the agent's finished work.
730    #[serde(default, skip_serializing_if = "is_false")]
731    pub ended_after_interrupt: bool,
732    /// The materialized transcript item this entry was derived from, when it
733    /// came from the controller's projection. Provenance only, so it is
734    /// neither serialized nor part of the entry's value.
735    #[serde(skip)]
736    pub source: TranscriptSource,
737}
738
739/// Handle on the transcript item an entry was derived from. Unchanged items
740/// keep the same `Arc` from one projection to the next, so a pointer
741/// comparison replaces re-reading the item and re-parsing its JSON.
742///
743/// The handle records where an entry came from, not what it says, so two
744/// entries with equal content are equal whatever they were derived from.
745#[derive(Debug, Clone, Default)]
746pub struct TranscriptSource(pub Option<Arc<TranscriptItem>>);
747
748impl TranscriptSource {
749    pub fn is(&self, item: &Arc<TranscriptItem>) -> bool {
750        self.0
751            .as_ref()
752            .is_some_and(|source| Arc::ptr_eq(source, item))
753    }
754}
755
756impl PartialEq for TranscriptSource {
757    fn eq(&self, _other: &Self) -> bool {
758        true
759    }
760}
761
762impl Eq for TranscriptSource {}
763
764impl ChatEntry {
765    pub fn received_message(seq: u64, event: &crate::mailbox::MailboxEvent) -> Self {
766        let mut entry = Self::plain(
767            seq,
768            ChatRole::Message,
769            event
770                .message_text()
771                .expect("message entry carries a message event"),
772        );
773        entry.message_id = Some(message_item_id(&event.key));
774        entry.incoming_message = Some(Box::new(event.clone()));
775        entry
776    }
777
778    /// Whether this entry is the durable marker emitted when a session's
779    /// control plane restarts. The source identity is authoritative for
780    /// materialized entries; the role/text check also covers entries built
781    /// from older worker snapshots that have no materialized source handle.
782    pub fn is_session_restart(&self) -> bool {
783        self.source
784            .0
785            .as_ref()
786            .is_some_and(|item| item.is_session_restart())
787            || (self.role == ChatRole::System && self.text == SESSION_RESTART_TEXT)
788    }
789
790    /// Whether this entry is a message the user wrote, including an answer
791    /// to an agent's question. Prompts that Mjolnir submits on the user's
792    /// behalf are excluded: every [`crate::continuation::GeneratedPrompt`]
793    /// and text marked as generated. Authorization evidence asks the same
794    /// two predicates, so the two cannot disagree.
795    pub fn is_user_authored(&self) -> bool {
796        // An entry without a source is a prompt submitted from this client
797        // that the controller has not yet projected.
798        self.role == ChatRole::User
799            && crate::continuation::is_user_authored_message(
800                self.source.0.as_ref().map(|item| item.stable_id.as_str()),
801                &self.text,
802            )
803    }
804
805    pub fn plan(seq: u64, plan: Vec<PlanLine>) -> Self {
806        Self {
807            start_seq: seq,
808            seq,
809            role: ChatRole::Plan,
810            text: String::new(),
811            recorded_at_ms: None,
812            tool_ended_at_ms: None,
813            revision: 0,
814            message_id: None,
815            incoming_message: None,
816            tool_call_id: None,
817            tool_status: None,
818            tool_summary: None,
819            tool_presentation: None,
820            tool_input: None,
821            tool_error: None,
822            tool_content: Vec::new(),
823            tool_diffstats: Vec::new(),
824            tool_locations: Vec::new(),
825            plan,
826            leading_omitted: false,
827            raw_only: false,
828            ended_after_interrupt: false,
829            source: TranscriptSource::default(),
830        }
831    }
832
833    pub fn touch(&mut self, seq: u64) {
834        self.seq = seq;
835        self.revision = self.revision.wrapping_add(1);
836    }
837
838    /// Bound one entry to the sizes the dashboard's summary tolerates.
839    ///
840    /// Compiled unconditionally and hidden from the documentation because the
841    /// chat crate's tests need it, and a `#[cfg(test)]` item is invisible to
842    /// another crate.
843    #[doc(hidden)]
844    pub fn bounded_for_dashboard(mut self) -> Self {
845        self.bound_dashboard_content();
846        self
847    }
848
849    fn bound_dashboard_content(&mut self) {
850        const TEXT_BYTES: usize = 64 * 1024;
851        const DETAIL_BYTES: usize = 2 * 1024;
852        const DETAIL_COUNT: usize = 8;
853
854        self.leading_omitted |= truncate_string_start(&mut self.text, TEXT_BYTES);
855        // Dashboard summaries do not expand tool arguments.
856        self.tool_input = None;
857        if let Some(error) = &mut self.tool_error {
858            truncate_string_start(error, DETAIL_BYTES);
859        }
860        for values in [
861            &mut self.tool_content,
862            &mut self.tool_diffstats,
863            &mut self.tool_locations,
864        ] {
865            values.truncate(DETAIL_COUNT);
866            for value in values {
867                truncate_string_start(value, DETAIL_BYTES);
868            }
869        }
870        if let Some(summary) = &mut self.tool_summary {
871            truncate_string_start(summary, DETAIL_BYTES);
872        }
873        if let Some(presentation) = &mut self.tool_presentation {
874            truncate_string_start(&mut presentation.summary, DETAIL_BYTES);
875            let mut source = presentation.source.text().into_owned();
876            truncate_string_start(&mut source, TEXT_BYTES);
877            presentation.source = source.into();
878        }
879        self.plan.truncate(DETAIL_COUNT);
880        for line in &mut self.plan {
881            truncate_string_start(&mut line.text, DETAIL_BYTES);
882        }
883    }
884
885    pub fn with_recorded_at(mut self, recorded_at_ms: Option<i64>) -> Self {
886        self.recorded_at_ms = recorded_at_ms;
887        self
888    }
889}
890
891/// Constructors that sanitize the text they are given, so terminal escape
892/// sequences from a harness never reach a transcript entry.
893impl ChatEntry {
894    pub fn plain(seq: u64, role: ChatRole, text: impl Into<String>) -> Self {
895        Self {
896            start_seq: seq,
897            seq,
898            role,
899            text: sanitize_terminal_text(&text.into()),
900            recorded_at_ms: None,
901            tool_ended_at_ms: None,
902            revision: 0,
903            message_id: None,
904            incoming_message: None,
905            tool_call_id: None,
906            tool_status: None,
907            tool_summary: None,
908            tool_presentation: None,
909            tool_input: None,
910            tool_error: None,
911            tool_content: Vec::new(),
912            tool_diffstats: Vec::new(),
913            tool_locations: Vec::new(),
914            plan: Vec::new(),
915            leading_omitted: false,
916            raw_only: false,
917            ended_after_interrupt: false,
918            source: TranscriptSource::default(),
919        }
920    }
921
922    pub fn tool(
923        seq: u64,
924        title: impl Into<String>,
925        tool_call_id: Option<String>,
926        tool_status: ToolStatus,
927    ) -> Self {
928        Self {
929            start_seq: seq,
930            seq,
931            role: ChatRole::Tool,
932            text: sanitize_terminal_text(&title.into()),
933            recorded_at_ms: None,
934            tool_ended_at_ms: None,
935            revision: 0,
936            message_id: None,
937            incoming_message: None,
938            tool_call_id,
939            tool_status: Some(tool_status),
940            tool_summary: None,
941            tool_presentation: None,
942            tool_input: None,
943            tool_error: None,
944            tool_content: Vec::new(),
945            tool_diffstats: Vec::new(),
946            tool_locations: Vec::new(),
947            plan: Vec::new(),
948            leading_omitted: false,
949            raw_only: false,
950            ended_after_interrupt: false,
951            source: TranscriptSource::default(),
952        }
953    }
954}
955
956pub(crate) fn is_false(value: &bool) -> bool {
957    !*value
958}
959
960pub fn plan_status(status: &PlanEntryStatus) -> PlanStatus {
961    match status {
962        PlanEntryStatus::InProgress => PlanStatus::Running,
963        PlanEntryStatus::Completed => PlanStatus::Completed,
964        _ => PlanStatus::Pending,
965    }
966}
967
968/// Remove terminal controls while preserving user-visible whitespace.
969pub fn sanitize_terminal_text(text: &str) -> String {
970    let mut sanitized = String::with_capacity(text.len());
971    let mut chars = text.chars().peekable();
972    while let Some(ch) = chars.next() {
973        if ch == '\x1b' {
974            // One escape can end at the ESC introducing the next one, so keep
975            // consuming rather than recursing: transcript text is untrusted and
976            // may nest these arbitrarily deep.
977            while consume_escape_body(&mut chars) {}
978        } else if ch == '\r' {
979            if chars.peek() != Some(&'\n') {
980                sanitized.push('\n');
981            }
982        } else if matches!(ch, '\n' | '\t') || !ch.is_control() {
983            sanitized.push(ch);
984        }
985    }
986    sanitized
987}
988
989/// Consume one escape sequence's body, after its introducing ESC. Returns
990/// whether the body ended at another ESC, which introduces the next sequence.
991///
992/// Dropping the ESC alone is not enough: an OSC payload (a build tool setting
993/// the window title) or the second byte of a charset selection would otherwise
994/// reach the transcript as visible text.
995fn consume_escape_body(chars: &mut std::iter::Peekable<std::str::Chars<'_>>) -> bool {
996    match chars.next() {
997        // CSI: parameter and intermediate bytes up to a final byte.
998        Some('[') => {
999            let _ = chars.find(|ch| ('@'..='~').contains(ch));
1000            false
1001        }
1002        // OSC, DCS, SOS, PM, and APC all carry a string payload.
1003        Some(']' | 'P' | 'X' | '^' | '_') => consume_string_body(chars),
1004        // Two-byte sequences: charset selection (ESC ( B), ESC # 8, ESC SP F.
1005        Some('(' | ')' | '*' | '+' | '-' | '.' | '/' | '#' | '%' | ' ') => {
1006            chars.next();
1007            false
1008        }
1009        // Everything else is a complete one-byte escape: ESC 7, ESC 8, ESC M,
1010        // ESC =, and a trailing ESC with nothing after it.
1011        _ => false,
1012    }
1013}
1014
1015/// Consume a string payload, which ends at BEL or at ST (ESC \). A line break
1016/// or a cancel control aborts it instead, so one malformed OSC cannot swallow
1017/// the rest of a transcript.
1018fn consume_string_body(chars: &mut std::iter::Peekable<std::str::Chars<'_>>) -> bool {
1019    while let Some(&ch) = chars.peek() {
1020        match ch {
1021            '\n' | '\r' | '\x18' | '\x1a' => return false,
1022            '\x07' => {
1023                chars.next();
1024                return false;
1025            }
1026            '\x1b' => {
1027                chars.next();
1028                return true;
1029            }
1030            _ => {
1031                chars.next();
1032            }
1033        }
1034    }
1035    false
1036}
1037
1038pub fn materialized_content_text(content: &[serde_json::Value]) -> String {
1039    let text = content
1040        .iter()
1041        .map(materialized_value_text)
1042        .filter(|text| !text.is_empty())
1043        .collect::<Vec<_>>()
1044        .join("\n");
1045    crate::relay::strip_hidden_prompt_context(&text).to_owned()
1046}
1047
1048/// What produced a transcript item, as a stable wire name.
1049///
1050/// The chat view has its own role enum shaped around how it renders; this is
1051/// the name the HTTP API publishes, so it changes only when the transcript
1052/// model does.
1053#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
1054#[serde(rename_all = "snake_case")]
1055pub enum TranscriptRole {
1056    User,
1057    Agent,
1058    Message,
1059    Thought,
1060    Tool,
1061    Terminal,
1062    Plan,
1063    PlanProposal,
1064    System,
1065}
1066
1067impl TranscriptRole {
1068    pub fn as_str(self) -> &'static str {
1069        match self {
1070            Self::User => "user",
1071            Self::Agent => "agent",
1072            Self::Message => "message",
1073            Self::Thought => "thought",
1074            Self::Tool => "tool",
1075            Self::Terminal => "terminal",
1076            Self::Plan => "plan",
1077            Self::PlanProposal => "plan_proposal",
1078            Self::System => "system",
1079        }
1080    }
1081    pub fn storage_kind(self) -> &'static str {
1082        match self {
1083            Self::Terminal => "terminal_output",
1084            other => other.as_str(),
1085        }
1086    }
1087}
1088
1089pub fn transcript_item_role(body: &TranscriptBody) -> &'static str {
1090    let role = match body {
1091        TranscriptBody::User { .. } => TranscriptRole::User,
1092        TranscriptBody::Agent { .. } => TranscriptRole::Agent,
1093        TranscriptBody::Message { .. } => TranscriptRole::Message,
1094        TranscriptBody::Thought { .. } => TranscriptRole::Thought,
1095        TranscriptBody::Tool { .. } => TranscriptRole::Tool,
1096        TranscriptBody::TerminalOutput { .. } => TranscriptRole::Terminal,
1097        TranscriptBody::Plan { .. } => TranscriptRole::Plan,
1098        TranscriptBody::PlanProposal { .. } => TranscriptRole::PlanProposal,
1099        TranscriptBody::System { .. } => TranscriptRole::System,
1100    };
1101    role.as_str()
1102}
1103
1104pub fn message_item_id(event_key: &str) -> String {
1105    format!("message:{event_key}")
1106}
1107
1108/// Recover an assistant message by its stable transcript identity.
1109pub fn materialized_agent_message_text<'a>(
1110    mut items: impl Iterator<Item = &'a TranscriptItem>,
1111    stable_id: &str,
1112) -> Option<String> {
1113    let item = items.find(|item| item.stable_id == stable_id)?;
1114    match &item.body {
1115        TranscriptBody::Agent { chunks, .. } => Some(materialized_chunks_text(chunks)),
1116        _ => None,
1117    }
1118}
1119
1120pub fn materialized_chunks_text(chunks: &[serde_json::Value]) -> String {
1121    chunks
1122        .iter()
1123        .filter_map(|value| match ContentChunk::deserialize(value) {
1124            Ok(chunk) => Some(chunk),
1125            Err(error) => {
1126                tracing::warn!(%error, "could not decode a stored content chunk");
1127                None
1128            }
1129        })
1130        .filter_map(|chunk| content_block_text(&chunk.content))
1131        .map(|text| sanitize_terminal_text(&text))
1132        .collect::<Vec<_>>()
1133        .join("")
1134}
1135
1136fn materialized_value_text(value: &serde_json::Value) -> String {
1137    if let Ok(block) = ContentBlock::deserialize(value)
1138        && let Some(text) = content_block_text(&block)
1139    {
1140        return sanitize_terminal_text(&text);
1141    }
1142    if let Some(text) = value.as_str() {
1143        return sanitize_terminal_text(text);
1144    }
1145    sanitize_terminal_text(&serde_json::to_string(value).unwrap_or_else(|_| "[content]".into()))
1146}
1147
1148pub fn tool_status(status: &ToolCallStatus) -> ToolStatus {
1149    match status {
1150        ToolCallStatus::InProgress => ToolStatus::Running,
1151        ToolCallStatus::Completed => ToolStatus::Completed,
1152        ToolCallStatus::Failed => ToolStatus::Failed,
1153        _ => ToolStatus::Pending,
1154    }
1155}
1156
1157pub fn content_block_text(content: &ContentBlock) -> Option<String> {
1158    match content {
1159        ContentBlock::Text(text) => Some(text.text.clone()),
1160        ContentBlock::Image(_) => Some("[image]".into()),
1161        ContentBlock::Audio(_) => Some("[audio]".into()),
1162        ContentBlock::ResourceLink(link) => Some(format!("[{}]({})", link.name, link.uri)),
1163        ContentBlock::Resource(resource) => Some(match &resource.resource {
1164            EmbeddedResourceResource::TextResourceContents(resource) => resource.text.clone(),
1165            EmbeddedResourceResource::BlobResourceContents(resource) => {
1166                format!("[embedded resource: {}]", resource.uri)
1167            }
1168            _ => "[embedded resource]".into(),
1169        }),
1170        _ => None,
1171    }
1172}
1173
1174pub fn truncate_string_start(value: &mut String, maximum_bytes: usize) -> bool {
1175    if value.len() <= maximum_bytes {
1176        return false;
1177    }
1178    let mut start = value.len() - maximum_bytes;
1179    while !value.is_char_boundary(start) {
1180        start += 1;
1181    }
1182    value.drain(..start);
1183    true
1184}
1185
1186/// The ACP tool states needed to keep a compact tool block visually useful.
1187#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
1188pub enum ToolStatus {
1189    Pending,
1190    Running,
1191    Completed,
1192    Failed,
1193}
1194
1195#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
1196pub enum PlanStatus {
1197    Pending,
1198    Running,
1199    Completed,
1200}
1201
1202#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
1203pub struct PlanLine {
1204    pub text: String,
1205    pub status: PlanStatus,
1206}
1207
1208#[cfg(test)]
1209mod tests {
1210    use super::*;
1211    use serde_json::json;
1212
1213    fn text_chunk(text: &str, message_id: Option<&str>) -> serde_json::Value {
1214        match message_id {
1215            Some(id) => json!({"content": {"type": "text", "text": text}, "messageId": id}),
1216            None => json!({"content": {"type": "text", "text": text}}),
1217        }
1218    }
1219
1220    fn sourced_user_entry(stable_id: &str, text: &str) -> ChatEntry {
1221        let mut entry = ChatEntry::plain(1, ChatRole::User, text);
1222        entry.source = TranscriptSource(Some(Arc::new(TranscriptItem {
1223            stable_id: stable_id.into(),
1224            position: 1,
1225            latest_content_event_ordinal: None,
1226            created_at_ms: 0,
1227            last_changed_at_ms: 0,
1228            body: TranscriptBody::User {
1229                content: vec![json!({"type": "text", "text": text})],
1230            },
1231        })));
1232        entry
1233    }
1234
1235    #[test]
1236    fn only_messages_the_user_wrote_are_user_authored() {
1237        for (stable_id, text) in [
1238            ("user:prompt-7", "fix the build"),
1239            ("user:2", "a prompt recovered by position"),
1240            ("elicitation-reply:9", "Yes"),
1241        ] {
1242            assert!(
1243                sourced_user_entry(stable_id, text).is_user_authored(),
1244                "{stable_id}"
1245            );
1246        }
1247        assert!(ChatEntry::plain(1, ChatRole::User, "not yet projected").is_user_authored());
1248        for (stable_id, text) in [
1249            ("user:auto-continue-1-1", "Continue."),
1250            ("user:quota-retry-4", "Continue."),
1251            ("user:server-retry-5", "Continue."),
1252            ("user:review-forward-2", "Review findings"),
1253            // Hard-won: 8b08e8bc1: handback reminders and peer-session messages counted as user authorization
1254            ("user:handback-reminder-36", "Please also update the docs"),
1255            ("user:subagent-input-3", "A sub-agent finished."),
1256            (
1257                "user:session-message-turn-8",
1258                "Message from another session",
1259            ),
1260            ("user:prompt-9", "[HARNESS NOTE: summarize the request]"),
1261            (
1262                "user:prompt-10",
1263                crate::continuation::PARENT_WAIT_PROMPT_TEXT,
1264            ),
1265        ] {
1266            assert!(
1267                !sourced_user_entry(stable_id, text).is_user_authored(),
1268                "{stable_id}"
1269            );
1270        }
1271        assert!(!ChatEntry::plain(1, ChatRole::Agent, "a reply").is_user_authored());
1272    }
1273
1274    // Hard-won: ff088d42: A 15,000-chunk thought made daemon RSS grow from gigabytes of stored JSON into many gigabytes.
1275    #[test]
1276    fn push_content_chunk_merges_adjacent_text_for_the_same_message_id() {
1277        let mut chunks = vec![text_chunk("x", Some("m1"))];
1278        for _ in 1..15_001 {
1279            push_content_chunk(&mut chunks, text_chunk("x", Some("m1")));
1280        }
1281        assert_eq!(chunks, vec![text_chunk(&"x".repeat(15_001), Some("m1"))]);
1282    }
1283
1284    #[test]
1285    fn push_content_chunk_keeps_chunks_from_different_message_ids_apart() {
1286        let image = json!({"content": {"type": "image", "data": "abc", "mimeType": "image/png"}});
1287        let mut chunks = vec![text_chunk("first", Some("m1"))];
1288        push_content_chunk(&mut chunks, text_chunk(" more", Some("m1")));
1289        push_content_chunk(&mut chunks, text_chunk("second", Some("m2")));
1290        push_content_chunk(&mut chunks, text_chunk("third", None));
1291        push_content_chunk(&mut chunks, text_chunk(" more", None));
1292        push_content_chunk(&mut chunks, image.clone());
1293        push_content_chunk(&mut chunks, image.clone());
1294        push_content_chunk(
1295            &mut chunks,
1296            json!({"content": {"type": "text", "text": "a"}, "meta": {"source": "one"}}),
1297        );
1298        push_content_chunk(
1299            &mut chunks,
1300            json!({"content": {"type": "text", "text": "b"}, "meta": {"source": "two"}}),
1301        );
1302        push_content_chunk(
1303            &mut chunks,
1304            json!({"content": {"type": "text", "text": "c"}, "meta": {"source": "two"}}),
1305        );
1306        push_content_chunk(
1307            &mut chunks,
1308            json!({"content": {"type": "text", "text": "annotated", "annotations": {"audience": ["user"]}}}),
1309        );
1310        push_content_chunk(
1311            &mut chunks,
1312            json!({"content": {"type": "text", "text": "plain"}}),
1313        );
1314        assert_eq!(
1315            chunks,
1316            vec![
1317                text_chunk("first more", Some("m1")),
1318                text_chunk("second", Some("m2")),
1319                text_chunk("third more", None),
1320                image.clone(),
1321                image,
1322                json!({"content": {"type": "text", "text": "a"}, "meta": {"source": "one"}}),
1323                json!({"content": {"type": "text", "text": "bc"}, "meta": {"source": "two"}}),
1324                json!({"content": {"type": "text", "text": "annotated", "annotations": {"audience": ["user"]}}}),
1325                json!({"content": {"type": "text", "text": "plain"}}),
1326            ]
1327        );
1328    }
1329
1330    // Hard-won: ff088d42: Stored 15,000-chunk transcript rows ballooned daemon RSS after restart.
1331    #[test]
1332    fn coalesce_content_chunks_collapses_runs_and_keeps_segment_boundaries() {
1333        let image = json!({"content": {"type": "image", "data": "x", "mimeType": "image/png"}});
1334        let mut chunks = (0..15_001)
1335            .map(|_| text_chunk("x", Some("m1")))
1336            .collect::<Vec<_>>();
1337        chunks.extend([
1338            text_chunk("next", Some("m2")),
1339            text_chunk(" turn", Some("m2")),
1340            image.clone(),
1341        ]);
1342        coalesce_content_chunks(&mut chunks);
1343        assert_eq!(
1344            chunks,
1345            vec![
1346                text_chunk(&"x".repeat(15_001), Some("m1")),
1347                text_chunk("next turn", Some("m2")),
1348                image
1349            ]
1350        );
1351    }
1352}