Skip to main content

agentmux_srv/server/agent_handlers/
fork_history.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! `copyforkhistory`: a fork's pane starts with its parent's history
5//! (`agent_session::fork_history`). Forks only; see "Fork, spawn and worker"
6//! in `mod.rs`.
7
8use std::sync::Arc;
9
10use crate::backend::agent_session::fork_history::{copy_older_session_history, copy_parent_history, ForkHistory};
11use crate::backend::history::HistoryService;
12use crate::backend::rpc::engine::WshRpcEngine;
13use crate::backend::rpc_types::{CommandCopyForkHistoryData, CopyForkHistoryResult, COMMAND_COPY_FORK_HISTORY};
14use crate::backend::storage::store::Store;
15
16use super::super::AppState;
17
18pub(super) fn register(engine: &Arc<WshRpcEngine>, state: &AppState) {
19    let mstore = state.mstore.clone();
20    let history = state.history_service.clone();
21    engine.register_typed(COMMAND_COPY_FORK_HISTORY, move |cmd: CommandCopyForkHistoryData, _ctx| {
22        let mstore = mstore.clone();
23        let history = history.clone();
24        async move { tokio::task::spawn_blocking(move || copy_fork_history(&mstore, &history, &cmd)).await.map_err(|e| format!("copyforkhistory: {e}"))? }
25    });
26}
27
28/// Refuses anything but a real fork of `source_id` (its `parent_id`, and a
29/// branch label, which only `forkagentdefinition` sets) on a provider that
30/// names its sessions.
31pub(super) fn copy_fork_history(mstore: &Store, history: &HistoryService, cmd: &CommandCopyForkHistoryData) -> Result<CopyForkHistoryResult, String> {
32    let fork = mstore
33        .agent_def_get(&cmd.fork_id)
34        .map_err(|e| format!("copyforkhistory: {e}"))?
35        .ok_or_else(|| format!("copyforkhistory: no agent {}", cmd.fork_id))?;
36    if fork.parent_id != cmd.source_id || fork.branch_label.is_empty() {
37        return Err(format!("copyforkhistory: {} is not a fork of {}", cmd.fork_id, cmd.source_id));
38    }
39    let field = crate::backend::providers::get_provider(crate::backend::providers::resolve_provider_alias(&cmd.provider))
40        .map(|p| p.session_id_field)
41        .unwrap_or("");
42    if field.is_empty() {
43        return Err(format!("copyforkhistory: {} has no sessions to continue", cmd.provider));
44    }
45    let gfs = crate::backend::agent_session::global_transcript_store()
46        .ok_or_else(|| "copyforkhistory: no transcript store".to_string())?;
47    let result = |copied: bool, reason: &str, bytes: u64| CopyForkHistoryResult { copied, reason: reason.to_string(), bytes };
48    let runtime = crate::backend::agent_session::fork_history::runtime_of_agent(mstore, &cmd.source_id);
49    let copied = match copy_parent_history(gfs, &cmd.source_id, &cmd.fork_id, &cmd.session_id, field, runtime)? {
50        ForkHistory::Copied { bytes } => result(true, "", bytes),
51        // Either way the session may be in the record: after a New conversation
52        // the current zone is empty and the older sessions are in an archive.
53        ForkHistory::NoParentHistory => older_session(gfs, history, cmd, field, runtime, "no_parent_history")?,
54        ForkHistory::NotTheLastSession => older_session(gfs, history, cmd, field, runtime, "not_the_last_session")?,
55        ForkHistory::ForkHasHistory => result(false, "fork_has_history", 0),
56    };
57    if copied.copied {
58        // The fork has history now: the History pane's agent list gains its row.
59        crate::backend::history_changed::mark();
60    }
61    Ok(copied)
62}
63
64/// A fork of an older session: the parent's history up to where that session
65/// ends, found in the agent's record. A session the record doesn't know has no
66/// history to copy, and the answer is `reason`, what the current zone said.
67fn older_session(
68    gfs: &crate::backend::storage::filestore::FileStore,
69    history: &HistoryService,
70    cmd: &CommandCopyForkHistoryData,
71    field: &str,
72    runtime: crate::backend::transcript::origin_sig::WriterRuntime,
73    reason: &str,
74) -> Result<CopyForkHistoryResult, String> {
75    let not_last = || CopyForkHistoryResult { copied: false, reason: reason.to_string(), bytes: 0 };
76    let sessions = history.agent_sessions(&cmd.source_id).sessions;
77    let Some(session) = sessions.iter().find(|s| s.session_id == cmd.session_id && !s.zone.is_empty() && s.end_byte > 0) else {
78        return Ok(not_last());
79    };
80    Ok(match copy_older_session_history(gfs, &cmd.source_id, &cmd.fork_id, &cmd.session_id, field, &session.zone, session.end_byte as i64, runtime)? {
81        ForkHistory::Copied { bytes } => CopyForkHistoryResult { copied: true, reason: String::new(), bytes },
82        ForkHistory::NoParentHistory => CopyForkHistoryResult { copied: false, reason: "no_parent_history".to_string(), bytes: 0 },
83        ForkHistory::ForkHasHistory => CopyForkHistoryResult { copied: false, reason: "fork_has_history".to_string(), bytes: 0 },
84        ForkHistory::NotTheLastSession => not_last(),
85    })
86}