Skip to main content

agentmux_srv_core/backend/transcript/
live.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! The live file of a streaming reply (`SPEC_HISTORY_COMPACT_FORM_ONLY_2026_11_23.md` section 4).
5//!
6//! While a reply streams, its fragments (`stream_event` lines) go to `output.live`, a second file in
7//! the agent's zone, and to the pane's feed as events with no position, as the pane takes them today.
8//! `output` never receives a fragment unless it cannot be proven redundant (see
9//! [`compact::LiveReply`]). When a message has stopped and every block of it is in a complete line,
10//! its fragments leave `output.live`. At a turn boundary, what is left of a cut-off reply becomes
11//! one interrupted `assistant` line in `output`, before the boundary line.
12//!
13//! A kill leaves `output.live` behind. The first write to a block after a start looks at it: the
14//! leftovers are reassembled against the last complete lines of `output`, appended, and the file is
15//! emptied.
16//!
17//! Readers of `output` see no fragments. A pane opened mid-reply gets the rest of the reply from the
18//! feed and the whole of it from `output` once the block completes.
19
20use std::collections::HashMap;
21use std::sync::{Arc, LazyLock, Mutex};
22
23use super::compact::{recover_live, LiveReply};
24use crate::backend::agent_session::OUTPUT_FILE;
25use crate::backend::storage::error::StoreError;
26use crate::backend::storage::filestore::{FileOpts, FileStore};
27
28/// The file in an agent's zone that holds the fragments of the reply in progress.
29pub const LIVE_FILE: &str = "output.live";
30
31/// How much of the end of `output` a recovery reads to find the complete lines of a cut-off reply.
32const RECOVERY_TAIL_BYTES: i64 = 4 << 20;
33
34#[derive(Default)]
35struct State {
36    reply: LiveReply,
37    /// The live file has been looked at since this process started.
38    looked: bool,
39    /// The shared zone that `unshared` and `held_live` were kept for, and the store it is in.
40    held_zone: String,
41    held_shared: Option<Arc<FileStore>>,
42    /// Complete lines only the block's own copy of `output` holds, because the append to the shared transcript failed:
43    /// the next shared append sends them first (see `append.rs`).
44    unshared: Vec<u8>,
45    /// Fragment lines only the block's own live file holds, because the append to the shared live file failed: the next
46    /// fragment append sends them first, and the block's own live file is then emptied.
47    held_live: Vec<u8>,
48    /// The block's own live file those fragments were written to.
49    held_live_own: Option<(Arc<FileStore>, String)>,
50}
51
52/// The most lines (or fragments) held back this way for one block. Past it the shared transcript is not caught up from
53/// memory: the block's own copy has them all, and the copies pass reconciles it later.
54const UNSHARED_CAP: usize = 16 << 20;
55
56/// Take the lines the shared transcript lacks, in order; empty when it has everything.
57pub(crate) fn take_unshared(block_id: &str) -> Vec<u8> {
58    let mut states = STATES.lock().unwrap_or_else(|e| e.into_inner());
59    states.get_mut(block_id).map(|st| std::mem::take(&mut st.unshared)).unwrap_or_default()
60}
61
62/// Remember the lines the shared transcript `zone` still lacks (empty: it lacks none).
63pub(crate) fn put_unshared(block_id: &str, shared: &Arc<FileStore>, zone: &str, lines: Vec<u8>) {
64    let mut states = STATES.lock().unwrap_or_else(|e| e.into_inner());
65    if lines.is_empty() {
66        if let Some(st) = states.get_mut(block_id) {
67            st.unshared = Vec::new();
68        }
69    } else if lines.len() > UNSHARED_CAP {
70        tracing::warn!(block = %block_id, bytes = lines.len(), "transcript: too much is held only in the block's own copy to send it from memory");
71    } else {
72        let st = states.entry(block_id.to_string()).or_default();
73        st.held_zone = zone.to_string();
74        st.held_shared = Some(shared.clone());
75        st.unshared = lines;
76    }
77}
78
79/// Take the fragments the shared live file lacks, and the block's own live file that holds them.
80fn take_held_live(block_id: &str) -> (Vec<u8>, Option<(Arc<FileStore>, String)>) {
81    let mut states = STATES.lock().unwrap_or_else(|e| e.into_inner());
82    states.get_mut(block_id).map_or_else(Default::default, |st| (std::mem::take(&mut st.held_live), st.held_live_own.take()))
83}
84
85fn put_held_live(block_id: &str, shared: &Arc<FileStore>, zone: &str, held: Vec<u8>, own: Option<(Arc<FileStore>, String)>) {
86    let mut states = STATES.lock().unwrap_or_else(|e| e.into_inner());
87    if held.is_empty() {
88        if let Some(st) = states.get_mut(block_id) {
89            st.held_live = Vec::new();
90            st.held_live_own = None;
91        }
92    } else if held.len() > UNSHARED_CAP {
93        tracing::warn!(block = %block_id, bytes = held.len(), "transcript live file: too much is held only in the block's own copy to send it from memory");
94    } else {
95        let st = states.entry(block_id.to_string()).or_default();
96        st.held_zone = zone.to_string();
97        st.held_shared = Some(shared.clone());
98        st.held_live = held;
99        st.held_live_own = own.or(st.held_live_own.take());
100    }
101}
102
103/// The live files were just emptied: nothing is held for them any more.
104pub(crate) fn clear_held_live(block_id: &str) {
105    let mut states = STATES.lock().unwrap_or_else(|e| e.into_inner());
106    if let Some(st) = states.get_mut(block_id) {
107        st.held_live = Vec::new();
108        st.held_live_own = None;
109    }
110}
111
112/// A zone's conversation is about to leave it (an archive): what was held in memory for it belongs to that conversation.
113/// The lines the zone lacks are appended to it, so the archive has them. The fragments of a reply that did not finish
114/// are returned (the shared live file lacks them): `settle` reassembles them after the shared file's own, and the
115/// block's own live file that kept them is removed. Without this the next conversation's first append would receive
116/// the old one's lines.
117fn release_held(fs: &FileStore, zone: &str) -> Vec<u8> {
118    let drained: Vec<(Vec<u8>, Vec<u8>, Option<(Arc<FileStore>, String)>)> = {
119        let mut states = STATES.lock().unwrap_or_else(|e| e.into_inner());
120        states
121            .values_mut()
122            .filter(|st| st.held_zone == zone && st.held_shared.as_ref().is_some_and(|held_in| std::ptr::eq(Arc::as_ptr(held_in), fs)))
123            .map(|st| (std::mem::take(&mut st.unshared), std::mem::take(&mut st.held_live), st.held_live_own.take()))
124            .collect()
125    };
126    let mut fragments = Vec::new();
127    for (lines, held, own) in drained {
128        if !lines.is_empty() {
129            if let Err(e) = fs.append_data(zone, OUTPUT_FILE, &lines) {
130                tracing::warn!(zone = %zone, error = %e, "transcript: lines held for the zone could not be added before its archive");
131            }
132        }
133        fragments.extend_from_slice(&held);
134        if let Some((own_fs, own_zone)) = own {
135            let _ = own_fs.delete_file(&own_zone, LIVE_FILE);
136        }
137    }
138    fragments
139}
140
141static STATES: LazyLock<Mutex<HashMap<String, State>>> = LazyLock::new(Default::default);
142
143/// One step of an append, in order.
144pub(crate) enum Run {
145    /// Fragment lines, for the live file and an unpositioned event.
146    Fragments(Vec<u8>),
147    /// Complete lines, for `output`.
148    Lines(Vec<u8>),
149    /// The held fragments are redundant now: empty the live file.
150    ClearLive,
151}
152
153fn push(runs: &mut Vec<Run>, fragment: bool, line: &[u8]) {
154    match runs.last_mut() {
155        Some(Run::Fragments(b)) if fragment => {
156            b.extend_from_slice(line);
157            b.push(b'\n');
158        }
159        Some(Run::Lines(b)) if !fragment => {
160            b.extend_from_slice(line);
161            b.push(b'\n');
162        }
163        _ => {
164            let mut b = line.to_vec();
165            b.push(b'\n');
166            runs.push(if fragment { Run::Fragments(b) } else { Run::Lines(b) });
167        }
168    }
169}
170
171/// Split `records` (complete lines, each ending in a newline) into the runs to write, feeding the
172/// block's reply tracker in line order. Not UTF-8 is not JSON: such a line is a complete line.
173pub(crate) fn plan(block_id: &str, records: &[u8]) -> Vec<Run> {
174    let mut states = STATES.lock().unwrap_or_else(|e| e.into_inner());
175    let st = states.entry(block_id.to_string()).or_default();
176    let mut runs = Vec::new();
177    for line in records.split(|b| *b == b'\n').filter(|l| !l.is_empty()) {
178        let Ok(text) = std::str::from_utf8(line) else {
179            push(&mut runs, false, line);
180            continue;
181        };
182        let before = st.reply.before(text);
183        for e in &before.emits {
184            push(&mut runs, false, e.line().as_bytes());
185        }
186        push(&mut runs, before.fragment, line);
187        if before.ended {
188            runs.push(Run::ClearLive);
189        } else if st.reply.holds_fragments() && st.reply.settled() {
190            st.reply.reset();
191            runs.push(Run::ClearLive);
192        }
193    }
194    runs
195}
196
197/// Forget what this process knows of a block, as a new process would.
198#[cfg(test)]
199pub(crate) fn forget(block_id: &str) {
200    STATES.lock().unwrap_or_else(|e| e.into_inner()).remove(block_id);
201}
202
203/// The files a block's live fragments are read from and cleared from: the shared zone first, then the block's own
204/// copy. A fragment is written to the block's own only when the shared write failed ([`append_fragments`]), so it
205/// is empty in the ordinary case, and a restart still finds what a refused shared write would have lost.
206pub(crate) fn targets(
207    block_id: &str,
208    filestore: Option<&Arc<FileStore>>,
209    global: Option<(&Arc<FileStore>, &str)>,
210) -> Vec<(Arc<FileStore>, String)> {
211    let mut out = Vec::new();
212    if let Some((gfs, zone)) = global {
213        out.push((gfs.clone(), zone.to_string()));
214    }
215    if let Some(fs) = filestore {
216        out.push((fs.clone(), block_id.to_string()));
217    }
218    out
219}
220
221/// Append fragment lines to one live file, creating it on first write.
222fn append_live(fs: &FileStore, zone: &str, bytes: &[u8]) -> Result<(), StoreError> {
223    let put = || fs.append_data(zone, LIVE_FILE, bytes);
224    match put() {
225        Err(StoreError::NotFound) => match fs.make_file(zone, LIVE_FILE, HashMap::new(), FileOpts::default()) {
226            Ok(()) | Err(StoreError::AlreadyExists) => put().map(|_| ()),
227            Err(e) => Err(e),
228        },
229        other => other.map(|_| ()),
230    }
231}
232
233/// Append fragment lines to the live file of the targets, creating it on first write. With `single_copy` (a defined
234/// agent's stream) the shared zone (the first target) keeps the only copy, and the block's own live file is written
235/// only when the shared one refused: a reply that streams while the shared store is failing is still on disk if the
236/// process dies. What only the block's own file holds is sent to the shared one ahead of the next fragments, in order,
237/// and the block's own file is then emptied, so the shared live file is whole again as soon as it takes writes.
238pub(crate) fn append_fragments(block_id: &str, targets: &[(Arc<FileStore>, String)], bytes: &[u8], single_copy: bool) {
239    if !single_copy {
240        for (fs, zone) in targets {
241            if let Err(e) = append_live(fs, zone, bytes) {
242                tracing::warn!(zone = %zone, error = %e, "transcript live file: append failed");
243            }
244        }
245        return;
246    }
247    let Some((shared_fs, shared_zone)) = targets.first() else { return };
248    let (mut held, held_own) = take_held_live(block_id);
249    let mut shared_took = true;
250    if !held.is_empty() {
251        shared_took = append_live(shared_fs, shared_zone, &held).is_ok();
252        if shared_took {
253            held.clear();
254            if let Some((own_fs, own_zone)) = held_own.as_ref() {
255                let _ = own_fs.delete_file(own_zone, LIVE_FILE);
256            }
257        }
258    }
259    if shared_took {
260        shared_took = match append_live(shared_fs, shared_zone, bytes) {
261            Ok(()) => true,
262            Err(e) => {
263                tracing::warn!(zone = %shared_zone, error = %e, "transcript live file: append failed");
264                false
265            }
266        };
267    }
268    let mut own = held_own.filter(|_| !held.is_empty());
269    if !shared_took {
270        held.extend_from_slice(bytes);
271        if let Some((fs, zone)) = targets.get(1) {
272            if let Err(e) = append_live(fs, zone, bytes) {
273                tracing::warn!(zone = %zone, error = %e, "transcript live file: the fallback append failed");
274            }
275            own = Some((fs.clone(), zone.clone()));
276        }
277    }
278    put_held_live(block_id, shared_fs, shared_zone, held, own);
279}
280
281/// Empty the live file of every target.
282pub(crate) fn clear(targets: &[(Arc<FileStore>, String)]) {
283    for (fs, zone) in targets {
284        match fs.delete_file(zone, LIVE_FILE) {
285            Ok(()) | Err(StoreError::NotFound) => {}
286            Err(e) => tracing::warn!(zone = %zone, error = %e, "transcript live file: clearing failed"),
287        }
288    }
289}
290
291/// The lines of `bytes`, without a first line that may be cut by where the read began.
292fn lines_of(bytes: &[u8], cut_head: bool) -> Vec<String> {
293    let text = String::from_utf8_lossy(bytes);
294    let mut it = text.split('\n');
295    if cut_head {
296        it.next();
297    }
298    it.filter(|l| !l.is_empty()).map(str::to_string).collect()
299}
300
301/// What a leftover live file of `zone` (and `extra`, fragments that came after it and are kept elsewhere) leaves for
302/// `output`, as lines ending in newlines; `None` when there is no live file or nothing in it.
303fn leftovers_of(fs: &FileStore, zone: &str, extra: &[u8]) -> Option<Vec<u8>> {
304    let mut live = fs.read_file(zone, LIVE_FILE).ok().flatten().unwrap_or_default();
305    if !live.is_empty() && !live.ends_with(b"\n") && !extra.is_empty() {
306        live.push(b'\n');
307    }
308    live.extend_from_slice(extra);
309    if live.is_empty() {
310        return None;
311    }
312    let size = fs.stat(zone, OUTPUT_FILE).ok().flatten().map_or(0, |f| f.size);
313    let start = (size - RECOVERY_TAIL_BYTES).max(0);
314    let tail = if size > start { fs.read_bytes_db(zone, OUTPUT_FILE, start, size - start).unwrap_or_default() } else { Vec::new() };
315    let emits = recover_live(&lines_of(&tail, start > 0), &lines_of(&live, false));
316    let mut out = Vec::new();
317    for e in emits {
318        out.extend_from_slice(e.line().as_bytes());
319        out.push(b'\n');
320    }
321    Some(out)
322}
323
324/// Settle a zone's live file before its conversation leaves the zone (an archive moves `output` away): what a kill
325/// left becomes lines of `output`, and the file is emptied. A leftover left in place would be recovered into the next
326/// conversation's `output` as a cut-off reply it never had. `false` when the leftover could not be appended: the
327/// live file is then left as it is, and the archive takes it along with the conversation it belongs to.
328pub(crate) fn settle(fs: &FileStore, zone: &str) -> bool {
329    let held = release_held(fs, zone);
330    let Some(left) = leftovers_of(fs, zone, &held) else { return true };
331    if !left.is_empty() {
332        if let Err(e) = fs.append_data(zone, OUTPUT_FILE, &left) {
333            tracing::warn!(zone = %zone, error = %e, "transcript live file: settling before archive failed");
334            return false;
335        }
336    }
337    match fs.delete_file(zone, LIVE_FILE) {
338        Ok(()) | Err(StoreError::NotFound) => true,
339        Err(e) => {
340            tracing::warn!(zone = %zone, error = %e, "transcript live file: clearing failed");
341            false
342        }
343    }
344}
345
346/// The first call for a block in this process: what a kill left in its live file, as lines for
347/// `output` (possibly none), after which the live files are emptied. `None` on every later call,
348/// and when there is nothing to recover. The first target (the shared zone, when there is one) is read first.
349/// A copy in a later target counts only while the first still holds its conversation: after an archive the
350/// shared zone holds none, and what a later target has left is stale (the old conversation's), so it is only
351/// emptied. A cut-off reply the shared zone failed to keep is still recovered from the other copy.
352pub(crate) fn recover_once(block_id: &str, targets: &[(Arc<FileStore>, String)], single_copy: bool) -> Option<Vec<u8>> {
353    {
354        let mut states = STATES.lock().unwrap_or_else(|e| e.into_inner());
355        let st = states.entry(block_id.to_string()).or_default();
356        if std::mem::replace(&mut st.looked, true) {
357            return None;
358        }
359    }
360    let (fs, zone) = targets.first()?;
361    let holds = fs.stat(zone, OUTPUT_FILE).ok().flatten().is_some_and(|f| f.size > 0);
362    let found = if single_copy {
363        // A defined agent's stream: the block's own live file holds only what the shared file lacks, the fragments the
364        // shared write refused (the later part of the reply when the shared file has the earlier part, the whole of it
365        // when it has none), so both are reassembled together. It counts only while the shared zone still holds its
366        // conversation (after an archive what it has left is the old conversation's). A kill between the catch-up (the held
367        // fragments were appended to the shared file) and the deletion of the block's own file leaves both holding them: the
368        // shared file then already ends with the block's, which is not added again.
369        let own_live = if holds && targets.len() > 1 {
370            targets[1..].iter().find_map(|(own_fs, own_zone)| own_fs.read_file(own_zone, LIVE_FILE).ok().flatten().filter(|b| !b.is_empty()))
371        } else {
372            None
373        };
374        let shared_live = fs.read_file(zone, LIVE_FILE).ok().flatten().unwrap_or_default();
375        let extra = own_live.filter(|own| !shared_live.ends_with(own)).unwrap_or_default();
376        leftovers_of(fs, zone, &extra)
377    } else {
378        // Every target is written the same (a quick-launch pane's, or a writer with one copy): the shared file is the
379        // whole reply, and a copy that lacks the end of it (its write was refused) is a prefix, not more fragments.
380        leftovers_of(fs, zone, &[]).or_else(|| {
381            if holds { targets[1..].iter().find_map(|(own_fs, own_zone)| leftovers_of(own_fs, own_zone, &[])) } else { None }
382        })
383    };
384    clear(targets);
385    clear_held_live(block_id);
386    found
387}
388
389#[cfg(test)]
390#[path = "live_tests.rs"]
391mod tests;