Skip to main content

agentmux_srv/server/app_api/
blockfile.rs

1use super::*;
2
3pub fn register(engine: &Arc<WshRpcEngine>, state: &AppState) {
4    register_blockfile_line_count(engine, state);
5    register_blockfile_read_range(engine, state);
6    register_blockfile_read_state(engine, state);
7    register_blockfile_write_state(engine, state);
8}
9
10fn register_blockfile_line_count(engine: &Arc<WshRpcEngine>, state: &AppState) {
11    let state = state.clone();
12    engine.register_typed(COMMAND_BLOCKFILE_LINE_COUNT, move |cmd: CommandBlockfileLineCountData, _ctx| {
13        let state = state.clone();
14        async move { blockfile_line_count(&state, cmd).await }
15    });
16}
17
18/// `blockfile:line_count`.
19///
20/// Every step reads a store: a lock on the one object-store connection, and a file-backed database that another srv
21/// instance can hold. The page asks about every agent it shows every few seconds, so the whole answer runs on the
22/// blocking pool: a store that is busy then holds a blocking thread, never a runtime worker.
23pub(crate) async fn blockfile_line_count(
24    state: &AppState,
25    cmd: CommandBlockfileLineCountData,
26) -> Result<BlockfileLineCountResult, String> {
27    let state = state.clone();
28    tokio::task::spawn_blocking(move || line_count_blocking(&state, &cmd))
29        .await
30        .map_err(|e| format!("blockfile:line_count: the count task failed: {e}"))?
31}
32
33fn line_count_blocking(state: &AppState, cmd: &CommandBlockfileLineCountData) -> Result<BlockfileLineCountResult, String> {
34    let wants_flag = cmd.filename == crate::backend::agent_session::OUTPUT_FILE && cmd.archive_zone.is_none();
35    let result = count_lines(state, cmd);
36    // An empty count from the block's own copy of a damaged history is not "no history":
37    // the pane tells the user earlier history may be missing.
38    match result {
39        Ok(mut r) if wants_flag && super::history_damaged(&state.mstore, &cmd.block_id) => {
40            r.history_damaged = Some(true);
41            Ok(r)
42        }
43        other => other,
44    }
45}
46
47/// The count itself, from the first source that has one: the agent's global transcript zone, the block's
48/// own counter, the `session:line_count` meta, and last the event ring buffer. Blocking: call on the blocking pool.
49fn count_lines(state: &AppState, cmd: &CommandBlockfileLineCountData) -> Result<BlockfileLineCountResult, String> {
50    tracing::info!(block_id = %cmd.block_id, filename = %cmd.filename, "blockfile:line_count");
51
52    // Cross-channel fallback (checked first): when this channel has
53    // no local `output` for the block, the local `session:line_count`
54    // meta is absent/stale, so a fresh cross-channel open would
55    // report 0 lines and the pane would render empty. Count from the
56    // agent's GLOBAL transcript zone instead. See
57    // `docs/analysis/ANALYSIS_CROSS_CHANNEL_CONVERSATION_HISTORY_2026_06_14.md`.
58    if let Some((gfs, zone)) = history_output_source(
59        &state.filestore,
60        &state.global_transcript_store,
61        &state.mstore,
62        &cmd.block_id,
63        &cmd.filename,
64        cmd.archive_zone.as_deref(),
65    )?
66    {
67        // A counted zone answers from its counter (O(1), Phase 5a-3);
68        // a zone without an epoch gets one first (`init_line_counter`,
69        // one read of the file, once). Only if it can't be counted does
70        // this extend or rebuild `output.idx`, as before.
71        let stream = format!("g:{zone}");
72        let count = counted_line_count(&gfs, &zone, stream).or_else(|| {
73            global_zone_line_count(&gfs, &zone).map(|count| BlockfileLineCountResult { count, ..Default::default() })
74        });
75        if let Some(result) = count {
76            return Ok(result);
77        }
78    }
79
80    // The block's own `output`, from its counter when it is a
81    // counted transcript (Phase 5a-3): exact, O(1), and the same
82    // count `read_range` serves lines from.
83    if cmd.filename == crate::backend::agent_session::OUTPUT_FILE {
84        let stream = format!("b:{}", cmd.block_id);
85        if let Some(result) = counted_line_count(&state.filestore, &cmd.block_id, stream) {
86            return Ok(result);
87        }
88    }
89
90    // Fast path: read session:line_count meta (O(1), maintained
91    // by SessionStatsAccumulator). For "output" filename this is
92    // the authoritative total — matches the unbounded counter
93    // that SessionStats increments on every line. FileStore's
94    // persisted line count will trail meta by up to the debounce
95    // interval (1s), and reading the full file just to count
96    // lines is O(file size) which defeats the point of a fast
97    // line_count endpoint.
98    if cmd.filename == "output" {
99        if let Ok(Some(block)) = state.mstore.get::<Block>(&cmd.block_id) {
100            if let Some(count) = block.meta.get("session:line_count").and_then(|v| v.as_u64()) {
101                return Ok(BlockfileLineCountResult { count, ..Default::default() });
102            }
103        }
104    }
105
106    Ok(BlockfileLineCountResult {
107        count: count_from_event_history(&state.broker, &cmd.block_id, &cmd.filename),
108        ..Default::default()
109    })
110}
111
112/// The non-empty lines of `filename` still in the block's event ring buffer (capped at MAX_PERSIST = 4096 events and the broker's byte cap per scope): the
113/// count of last resort, for a file with no counter and no `session:line_count` meta.
114fn count_from_event_history(broker: &crate::backend::mps::Broker, block_id: &str, filename: &str) -> u64 {
115    let scope = format!("block:{}", block_id);
116    let events = broker.read_event_history(
117        crate::backend::mps::EVENT_BLOCK_FILE,
118        &scope,
119        usize::MAX, // broker clamps to MAX_PERSIST internally
120    );
121
122    let mut count: u64 = 0;
123    for event in events {
124        if let Some(ref event_data) = event.data {
125            let ev_filename = event_data.get("filename")
126                .and_then(|v| v.as_str()).unwrap_or("");
127            if ev_filename != filename {
128                continue;
129            }
130            if let Some(data64) = event_data.get("data64").and_then(|v| v.as_str()) {
131                if let Ok(bytes) = base64::engine::general_purpose::STANDARD.decode(data64) {
132                    let text = String::from_utf8_lossy(&bytes);
133                    for line in text.lines() {
134                        if !line.trim().is_empty() {
135                            count += 1;
136                        }
137                    }
138                }
139            }
140        }
141    }
142    count
143}
144
145/// Where a block's transcript is read from: with `archive_zone`, that
146/// archived conversation of the block's agent (in the global store, or the
147/// per-channel store for an archive written before archives moved there),
148/// refused unless it is one of that agent's own archives; otherwise the
149/// global current zone, as [`global_output_source`].
150pub(crate) fn history_output_source(
151    per_channel: &Arc<crate::backend::storage::filestore::FileStore>,
152    global: &Option<Arc<crate::backend::storage::filestore::FileStore>>,
153    mstore: &Arc<crate::backend::storage::store::Store>,
154    block_id: &str,
155    filename: &str,
156    archive_zone: Option<&str>,
157) -> Result<Option<(Arc<crate::backend::storage::filestore::FileStore>, String)>, String> {
158    let Some(zone) = archive_zone else {
159        return Ok(global_output_source(per_channel, global, mstore, block_id, filename));
160    };
161    let refuse = || format!("{zone:?} is not an archived conversation of this block's agent");
162    let agent_id = mstore
163        .get::<Block>(block_id)
164        .ok()
165        .flatten()
166        .map(|b| crate::backend::obj::meta_get_string(&b.meta, "agentId", ""))
167        .ok_or_else(refuse)?;
168    let own = crate::backend::agent_session::is_valid_definition_id(&agent_id)
169        && filename == crate::backend::agent_session::OUTPUT_FILE
170        && zone
171            .strip_prefix(&format!("agent:{agent_id}:archive:"))
172            .is_some_and(|ms| !ms.is_empty() && ms.bytes().all(|b| b.is_ascii_digit()));
173    if !own {
174        return Err(refuse());
175    }
176    for store in global.iter().chain(std::iter::once(per_channel)) {
177        if matches!(store.stat(zone, filename), Ok(Some(_))) {
178            return Ok(Some((store.clone(), zone.to_string())));
179        }
180    }
181    Err(format!("archived conversation {zone} not found"))
182}
183
184fn register_blockfile_read_range(engine: &Arc<WshRpcEngine>, state: &AppState) {
185    let broker = state.broker.clone();
186    let filestore = state.filestore.clone();
187    let global_store = state.global_transcript_store.clone();
188    let mstore = state.mstore.clone();
189
190    engine.register_typed(
191        COMMAND_BLOCKFILE_READ_RANGE,
192        move |cmd: CommandBlockfileReadRangeData, _ctx| {
193            read_range(broker.clone(), filestore.clone(), global_store.clone(), mstore.clone(), cmd)
194        },
195    );
196}
197
198/// `blockfile:read_range`, also called in-process: the viewer feed reads its
199/// snapshot through it (`server::http_viewer`), so the feed gets the same
200/// bounded read the pane does and never a whole-file one.
201pub(crate) async fn read_range(
202    broker: Arc<crate::backend::mps::Broker>,
203    filestore: Arc<crate::backend::storage::filestore::FileStore>,
204    global_store: Option<Arc<crate::backend::storage::filestore::FileStore>>,
205    mstore: Arc<crate::backend::storage::store::Store>,
206    cmd: CommandBlockfileReadRangeData,
207) -> Result<BlockfileReadRangeResult, String> {
208    let damaged = crate::backend::transcript::damage::damaged_count();
209    let (block_id, is_output, archive_zone) = (cmd.block_id.clone(), cmd.filename == crate::backend::agent_session::OUTPUT_FILE, cmd.archive_zone.clone());
210    let check = mstore.clone();
211    let first = read_range_once(broker.clone(), filestore.clone(), global_store.clone(), mstore.clone(), cmd.clone()).await;
212    let mut result = if crate::backend::transcript::damage::damaged_count() == damaged {
213        first
214    } else {
215        // That read found the agent's shared zone corrupt (an index rebuild or a read
216        // failed on it, or on another agent's at the same time). The zone is marked
217        // now, so the source resolves to the block's own copy: answer from it, not
218        // with the failure.
219        read_range_once(broker, filestore, global_store, mstore, cmd).await
220    };
221    // The pane says so when what it was given is the block's own copy of a damaged history.
222    if is_output && archive_zone.is_none() && super::history_damaged(&check, &block_id) {
223        if let Ok(r) = result.as_mut() {
224            r.history_damaged = Some(true);
225        }
226    }
227    result
228}
229
230#[path = "blockfile_read.rs"]
231mod read_steps;
232
233async fn read_range_once(
234    broker: Arc<crate::backend::mps::Broker>,
235    filestore: Arc<crate::backend::storage::filestore::FileStore>,
236    global_store: Option<Arc<crate::backend::storage::filestore::FileStore>>,
237    mstore: Arc<crate::backend::storage::store::Store>,
238    cmd: CommandBlockfileReadRangeData,
239) -> Result<BlockfileReadRangeResult, String> {
240    tracing::info!(block_id = %cmd.block_id, filename = %cmd.filename, offset = cmd.offset, limit = cmd.limit, "blockfile:read_range");
241    let started = std::time::Instant::now();
242    let mut clock = ReadRangeClock::default();
243
244    let limit = cmd.limit.min(10_000) as usize;
245    let offset = cmd.offset as usize;
246    let end = offset.saturating_add(limit);
247
248    // Cross-channel fallback: when this channel has no local `output`
249    // for the block, read the agent's GLOBAL transcript zone
250    // (`agent:<defId>:current`) instead. `read_block` is the zone for
251    // every FileStore call below — the local block_id normally, the
252    // agent zone when the agent ran in another build/channel.
253    let source = history_output_source(&filestore, &global_store, &mstore, &cmd.block_id, &cmd.filename, cmd.archive_zone.as_deref())?;
254    let stream = match &source {
255        Some((_, zone)) => format!("g:{zone}"),
256        None => format!("b:{}", cmd.block_id),
257    };
258    let (filestore, read_block) = source.unwrap_or_else(|| (filestore.clone(), cmd.block_id.clone()));
259    clock.source_ms = ms_since(started);
260
261    // Generation (Phase 5a-3): read before and after the lines. A
262    // replace always mints a new one, so the same value on both
263    // sides proves every line came from that generation — only then
264    // does the response name it. `expect_gen` turns any other
265    // outcome into `gen_mismatch` instead of lines of another file.
266    let transcript = cmd.filename == crate::backend::agent_session::OUTPUT_FILE;
267    let lap = std::time::Instant::now();
268    let gen_before = if transcript { db_generation(&filestore, &read_block).await } else { None };
269    clock.gen_before_ms = ms_since(lap);
270    if let Some(expected) = &cmd.expect_gen {
271        if gen_before.as_deref() != Some(expected.as_str()) {
272            return Ok(read_steps::mismatch(&stream, gen_before));
273        }
274    }
275    // A transcript's `amx` is shown only as srv signed it (`origin_sig`).
276    let owner = transcript.then(|| crate::backend::transcript::origin_sig::owner_for_read(&mstore, &cmd.block_id, &read_block));
277    let range = read_steps::RangeRead { cmd: &cmd, stores: (&mstore, &filestore), offset, stream, owner, gen_before };
278
279    // Fast path: output.idx — a lazily-built, self-validating byte-offset
280    // index of every non-blank line in `output`. It lets us seek directly
281    // to the requested line range instead of loading the whole file.
282    //
283    // The index is a pure cache of `output`: its 8-byte header records
284    // the `output` size it was built for. If that equals `output`'s
285    // current size (and it is labelled with `output`'s generation) the
286    // index is fresh; otherwise THIS path extends it (`extend_output_idx`,
287    // #2838): it scans just the bytes appended since, re-deriving the
288    // last indexed line so a straddling partial line isn't
289    // double-counted, and rebuilds from byte 0 only when the index
290    // can't be a base (missing, shrunk, another generation's).
291    //
292    // Gated to non-circular files: circular `output` (terminal ring buffers)
293    // drops early bytes, so absolute byte offsets wouldn't map cleanly.
294    if cmd.filename == "output" {
295        if let Some(result) = read_steps::indexed_window(&filestore, &read_block, &cmd.block_id, offset, limit, &mut clock).await {
296            let lap = std::time::Instant::now();
297            let gen_after = if transcript { db_generation(&filestore, &read_block).await } else { None };
298            clock.gen_after_ms = ms_since(lap);
299            let result = range.finish(result, gen_after);
300            clock.log_done(&cmd.block_id, offset, limit, "index", started, &result);
301            return Ok(result);
302        }
303    }
304
305    // Phase 1.3: Prefer FileStore (persistent, no size cap) over the
306    // MPS broker ring buffer (MAX_PERSIST = 4096 events).
307    //
308    // If FileStore has the file and it is non-empty, read from disk.
309    // Otherwise fall back to ring buffer for backward compatibility.
310    let all_lines = match read_steps::whole_file_lines(&filestore, &read_block, &cmd, started)? {
311        Some(lines) => lines,
312        None => read_steps::ring_buffer_lines(&broker, &cmd),
313    };
314
315    let total = all_lines.len() as u64;
316    let clamped_offset = offset.min(all_lines.len());
317    let clamped_end = end.min(all_lines.len());
318    let lines: Vec<String> = if clamped_offset >= clamped_end {
319        Vec::new()
320    } else {
321        all_lines[clamped_offset..clamped_end].to_vec()
322    };
323
324    let lap = std::time::Instant::now();
325    let gen_after = if transcript { db_generation(&filestore, &read_block).await } else { None };
326    clock.gen_after_ms = ms_since(lap);
327    let result = range.finish(BlockfileReadRangeResult { lines, total, ..Default::default() }, gen_after);
328    clock.log_done(&cmd.block_id, offset, limit, "whole_file", started, &result);
329    Ok(result)
330}
331
332fn ms_since(t: std::time::Instant) -> u64 {
333    t.elapsed().as_millis() as u64
334}
335
336/// The whole-file fallback of `blockfile:read_range` loads the file under the
337/// store's lock; a file this large is logged when it does.
338const WHOLE_FILE_WARN_BYTES: i64 = 16 * 1024 * 1024;
339
340/// A non-circular `output` this large is never read whole: loading it holds the
341/// store's connection mutex for the whole read (about 15 s for a 1.3 GB
342/// transcript), stalling every agent's appends and every pane's reads in this
343/// process (docs/reports/REPORT_AGENT_OPEN_STALL_RCA_2026_10_05.md). When the
344/// index can't serve such a read, `read_range` answers with an error instead;
345/// the pane falls back to its short tail read, which extends the index again.
346const WHOLE_FILE_REFUSE_BYTES: i64 = 64 * 1024 * 1024;
347
348/// Whether `read_range` may load this file whole (its fallback when
349/// `output.idx` can't serve a read). Everything but a large, non-circular
350/// transcript may; terminal ring buffers (circular) stay bounded by their
351/// `maxsize`.
352fn whole_file_read_allowed(filename: &str, circular: bool, size: i64) -> bool {
353    filename != crate::backend::agent_session::OUTPUT_FILE || circular || size < WHOLE_FILE_REFUSE_BYTES
354}
355
356/// A `blockfile:read_range` call this slow is logged as a warning, with where
357/// its time went.
358const SLOW_READ_RANGE_MS: u64 = 1_000;
359
360/// Where a `blockfile:read_range` call spent its time. Two pane opens waited
361/// about 17 s on this call while the log recorded only when it started
362/// (docs/reports/REPORT_AGENT_OPEN_STALL_RCA_2026_10_05.md); with
363/// `filestore: connection held a long time`, this names the step that waited.
364#[derive(Default)]
365struct ReadRangeClock {
366    /// Choosing the store (the block's, or the agent's zone).
367    source_ms: u64,
368    /// `output`'s generation, read before the lines.
369    gen_before_ms: u64,
370    /// The `output.idx` read on the blocking pool, when it ran.
371    index: Option<IndexClock>,
372    /// `output`'s generation, read after the lines.
373    gen_after_ms: u64,
374}
375
376#[derive(Default)]
377struct IndexClock {
378    /// Waiting for a blocking-pool thread.
379    queued_ms: u64,
380    /// Bringing `output.idx` up to date, when the first read found it stale.
381    extend_ms: Option<u64>,
382    /// The whole read on that thread, `extend_ms` included.
383    run_ms: u64,
384    /// Served from an index an append had outrun (`read_via_stale_index`).
385    stale: bool,
386}
387
388impl ReadRangeClock {
389    fn log_done(
390        &self,
391        block_id: &str,
392        offset: usize,
393        limit: usize,
394        path: &str,
395        started: std::time::Instant,
396        result: &BlockfileReadRangeResult,
397    ) {
398        let total_ms = ms_since(started);
399        let bytes: usize = result.lines.iter().map(String::len).sum();
400        let (queued_ms, extend_ms, run_ms, stale) =
401            self.index.as_ref().map_or((0, None, 0, false), |i| (i.queued_ms, i.extend_ms, i.run_ms, i.stale));
402        macro_rules! done {
403            ($level:ident, $msg:literal) => {
404                tracing::$level!(
405                    block_id = %block_id,
406                    offset,
407                    limit,
408                    path,
409                    lines = result.lines.len(),
410                    bytes,
411                    total_ms,
412                    source_ms = self.source_ms,
413                    gen_before_ms = self.gen_before_ms,
414                    queued_ms,
415                    extend_ms = ?extend_ms,
416                    run_ms,
417                    stale,
418                    gen_after_ms = self.gen_after_ms,
419                    $msg
420                )
421            };
422        }
423        if total_ms >= SLOW_READ_RANGE_MS {
424            done!(warn, "blockfile:read_range slow");
425        } else if stale {
426            // Rare by construction (an append outran the index between its
427            // extension and the read), and the only trace that the stale-prefix
428            // path runs in the field, so kept above debug.
429            done!(info, "blockfile:read_range served an index prefix an append had outrun");
430        } else {
431            done!(debug, "blockfile:read_range done");
432        }
433    }
434}
435
436// Where a turn starts moved to `transcript::turns`, which a fork's copy also needs.
437pub(crate) use crate::backend::transcript::turns::is_claude_turn_start;
438
439/// Index in `lines` where the last `turns` turns begin; `None` when there
440/// are fewer. Scans from the end and stops at the `turns`-th start.
441pub(crate) fn last_turns_start(lines: &[String], turns: usize) -> Option<usize> {
442    if turns == 0 {
443        return None;
444    }
445    let mut seen = 0;
446    for (i, line) in lines.iter().enumerate().rev() {
447        if is_claude_turn_start(line) {
448            seen += 1;
449            if seen == turns {
450                return Some(i);
451            }
452        }
453    }
454    None
455}
456
457/// `tail_turns`: drop everything before the last `turns` turns (stamps
458/// with it) and record where `lines` now starts.
459pub(super) fn trim_to_last_turns(result: &mut BlockfileReadRangeResult, first_line: u64, turns: usize) {
460    if result.gen_mismatch.is_some() {
461        return;
462    }
463    let cut = last_turns_start(&result.lines, turns).unwrap_or(0);
464    if cut > 0 {
465        result.lines.drain(..cut);
466        if let Some(stamps) = result.stamps.as_mut() {
467            stamps.drain(..cut.min(stamps.len()));
468        }
469    }
470    result.offset = Some(first_line + cut as u64);
471}
472
473/// `tail_bytes`: keep the newest lines that fit in `max_bytes` (the newest
474/// line always stays, however large; a line costs its length plus its
475/// newline), then move the start up to the first turn start among them, if
476/// there is one, so the pane doesn't open on the tail of a turn. Lines before
477/// `first_line` were already trimmed (`tail_turns`): `result.offset` wins.
478pub(super) fn trim_to_tail_bytes(result: &mut BlockfileReadRangeResult, first_line: u64, max_bytes: usize) {
479    if result.gen_mismatch.is_some() {
480        return;
481    }
482    let first_line = result.offset.unwrap_or(first_line);
483    let mut cut = result.lines.len();
484    let mut kept = 0usize;
485    for (i, line) in result.lines.iter().enumerate().rev() {
486        let cost = line.len() + 1;
487        if cut < result.lines.len() && kept + cost > max_bytes {
488            break;
489        }
490        kept += cost;
491        cut = i;
492    }
493    if cut > 0 {
494        if let Some(turn) = result.lines[cut..].iter().position(|l| is_claude_turn_start(l)) {
495            cut += turn;
496        }
497        result.lines.drain(..cut);
498        if let Some(stamps) = result.stamps.as_mut() {
499            stamps.drain(..cut.min(stamps.len()));
500        }
501    }
502    result.offset = Some(first_line + cut as u64);
503}
504
505#[cfg(test)]
506mod whole_file_tests {
507    use super::*;
508
509    #[test]
510    fn a_large_transcript_is_never_read_whole() {
511        assert!(!whole_file_read_allowed("output", false, WHOLE_FILE_REFUSE_BYTES));
512        assert!(!whole_file_read_allowed("output", false, 1_310_788_351));
513        assert!(whole_file_read_allowed("output", false, WHOLE_FILE_REFUSE_BYTES - 1));
514    }
515
516    #[test]
517    fn ring_buffers_and_other_files_keep_the_whole_file_path() {
518        assert!(whole_file_read_allowed("output", true, 10 * WHOLE_FILE_REFUSE_BYTES));
519        assert!(whole_file_read_allowed("term", false, 10 * WHOLE_FILE_REFUSE_BYTES));
520    }
521}
522
523#[cfg(test)]
524mod tail_turns_tests {
525    use super::*;
526
527    fn user(text: &str) -> String {
528        serde_json::json!({"type": "user", "message": {"role": "user", "content": text}})
529            .to_string()
530    }
531    fn tool_result() -> String {
532        serde_json::json!({"type": "user", "message": {"role": "user", "content": [{"type": "tool_result", "tool_use_id": "t", "content": "ok"}]}}).to_string()
533    }
534    fn delta(text: &str) -> String {
535        serde_json::json!({"type": "stream_event", "event": {"type": "content_block_delta", "delta": {"type": "text_delta", "text": text}}}).to_string()
536    }
537
538    #[test]
539    fn turn_starts_match_what_the_pane_renders_as_a_user_message() {
540        assert!(is_claude_turn_start(&user("deploy now")));
541        assert!(!is_claude_turn_start(&user("")));
542        assert!(!is_claude_turn_start(&tool_result()));
543        assert!(!is_claude_turn_start(&delta("the user said")));
544        let interrupted = serde_json::json!({"type": "user", "message": {"content": [{"type": "text", "text": "[Request interrupted by user]"}]}}).to_string();
545        assert!(!is_claude_turn_start(&interrupted));
546        let with_image = serde_json::json!({"type": "user", "message": {"content": [
547            {"type": "image", "source": {"type": "base64", "data": "AAAA"}},
548            {"type": "text", "text": "what is this?"}
549        ]}})
550        .to_string();
551        assert!(is_claude_turn_start(&with_image));
552        let image_only =
553            serde_json::json!({"type": "user", "message": {"content": [{"type": "image"}]}})
554                .to_string();
555        assert!(!is_claude_turn_start(&image_only));
556        assert!(!is_claude_turn_start("not json \"user\""));
557    }
558
559    fn transcript() -> Vec<String> {
560        // 3 turns: [0..3) [3..6) [6..9)
561        vec![
562            user("one"),
563            delta("a"),
564            tool_result(),
565            user("two"),
566            delta("b"),
567            delta("c"),
568            user("three"),
569            delta("d"),
570            delta("e"),
571        ]
572    }
573
574    #[test]
575    fn finds_where_the_last_turns_begin() {
576        let lines = transcript();
577        assert_eq!(last_turns_start(&lines, 1), Some(6));
578        assert_eq!(last_turns_start(&lines, 2), Some(3));
579        assert_eq!(last_turns_start(&lines, 3), Some(0));
580        assert_eq!(last_turns_start(&lines, 4), None);
581        assert_eq!(last_turns_start(&lines, 0), None);
582    }
583
584    #[test]
585    fn trims_lines_and_stamps_and_reports_the_new_start() {
586        let mut r = BlockfileReadRangeResult {
587            lines: transcript(),
588            total: 109,
589            stamps: Some((0..9).collect()),
590            ..Default::default()
591        };
592        trim_to_last_turns(&mut r, 100, 2);
593        assert_eq!(r.offset, Some(103));
594        assert_eq!(r.lines, transcript()[3..].to_vec());
595        assert_eq!(r.stamps, Some(vec![3, 4, 5, 6, 7, 8]));
596        assert_eq!(r.total, 109, "total is the file's, untouched");
597    }
598
599    #[test]
600    fn fewer_turns_than_asked_returns_the_whole_range() {
601        let mut r = BlockfileReadRangeResult {
602            lines: transcript(),
603            total: 9,
604            ..Default::default()
605        };
606        trim_to_last_turns(&mut r, 0, 7);
607        assert_eq!(r.lines.len(), 9);
608        assert_eq!(r.offset, Some(0));
609    }
610
611    #[test]
612    fn a_generation_mismatch_is_left_alone() {
613        let mut r = BlockfileReadRangeResult {
614            gen_mismatch: Some(true),
615            ..Default::default()
616        };
617        trim_to_last_turns(&mut r, 5, 2);
618        assert_eq!(r.offset, None);
619    }
620
621    fn lines_of(n: usize, len: usize) -> Vec<String> {
622        (0..n).map(|i| format!("{i:0len$}")).collect()
623    }
624
625    #[test]
626    fn keeps_the_newest_lines_that_fit_in_the_byte_budget() {
627        // Ten 9-byte lines cost 10 bytes each with their newline.
628        let mut r = BlockfileReadRangeResult {
629            lines: lines_of(10, 9),
630            total: 110,
631            stamps: Some((0..10).collect()),
632            ..Default::default()
633        };
634        trim_to_tail_bytes(&mut r, 100, 35);
635        assert_eq!(r.lines, lines_of(10, 9)[7..].to_vec());
636        assert_eq!(r.stamps, Some(vec![7, 8, 9]));
637        assert_eq!(r.offset, Some(107));
638        assert_eq!(r.total, 110, "total is the file's, untouched");
639    }
640
641    #[test]
642    fn a_range_within_the_budget_comes_back_whole() {
643        let mut r = BlockfileReadRangeResult { lines: lines_of(4, 9), total: 4, ..Default::default() };
644        trim_to_tail_bytes(&mut r, 0, 1_000);
645        assert_eq!(r.lines.len(), 4);
646        assert_eq!(r.offset, Some(0));
647    }
648
649    #[test]
650    fn the_newest_line_stays_even_over_the_budget() {
651        let mut r = BlockfileReadRangeResult {
652            lines: vec!["old".to_string(), "x".repeat(500)],
653            total: 2,
654            ..Default::default()
655        };
656        trim_to_tail_bytes(&mut r, 0, 10);
657        assert_eq!(r.lines, vec!["x".repeat(500)]);
658        assert_eq!(r.offset, Some(1));
659    }
660
661    #[test]
662    fn a_byte_cut_inside_a_turn_moves_up_to_the_next_turn_start() {
663        // The budget reaches back into turn two's deltas; the pane opens at
664        // turn three instead of on turn two's tail.
665        let lines = transcript();
666        let budget: usize = lines[5..].iter().map(|l| l.len() + 1).sum();
667        let mut r = BlockfileReadRangeResult { lines: lines.clone(), total: 9, ..Default::default() };
668        trim_to_tail_bytes(&mut r, 0, budget);
669        assert_eq!(r.lines, lines[6..].to_vec());
670        assert_eq!(r.offset, Some(6));
671    }
672
673    #[test]
674    fn with_no_turn_start_in_what_fits_the_byte_cut_stands() {
675        let lines = transcript();
676        let budget: usize = lines[7..].iter().map(|l| l.len() + 1).sum();
677        let mut r = BlockfileReadRangeResult { lines: lines.clone(), total: 9, ..Default::default() };
678        trim_to_tail_bytes(&mut r, 0, budget);
679        assert_eq!(r.lines, lines[7..].to_vec());
680        assert_eq!(r.offset, Some(7));
681    }
682
683    #[test]
684    fn the_byte_budget_applies_after_the_turn_trim() {
685        let lines = transcript();
686        let mut r = BlockfileReadRangeResult { lines: lines.clone(), total: 109, ..Default::default() };
687        trim_to_last_turns(&mut r, 100, 2); // lines [3..9) from line 103
688        let budget: usize = lines[6..].iter().map(|l| l.len() + 1).sum();
689        trim_to_tail_bytes(&mut r, 100, budget);
690        assert_eq!(r.lines, lines[6..].to_vec());
691        assert_eq!(r.offset, Some(106));
692    }
693
694    #[test]
695    fn a_generation_mismatch_is_left_alone_by_the_byte_trim() {
696        let mut r = BlockfileReadRangeResult { gen_mismatch: Some(true), ..Default::default() };
697        trim_to_tail_bytes(&mut r, 5, 10);
698        assert_eq!(r.offset, None);
699    }
700
701    #[test]
702    fn the_request_field_is_optional_on_the_wire() {
703        let old: CommandBlockfileReadRangeData = serde_json::from_value(serde_json::json!({
704            "block_id": "b", "filename": "output", "offset": 0, "limit": 10
705        }))
706        .unwrap();
707        assert_eq!(old.tail_turns, None);
708        assert_eq!(old.tail_bytes, None);
709        let new: CommandBlockfileReadRangeData = serde_json::from_value(serde_json::json!({
710            "block_id": "b", "filename": "output", "offset": 0, "limit": 10, "tail_turns": 7, "tail_bytes": 1000000
711        }))
712        .unwrap();
713        assert_eq!(new.tail_turns, Some(7));
714        assert_eq!(new.tail_bytes, Some(1_000_000));
715        let wire = serde_json::to_value(BlockfileReadRangeResult::default()).unwrap();
716        assert!(
717            wire.get("offset").is_none(),
718            "absent unless tail_turns was asked"
719        );
720    }
721}
722
723fn register_blockfile_read_state(engine: &Arc<WshRpcEngine>, state: &AppState) {
724    let filestore = state.filestore.clone();
725    engine.register_typed(COMMAND_BLOCKFILE_READ_STATE, move |cmd: CommandBlockfileReadStateData, _ctx| {
726        let filestore = filestore.clone();
727        async move { blockfile_read_state(&filestore, cmd) }
728    });
729}
730
731/// `blockfile:read_state`.
732pub(crate) fn blockfile_read_state(
733    filestore: &Arc<crate::backend::storage::filestore::FileStore>,
734    cmd: CommandBlockfileReadStateData,
735) -> Result<BlockfileReadStateResult, String> {
736    if cmd.filename.contains('/') || cmd.filename.contains('\\') || cmd.filename.contains("..") {
737        return Err("blockfile:read_state: filename must not contain path separators".to_string());
738    }
739    tracing::debug!(block_id = %cmd.block_id, filename = %cmd.filename, "blockfile:read_state");
740
741    let content = match filestore.read_file(&cmd.block_id, &cmd.filename) {
742        Ok(Some(bytes)) => Some(String::from_utf8_lossy(&bytes).into_owned()),
743        Ok(None) => None,
744        Err(e) => {
745            // NotFound is the common case (no snapshot yet). Suppress.
746            if matches!(e, crate::backend::storage::StoreError::NotFound) {
747                None
748            } else {
749                tracing::warn!(block_id = %cmd.block_id, error = %e, "blockfile:read_state: read failed");
750                None
751            }
752        }
753    };
754
755    Ok(BlockfileReadStateResult { content })
756}
757
758fn register_blockfile_write_state(engine: &Arc<WshRpcEngine>, state: &AppState) {
759    let filestore = state.filestore.clone();
760    engine.register_typed(COMMAND_BLOCKFILE_WRITE_STATE, move |cmd: CommandBlockfileWriteStateData, _ctx| {
761        let filestore = filestore.clone();
762        async move { blockfile_write_state(&filestore, cmd) }
763    });
764}
765
766/// `blockfile:write_state`.
767pub(crate) fn blockfile_write_state(
768    filestore: &Arc<crate::backend::storage::filestore::FileStore>,
769    cmd: CommandBlockfileWriteStateData,
770) -> Result<BlockfileWriteStateResult, String> {
771    if cmd.filename.contains('/') || cmd.filename.contains('\\') || cmd.filename.contains("..") {
772        return Err("blockfile:write_state: filename must not contain path separators".to_string());
773    }
774    // The transcript and its sidecars are written only by the
775    // transcript paths, which keep its generation and sidecars
776    // consistent (5a-2b). This RPC is for pane state files; letting
777    // it replace `output` would leave `output.idx` / `output.tsidx`
778    // describing other bytes.
779    if matches!(cmd.filename.as_str(), "output" | "output.idx" | "output.tsidx") {
780        return Err(format!(
781            "blockfile:write_state: {} is a transcript file and can't be written through this RPC",
782            cmd.filename
783        ));
784    }
785    let bytes = cmd.content.as_bytes();
786    let bytes_written = bytes.len() as u64;
787    tracing::debug!(block_id = %cmd.block_id, filename = %cmd.filename, bytes = bytes_written, "blockfile:write_state");
788
789    // FileStore.write_file is atomic at the DB level (single
790    // tx replaces all data parts) — no torn write surfaces.
791    // Need make_file first if the sidecar doesn't yet exist.
792    use crate::backend::storage::filestore::{FileMeta, FileOpts};
793    use crate::backend::storage::StoreError;
794    match filestore.write_file(&cmd.block_id, &cmd.filename, bytes) {
795        Ok(()) => {}
796        Err(StoreError::NotFound) => {
797            filestore
798                .make_file(&cmd.block_id, &cmd.filename, FileMeta::default(), FileOpts::default())
799                .map_err(|e| format!("blockfile:write_state: make_file: {e}"))?;
800            filestore
801                .write_file(&cmd.block_id, &cmd.filename, bytes)
802                .map_err(|e| format!("blockfile:write_state: write_file: {e}"))?;
803        }
804        Err(e) => return Err(format!("blockfile:write_state: {e}")),
805    }
806
807    Ok(BlockfileWriteStateResult { bytes_written })
808}
809
810/// A transcript stream's line count from its counter, with the stream and
811/// generation it counts (Phase 5a-3). A file with no epoch yet gets one
812/// first — `init_line_counter`, one read of the file, once per epoch; call on
813/// the blocking pool. `None` when it can't be counted (no such file, or
814/// mid-write by a build without transactions), and the caller falls back.
815fn counted_line_count(
816    fs: &crate::backend::storage::filestore::FileStore,
817    zone: &str,
818    stream: String,
819) -> Option<BlockfileLineCountResult> {
820    use crate::backend::agent_session::OUTPUT_FILE;
821    let state = fs.line_state(zone, OUTPUT_FILE).ok()??;
822    let state = if state.counted.is_some() { state } else { fs.init_line_counter(zone, OUTPUT_FILE).ok()?? };
823    let counted = state.counted?;
824    Some(BlockfileLineCountResult { count: counted.lines, stream: Some(stream), gen: Some(counted.gen), history_damaged: None })
825}
826
827/// Where `block_id`'s transcript stands, from the same source `read_range`
828/// reads it from (the block's own `output`, or the agent's global zone): its
829/// stream, generation and line count. `None` while it doesn't exist or can't
830/// be counted. For the viewer feed, which reads the tail through `read_range`.
831pub(crate) async fn transcript_position(
832    filestore: &Arc<crate::backend::storage::filestore::FileStore>,
833    global_store: &Option<Arc<crate::backend::storage::filestore::FileStore>>,
834    mstore: &Arc<crate::backend::storage::store::Store>,
835    block_id: &str,
836) -> Option<(String, String, u64)> {
837    use crate::backend::agent_session::OUTPUT_FILE;
838    let (filestore, global_store, mstore, block_id) = (filestore.clone(), global_store.clone(), mstore.clone(), block_id.to_string());
839    // The source lookup reads the object store and the global transcript store, so it runs here with the count.
840    let counted = tokio::task::spawn_blocking(move || {
841        let (fs, zone, stream) = match global_output_source(&filestore, &global_store, &mstore, &block_id, OUTPUT_FILE) {
842            Some((gfs, zone)) => (gfs, zone.clone(), format!("g:{zone}")),
843            None => (filestore.clone(), block_id.clone(), format!("b:{block_id}")),
844        };
845        counted_line_count(&fs, &zone, stream)
846    })
847    .await
848    .ok()
849    .flatten()?;
850    Some((counted.stream?, counted.gen?, counted.count))
851}
852
853/// The valid generation of a transcript's `output`, read from the database on
854/// the blocking pool (the global store can be held by another srv instance).
855async fn db_generation(fs: &Arc<crate::backend::storage::filestore::FileStore>, zone: &str) -> Option<String> {
856    let (fs, zone) = (fs.clone(), zone.to_string());
857    tokio::task::spawn_blocking(move || {
858        crate::backend::blockcontroller::shell::output_now(&fs, &zone).and_then(|(_, gen)| gen)
859    })
860    .await
861    .ok()
862    .flatten()
863}
864
865#[cfg(test)]
866#[path = "blockfile_transcript_tests.rs"]
867mod transcript_rpc_tests;
868
869#[cfg(test)]
870#[path = "blockfile_handler_tests.rs"]
871mod handler_tests;
872
873#[cfg(test)]
874#[path = "blockfile_read_range_tests.rs"]
875mod read_range_tests;