Skip to content

The fastest, cheapest, most efficient open-source agent harness. Run more than 500 agents on a $10 VPS.

feat(agent): route sub-agent transcripts through the turn tree's store

Steven Enamakeldfde77f6098f
diff --git a/crates/openhuman-core/src/agent/context_breakdown.rs b/crates/openhuman-core/src/agent/context_breakdown.rs
index 7ed8a997c1..f24d24ed2d 100644
--- a/crates/openhuman-core/src/agent/context_breakdown.rs
+++ b/crates/openhuman-core/src/agent/context_breakdown.rs
@@ -137,10 +137,17 @@ fn history_tokens(context_tokens: usize, fixed_prompt_tokens: usize) -> usize {
context_tokens.saturating_sub(fixed_prompt_tokens)
}
-async fn history_section(thread_id: &str, fixed_prompt_tokens: usize) -> Option<ContextSection> {
- let outcome = crate::threads::ops::token_usage(crate::threads::ops::ThreadTokenUsageRequest {
- thread_id: thread_id.to_string(),
- })
+async fn history_section(
+ ctx: &DispatchCtx,
+ thread_id: &str,
+ fixed_prompt_tokens: usize,
+) -> Option<ContextSection> {
+ let outcome = crate::threads::ops::token_usage(
+ ctx,
+ crate::threads::ops::ThreadTokenUsageRequest {
+ thread_id: thread_id.to_string(),
+ },
+ )
.await
.ok()?;
let usage = outcome.value.data?;
@@ -205,7 +212,7 @@ pub async fn context_breakdown(
.map(str::trim)
.filter(|s| !s.is_empty())
{
- if let Some(history) = history_section(thread_id, fixed_prompt_tokens).await {
+ if let Some(history) = history_section(ctx, thread_id, fixed_prompt_tokens).await {
sections.push(history);
}
}
diff --git a/crates/openhuman-core/src/agent/context_breakdown_tests.rs b/crates/openhuman-core/src/agent/context_breakdown_tests.rs
index eb000d37f6..bd56098035 100644
--- a/crates/openhuman-core/src/agent/context_breakdown_tests.rs
+++ b/crates/openhuman-core/src/agent/context_breakdown_tests.rs
@@ -90,7 +90,8 @@ async fn history_section_is_none_for_an_unknown_thread() {
// `has_usage: false` (or the RPC itself fails) and this must degrade to
// `None` rather than propagating an error — the breakdown must still
// answer with just the prompt/tools sections.
- let section = history_section("context-breakdown-unknown-thread-id", 0).await;
+ let ctx = DispatchCtx::process_default();
+ let section = history_section(&ctx, "context-breakdown-unknown-thread-id", 0).await;
assert!(section.is_none());
}
diff --git a/crates/openhuman-core/src/agent/session_host/runtime_session_turn.rs b/crates/openhuman-core/src/agent/session_host/runtime_session_turn.rs
index b336676b4d..ab37b2fe7b 100644
--- a/crates/openhuman-core/src/agent/session_host/runtime_session_turn.rs
+++ b/crates/openhuman-core/src/agent/session_host/runtime_session_turn.rs
@@ -44,6 +44,9 @@ impl OpenHumanSessionHost {
context.task_recency_window = self.task_recency_window;
context.autonomous_iter_cap = self.autonomous_iter_cap;
context.workspace = self.workspace_descriptor.clone();
+ // Sub-agents of this turn write their transcripts to this session's
+ // store, under the key it resolved for its own.
+ context.transcripts = Some(self.session_locator());
// The web backstop's deadline (`host_env.turn_deadline`), when this
// turn runs under one, is already on the context: the harness winds
// down before it instead of being dropped by it.
diff --git a/crates/openhuman-core/src/agent/session_store/mod.rs b/crates/openhuman-core/src/agent/session_store/mod.rs
index 70d3e4c291..39f6756bb4 100644
--- a/crates/openhuman-core/src/agent/session_store/mod.rs
+++ b/crates/openhuman-core/src/agent/session_store/mod.rs
@@ -18,7 +18,6 @@ use std::collections::HashMap;
use std::sync::{Arc, LazyLock, Mutex, PoisonError, RwLock};
use tinyagents_session::port::{AgentStores, SessionStoreProvider};
-use tinyagents_session::transcript::agent_transcript_root;
pub mod ledger_sync;
mod rebound;
@@ -26,10 +25,10 @@ mod workspace;
pub use rebound::{rebind_all, ReboundSessionStores};
pub use workspace::{
- artifact_blobs_for, attachment_stash_for, current_documents_for, default_turn_states_for, ledger_for,
- provider_for_workspace, release_workspace_defaults, require_ledger, status_store_for,
- stores_for, stores_or_ephemeral, turn_states_for, with_ledger, with_ledger_async,
- WorkspaceSessionStores,
+ artifact_blobs_for, attachment_stash_for, current_documents_for, default_turn_states_for,
+ ledger_for, provider_for_workspace, release_workspace_defaults, require_ledger,
+ status_store_for, stores_for, stores_or_ephemeral, turn_states_for, with_ledger,
+ with_ledger_async, WorkspaceSessionStores,
};
static PROVIDER: LazyLock<RwLock<Option<Arc<dyn SessionStoreProvider>>>> =
@@ -196,28 +195,6 @@ pub fn workspace_transcripts(
}
}
-/// The workspace root transcripts are written under: the agent's own
-/// directory under an embedded agent's context, else `workspace_dir` — which
-/// for a SaaS profile's default agent is that profile's own workspace.
-#[must_use]
-pub fn transcript_root(workspace_dir: &std::path::Path) -> std::path::PathBuf {
- match current_embedded_agent() {
- Some(agent) => agent_transcript_root(workspace_dir, &agent),
- None => workspace_dir.to_path_buf(),
- }
-}
-
-/// The embedded agent the calling tenant runs as, if any. A SaaS profile's
-/// default agent has none: its transcripts live at its workspace root, which
-/// no other profile shares. A SaaS task with no scope has none either; the
-/// workspace it was handed is the only one it touches.
-#[must_use]
-pub fn current_embedded_agent() -> Option<String> {
- crate::core::runtime::current_tenant()
- .ok()
- .and_then(|tenant| tenant.agent)
-}
-
/// The stores of the tenant the current [`CoreContext`] works for, keyed by
/// [`session_key`](crate::core::runtime::session_key): the agent it was
/// derived for ([`CoreContext::session_agent`]), else [`DEFAULT_AGENT`],
@@ -250,11 +227,24 @@ pub fn current() -> Option<AgentStores> {
/// session's own definition id), as before profiles existed.
#[must_use]
pub fn current_agent_key_or(fallback: &str) -> String {
- let tenant = crate::core::runtime::tenant::current_tenant_or_isolated("session_locator");
+ agent_key_for(
+ &crate::core::runtime::tenant::current_tenant_or_isolated("session_locator"),
+ fallback,
+ )
+}
+
+/// The agent id `tenant`'s transcripts are kept under, for a caller that
+/// already holds the request's tenant (an RPC handler's context): the
+/// [`session_key`](crate::core::runtime::session_key) when it serves a SaaS
+/// profile, else its agent, else `fallback` (the session's definition id).
+/// [`current_agent_key_or`] is this over the ambient tenant, so a reader that
+/// passes its tenant here resolves the same store the session host wrote to.
+#[must_use]
+pub fn agent_key_for(tenant: &crate::core::runtime::Tenant, fallback: &str) -> String {
if tenant.profile.is_some() {
- return crate::core::runtime::session_key(&tenant);
+ return crate::core::runtime::session_key(tenant);
}
- tenant.agent.unwrap_or_else(|| fallback.to_string())
+ tenant.agent.clone().unwrap_or_else(|| fallback.to_string())
}
/// The workspace the current [`CoreContext`](crate::core::runtime::CoreContext)
diff --git a/crates/openhuman-core/src/agent/session_store/mod_tests.rs b/crates/openhuman-core/src/agent/session_store/mod_tests.rs
index da3bc7d498..ea8bb8777d 100644
--- a/crates/openhuman-core/src/agent/session_store/mod_tests.rs
+++ b/crates/openhuman-core/src/agent/session_store/mod_tests.rs
@@ -99,10 +99,15 @@ async fn without_a_store_transcripts_come_from_the_workspace_store_not_files() {
parent_session_id: None,
};
let history = locator
- .open_stem(&tinyagents_session::transcript::session_stem(&session), meta)
+ .open_stem(
+ &tinyagents_session::transcript::session_stem(&session),
+ meta,
+ )
.expect("open the session's write handle");
history
- .append(tinyagents_session::transcript::TranscriptMessage::user("hi"))
+ .append(tinyagents_session::transcript::TranscriptMessage::user(
+ "hi",
+ ))
.expect("append a message");
assert!(transcripts_or_files("u1", dir).session_exists(&session));
assert!(
@@ -171,23 +176,19 @@ async fn under<T>(ctx: Arc<crate::core::runtime::CoreContext>, f: impl FnOnce()
}
#[tokio::test]
-async fn desktop_session_keys_and_transcript_roots_are_unchanged() {
- let ws = std::path::Path::new("/ws");
+async fn desktop_session_keys_are_unchanged() {
assert_eq!(current_agent_key_or("orchestrator"), "orchestrator");
- assert_eq!(transcript_root(ws), ws.to_path_buf());
- let (key, root) = under(derived(None, Some("alpha")), || {
- (current_agent_key_or("orchestrator"), transcript_root(ws))
+ let key = under(derived(None, Some("alpha")), || {
+ current_agent_key_or("orchestrator")
})
.await;
assert_eq!(key, "alpha");
- assert_eq!(root, agent_transcript_root(ws, "alpha"));
}
#[tokio::test]
async fn two_profiles_default_agents_keep_separate_session_keys_and_stores() {
- let ws = std::path::Path::new("/ws-profile");
- let (alice_key, alice_root) = under(derived(Some("alice"), None), || {
- (current_agent_key_or("orchestrator"), transcript_root(ws))
+ let alice_key = under(derived(Some("alice"), None), || {
+ current_agent_key_or("orchestrator")
})
.await;
let bob_key = under(derived(Some("bob"), None), || {
@@ -196,8 +197,6 @@ async fn two_profiles_default_agents_keep_separate_session_keys_and_stores() {
.await;
assert_eq!(alice_key, "alice~default");
assert_eq!(bob_key, "bob~default");
- // The default agent's transcripts sit at the profile's workspace root.
- assert_eq!(alice_root, ws.to_path_buf());
let provider: Arc<dyn SessionStoreProvider> = Arc::new(InMemorySessionStores::new());
let stores_of = |profile: &'static str| {
@@ -306,3 +305,28 @@ async fn a_stashed_attachment_survives_a_restart_of_the_workspace_store() {
.unwrap()
.is_none());
}
+
+#[test]
+fn agent_key_for_matches_the_session_hosts_resolution() {
+ use crate::core::runtime::Tenant;
+ let desktop = Tenant::default();
+ assert_eq!(agent_key_for(&desktop, "orchestrator"), "orchestrator");
+ let embedded = Tenant {
+ profile: None,
+ agent: Some("a1".into()),
+ };
+ assert_eq!(agent_key_for(&embedded, "orchestrator"), "a1");
+ let profile = Tenant {
+ profile: Some("p1".into()),
+ agent: None,
+ };
+ assert_eq!(agent_key_for(&profile, "orchestrator"), "p1~default");
+ let profile_agent = Tenant {
+ profile: Some("p1".into()),
+ agent: Some("a1".into()),
+ };
+ assert_eq!(
+ agent_key_for(&profile_agent, "orchestrator"),
+ crate::core::runtime::session_key(&profile_agent)
+ );
+}
diff --git a/crates/openhuman-core/src/agent/subagent_host/ops/graph/dispatch.rs b/crates/openhuman-core/src/agent/subagent_host/ops/graph/dispatch.rs
index 35c242157e..93a99160fc 100644
--- a/crates/openhuman-core/src/agent/subagent_host/ops/graph/dispatch.rs
+++ b/crates/openhuman-core/src/agent/subagent_host/ops/graph/dispatch.rs
@@ -58,8 +58,8 @@ pub(in super::super) async fn run_subagent_via_graph(
model_vision: bool,
// Transcript-persistence provenance: the resolved child transcript stem
// (`{parent_chain}__{child_session_key}`) and the provider label (the parent
- // turn's event channel) so the child's raw transcript lands in `session_raw`
- // with the right stem + provider/model meta — parity with the removed
+ // turn's event channel) so the child's raw transcript lands in the turn
+ // tree's transcript store with the right stem + provider/model meta — parity with the removed
// `SubagentObserver::persist_transcript`.
transcript_stem: &str,
provider_label: &str,
@@ -94,6 +94,8 @@ pub(in super::super) async fn run_subagent_via_graph(
// the child carrier cannot disagree.
let trace_session_group = run_context.thread_id.clone().or_else(|| thread_id.clone());
let thread_id = inherited_thread_id(run_context.thread_id.clone(), thread_id);
+ // Where this child's transcript is written: its turn tree's store.
+ let transcripts = super::transcript::subagent_transcripts(&run_context, &workspace_dir);
tracing::info!(
model,
max_iterations,
@@ -283,8 +285,8 @@ pub(in super::super) async fn run_subagent_via_graph(
Err(err) => {
// #4466: the harness dropped its partial transcript, but the snapshot
// middleware mirrored every completed round. Persist those rounds to
- // `session_raw` (so `learning/transcript_ingest` can still read a
- // failed run) and mirror them onto the worker thread, THEN surface the
+ // the turn tree's transcript store (so the thread's usage and view
+ // still count a failed run) and mirror them onto the worker thread, THEN surface the
// error. Previously the `?`-return skipped both persistence steps, so
// a failed run left no transcript and an empty worker thread.
let mapped = map_tinyagents_subagent_error(err);
@@ -318,6 +320,7 @@ pub(in super::super) async fn run_subagent_via_graph(
"[subagent_host:graph] sub-agent run errored; persisting recovered transcript before returning (#4466)"
);
super::transcript::persist_failed_run(
+ transcripts.as_ref(),
&workspace_dir,
transcript_stem,
agent_id,
@@ -441,11 +444,9 @@ pub(in super::super) async fn run_subagent_via_graph(
}
}
- // Persist the sub-agent's raw transcript to `session_raw` (parity with the
- // removed `SubagentObserver::persist_transcript`). The graph runner replaced
- // the observer but only mirrored to the worker thread, so per-child
- // transcripts stopped being written — breaking downstream learning ingestion
- // (`learning/transcript_ingest`, which reads `session_raw/*.jsonl`).
+ // Persist the sub-agent's raw transcript to the turn tree's transcript
+ // store (parity with the removed `SubagentObserver::persist_transcript`),
+ // where the thread's usage and transcript view read every child back.
// On a cap-hit / early-exit, `outcome.text` is the checkpoint (or clarifying
// question) that stands in for a final assistant turn — append it so the
// persisted transcript reflects the actual final state, not the pre-checkpoint
@@ -465,7 +466,7 @@ pub(in super::super) async fn run_subagent_via_graph(
history.as_slice()
};
persist_subagent_transcript(
- &workspace_dir,
+ transcripts.as_ref(),
transcript_stem,
agent_id,
task_id,
diff --git a/crates/openhuman-core/src/agent/subagent_host/ops/graph/transcript.rs b/crates/openhuman-core/src/agent/subagent_host/ops/graph/transcript.rs
index 10206a6621..b47cc59b29 100644
--- a/crates/openhuman-core/src/agent/subagent_host/ops/graph/transcript.rs
+++ b/crates/openhuman-core/src/agent/subagent_host/ops/graph/transcript.rs
@@ -1,8 +1,12 @@
-//! Persisting a sub-agent turn's (or a failed run's) raw transcript to
-//! `session_raw`, mirroring the removed `SubagentObserver::persist_transcript`.
+//! Persisting a sub-agent turn's (or a failed run's) raw transcript to the
+//! turn tree's transcript store, mirroring the removed
+//! `SubagentObserver::persist_transcript`.
+
+use std::sync::Arc;
use crate::agent::subagent_host::types::SubagentRunError;
-use tinyagents_session::transcript::TranscriptMessage;
+use crate::agent::tinyagents::host::OpenHumanRunContext;
+use tinyagents_session::transcript::{TranscriptLocator, TranscriptMessage, TranscriptTurn};
use super::dispatch::AggregatedUsage;
use super::worker_mirror::mirror_worker_thread_from_history;
@@ -39,13 +43,45 @@ pub(super) fn failed_run_history(
)
}
-/// Persist a sub-agent turn's raw transcript to `session_raw`, mirroring the
-/// removed `SubagentObserver::persist_transcript`: `agent_type:"subagent"`, the
+/// The store a sub-agent's transcript goes to: the turn tree's own
+/// ([`OpenHumanRunContext::transcripts`], set by the root session), so it lands
+/// beside its parent's under the same key. A run no session started falls
+/// back to the store of the run's own context, keyed like the parent
+/// session's (its definition id, or the default agent).
+pub(super) fn subagent_transcripts(
+ run_context: &OpenHumanRunContext,
+ workspace_dir: &std::path::Path,
+) -> Arc<dyn TranscriptLocator> {
+ if let Some(transcripts) = run_context.transcripts.clone() {
+ return transcripts;
+ }
+ let tenant = run_context
+ .core
+ .as_ref()
+ .and_then(std::sync::Weak::upgrade)
+ .map(|core| crate::core::runtime::Tenant::of(&core))
+ .unwrap_or_default();
+ let fallback = run_context
+ .parent
+ .as_ref()
+ .map_or(crate::agent::session_store::DEFAULT_AGENT, |parent| {
+ parent.agent_definition_id.as_str()
+ });
+ let key = crate::agent::session_store::agent_key_for(&tenant, fallback);
+ tracing::debug!(
+ profile = tenant.profile.is_some(),
+ "[subagent_host:graph] no turn-tree transcript store; using the run context's"
+ );
+ crate::agent::session_store::transcripts_or_files(&key, workspace_dir)
+}
+
+/// Persist a sub-agent turn's raw transcript to `transcripts` under
+/// `transcript_stem`, mirroring the removed `SubagentObserver::persist_transcript`: `agent_type:"subagent"`, the
/// `task_id`, and the provider/model + usage carried on the last assistant
/// message so per-thread usage reads price the sub-agent at its own model.
#[allow(clippy::too_many_arguments)]
pub(super) fn persist_subagent_transcript(
- workspace_dir: &std::path::Path,
+ transcripts: &dyn TranscriptLocator,
transcript_stem: &str,
agent_id: &str,
task_id: &str,
@@ -60,18 +96,6 @@ pub(super) fn persist_subagent_transcript(
) {
use tinyagents_session::transcript;
- let root = crate::agent::session_store::transcript_root(workspace_dir);
- let path = match transcript::resolve_keyed_transcript_path(&root, transcript_stem) {
- Ok(p) => p,
- Err(err) => {
- tracing::debug!(
- agent_id,
- error = %err,
- "[subagent_host:graph] failed to resolve child transcript path"
- );
- return;
- }
- };
let now = chrono::Utc::now().to_rfc3339();
let turn_usage = transcript::TurnUsage {
provider: provider_label.to_string(),
@@ -122,7 +146,39 @@ pub(super) fn persist_subagent_transcript(
thread_id: thread_id.map(str::to_owned),
task_id: Some(task_id.to_string()),
};
- if let Err(err) = transcript::write_transcript(&path, history, &meta, Some(&turn_usage)) {
+ let handle = match transcripts.open_stem(transcript_stem, meta.clone()) {
+ Ok(handle) => handle,
+ Err(err) => {
+ tracing::debug!(
+ agent_id,
+ error = %err,
+ "[subagent_host:graph] failed to open child transcript"
+ );
+ return;
+ }
+ };
+ // What the stem already holds (a resumed sub-agent session) is the
+ // baseline: an extension appends, anything else is recorded as a
+ // compaction, so nothing written before is erased.
+ let prev = match handle.messages() {
+ Ok(prev) => prev,
+ Err(err) => {
+ tracing::debug!(
+ agent_id,
+ error = %err,
+ "[subagent_host:graph] failed to read child transcript"
+ );
+ return;
+ }
+ };
+ if let Err(err) = handle.append_turn(TranscriptTurn {
+ prev: &prev,
+ next: history,
+ meta: &meta,
+ turn_usage: Some(&turn_usage),
+ request_id: None,
+ tools: None,
+ }) {
tracing::debug!(
agent_id,
error = %err,
@@ -132,8 +188,8 @@ pub(super) fn persist_subagent_transcript(
}
/// Persist a **failed** sub-agent run (#4466): write whatever rounds the live
-/// transcript-snapshot middleware captured before the harness error to
-/// `session_raw` (so `learning/transcript_ingest` can still ingest a failed run,
+/// transcript-snapshot middleware captured before the harness error to the
+/// turn tree's transcript store (so `learning/transcript_ingest` can still ingest a failed run,
/// not skip an absent file), mirror those rounds onto the worker thread, and
/// append a trailing failure marker so the record is self-describing. `recovered`
/// holds only what a provider accepted; steps only the failing request carried
@@ -142,6 +198,7 @@ pub(super) fn persist_subagent_transcript(
/// number of model calls a provider answered.
#[allow(clippy::too_many_arguments)]
pub(super) fn persist_failed_run(
+ transcripts: &dyn TranscriptLocator,
workspace_dir: &std::path::Path,
transcript_stem: &str,
agent_id: &str,
@@ -166,7 +223,7 @@ pub(super) fn persist_failed_run(
history.push(TranscriptMessage::assistant(marker.clone()));
persist_subagent_transcript(
- workspace_dir,
+ transcripts,
transcript_stem,
agent_id,
task_id,
diff --git a/crates/openhuman-core/src/agent/subagent_host/ops/graph_failed_run_tests.rs b/crates/openhuman-core/src/agent/subagent_host/ops/graph_failed_run_tests.rs
index b70d485c9c..53ce3f4b89 100644
--- a/crates/openhuman-core/src/agent/subagent_host/ops/graph_failed_run_tests.rs
+++ b/crates/openhuman-core/src/agent/subagent_host/ops/graph_failed_run_tests.rs
@@ -32,6 +32,40 @@ impl ChatModel<()> for FailsOnThirdCallProvider {
}
}
+/// Reads the transcript a sub-agent run wrote under `stem` back through the
+/// store it wrote to.
+fn read_stem(
+ locator: &dyn tinyagents_session::transcript::TranscriptLocator,
+ stem: &str,
+) -> tinyagents_session::transcript::SessionTranscript {
+ let seed = tinyagents_session::transcript::TranscriptMeta {
+ agent_name: String::new(),
+ agent_id: None,
+ agent_type: None,
+ dispatcher: String::new(),
+ provider: None,
+ model: None,
+ created: String::new(),
+ updated: String::new(),
+ turn_count: 0,
+ prefix_message_count: None,
+ input_tokens: 0,
+ output_tokens: 0,
+ cached_input_tokens: 0,
+ charged_amount_usd: 0.0,
+ thread_id: None,
+ task_id: None,
+ session_id: None,
+ parent_session_id: None,
+ };
+ locator
+ .open_stem(stem, seed)
+ .expect("open the child stem")
+ .read_session()
+ .expect("read the child transcript")
+ .expect("the child transcript was written")
+}
+
/// #6281: a failed sub-agent run persists only the round a provider accepted as
/// structured history; the round only the rejected request carried goes into the
/// failure marker as text, so a resumed sub-agent cannot replay it.
@@ -46,6 +80,10 @@ async fn failed_subagent_run_keeps_its_unanswered_round_out_of_history() {
let mut history = vec![TranscriptMessage::user("please echo twice")];
let workspace = tempfile::TempDir::new().expect("temp workspace");
let stem = "root-session__failed_run";
+ let locator =
+ crate::agent::session_store::transcripts_or_files("orchestrator", workspace.path());
+ let mut run_context = crate::agent::tinyagents::host::OpenHumanRunContext::new();
+ run_context.transcripts = Some(locator.clone());
let result = run_subagent_via_graph(
crate::agent::tinyagents::TurnModelSource::from_model(provider),
@@ -63,7 +101,7 @@ async fn failed_subagent_run_keeps_its_unanswered_round_out_of_history() {
"task-failed",
false,
None,
- crate::agent::tinyagents::host::OpenHumanRunContext::new(),
+ run_context,
None,
workspace.path().to_path_buf(),
None,
@@ -77,10 +115,7 @@ async fn failed_subagent_run_keeps_its_unanswered_round_out_of_history() {
.await;
assert!(result.is_err(), "the rejected third call fails the run");
- use tinyagents_session::transcript;
- let path =
- transcript::resolve_keyed_transcript_path(workspace.path(), stem).expect("transcript path");
- let persisted = transcript::read_transcript(&path).expect("failed run transcript");
+ let persisted = read_stem(locator.as_ref(), stem);
let tool_rows: Vec<&str> = persisted
.messages
.iter()
@@ -106,16 +141,15 @@ async fn failed_subagent_run_keeps_its_unanswered_round_out_of_history() {
// Two model calls were answered before the rejection; the recorded
// iteration must say so rather than count persisted messages.
- let raw = std::fs::read_to_string(&path).expect("raw transcript");
- let marker_line = raw
- .lines()
- .filter_map(|line| serde_json::from_str::<serde_json::Value>(line).ok())
- .rfind(|line| line.get("role").and_then(|role| role.as_str()) == Some("assistant"))
- .expect("failure marker line");
+ let iteration = persisted
+ .messages
+ .last()
+ .and_then(|marker| marker.turn_usage.as_ref())
+ .map(|usage| usage.iteration);
assert_eq!(
- marker_line.get("iteration").and_then(|n| n.as_u64()),
+ iteration,
Some(2),
- "the failed run reports the model calls a provider answered: {marker_line}"
+ "the failed run reports the model calls a provider answered"
);
}
diff --git a/crates/openhuman-core/src/agent/subagent_host/ops/graph_tests.rs b/crates/openhuman-core/src/agent/subagent_host/ops/graph_tests.rs
index 4213c61da9..ac261ba16c 100644
--- a/crates/openhuman-core/src/agent/subagent_host/ops/graph_tests.rs
+++ b/crates/openhuman-core/src/agent/subagent_host/ops/graph_tests.rs
@@ -9,9 +9,71 @@ use tinyinference_llm::tool::ToolCall;
use tinytools::Tool;
use tinytools::ToolResult;
+/// Reads the transcript a sub-agent run wrote under `stem` back through the
+/// store it wrote to.
+fn read_stem(
+ locator: &dyn tinyagents_session::transcript::TranscriptLocator,
+ stem: &str,
+) -> tinyagents_session::transcript::SessionTranscript {
+ let seed = tinyagents_session::transcript::TranscriptMeta {
+ agent_name: String::new(),
+ agent_id: None,
+ agent_type: None,
+ dispatcher: String::new(),
+ provider: None,
+ model: None,
+ created: String::new(),
+ updated: String::new(),
+ turn_count: 0,
+ prefix_message_count: None,
+ input_tokens: 0,
+ output_tokens: 0,
+ cached_input_tokens: 0,
+ charged_amount_usd: 0.0,
+ thread_id: None,
+ task_id: None,
+ session_id: None,
+ parent_session_id: None,
+ };
+ locator
+ .open_stem(stem, seed)
+ .expect("open the child stem")
+ .read_session()
+ .expect("read the child transcript")
+ .expect("the child transcript was written")
+}
+
+#[test]
+fn a_subagent_writes_to_its_turn_trees_store_else_its_contexts() {
+ let workspace = tempfile::tempdir().unwrap();
+ let tree = crate::agent::session_store::transcripts_or_files("tree-key", workspace.path());
+ let mut run_context = crate::agent::tinyagents::host::OpenHumanRunContext::new();
+ run_context.transcripts = Some(tree.clone());
+ let chosen = super::transcript::subagent_transcripts(&run_context, workspace.path());
+ assert!(
+ Arc::ptr_eq(&chosen, &tree),
+ "the root session's store is used as is"
+ );
+
+ // No session handed a store over: the default agent's store of the run's
+ // (here unbound, desktop) tenant.
+ let unbound = crate::agent::tinyagents::host::OpenHumanRunContext::new();
+ let fallback = super::transcript::subagent_transcripts(&unbound, workspace.path());
+ assert_eq!(
+ fallback.destination_key(),
+ crate::agent::session_store::transcripts_or_files(
+ crate::agent::session_store::DEFAULT_AGENT,
+ workspace.path()
+ )
+ .destination_key()
+ );
+}
+
#[test]
fn subagent_transcript_keeps_cumulative_spend_separate_from_unknown_last_call() {
let workspace = tempfile::tempdir().unwrap();
+ let locator =
+ crate::agent::session_store::transcripts_or_files("orchestrator", workspace.path());
let usage = AggregatedUsage {
input_tokens: 120,
output_tokens: 30,
@@ -22,7 +84,7 @@ fn subagent_transcript_keeps_cumulative_spend_separate_from_unknown_last_call()
},
};
super::transcript::persist_subagent_transcript(
- workspace.path(),
+ locator.as_ref(),
"root__usage",
"worker",
"task",
@@ -35,10 +97,7 @@ fn subagent_transcript_keeps_cumulative_spend_separate_from_unknown_last_call()
"test",
2,
);
- let root = crate::agent::session_store::transcript_root(workspace.path());
- let path = tinyagents_session::transcript::resolve_keyed_transcript_path(&root, "root__usage")
- .unwrap();
- let transcript = tinyagents_session::transcript::read_transcript(&path).unwrap();
+ let transcript = read_stem(locator.as_ref(), "root__usage");
let recorded = &transcript
.messages
.last()
@@ -149,8 +208,11 @@ fn parallel_worker_without_thread_keeps_parent_transcript_affinity() {
#[tokio::test]
async fn explicit_worker_thread_replaces_parent_for_model_run_and_transcript() {
let workspace = tempfile::tempdir().expect("workspace");
+ let locator =
+ crate::agent::session_store::transcripts_or_files("orchestrator", workspace.path());
let mut parent = crate::agent::tinyagents::host::OpenHumanRunContext::new();
parent.thread_id = Some("parent-thread".to_owned());
+ parent.transcripts = Some(locator.clone());
let mut history = vec![TranscriptMessage::user("finish this")];
run_subagent_via_graph(
@@ -185,13 +247,7 @@ async fn explicit_worker_thread_replaces_parent_for_model_run_and_transcript() {
.await
.expect("worker run");
- let path = tinyagents_session::transcript::resolve_keyed_transcript_path(
- workspace.path(),
- "root__worker-thread",
- )
- .expect("transcript path");
- let persisted =
- tinyagents_session::transcript::read_transcript(&path).expect("worker transcript");
+ let persisted = read_stem(locator.as_ref(), "root__worker-thread");
assert_eq!(persisted.meta.thread_id.as_deref(), Some("worker-thread"));
assert_ne!(persisted.meta.thread_id.as_deref(), Some("parent-thread"));
}
diff --git a/crates/openhuman-core/src/agent/tinyagents/host/run_context.rs b/crates/openhuman-core/src/agent/tinyagents/host/run_context.rs
index b1b8df1577..302a55df45 100644
--- a/crates/openhuman-core/src/agent/tinyagents/host/run_context.rs
+++ b/crates/openhuman-core/src/agent/tinyagents/host/run_context.rs
@@ -312,6 +312,9 @@ pub struct OpenHumanRunContext {
/// The context the turn runs under, read by tools, middleware and the
/// provider factory instead of the ambient scope. Children inherit it.
pub core: Option<std::sync::Weak<crate::core::runtime::CoreContext>>,
+ /// The turn tree's transcript store (the root session's locator), where
+ /// sub-agent transcripts land under the parent's store key. Inherited.
+ pub transcripts: Option<Arc<dyn tinyagents_session::transcript::TranscriptLocator>>,
/// File-state identity used to detect stale parent reads after child writes.
pub file_state_agent_id: Option<String>,
/// Host-owned artifact index for tool-result references.
@@ -446,6 +449,7 @@ impl OpenHumanRunContext {
prepared_context_sources: Arc::new(Vec::new()),
memory_identity: None,
core: None,
+ transcripts: None,
file_state_agent_id: None,
tool_result_artifact_index: None,
attachment_placeholders: Arc::new(Vec::new()),
diff --git a/crates/openhuman-core/src/config/migrations/phase_out_profile_md.rs b/crates/openhuman-core/src/config/migrations/phase_out_profile_md.rs
index 59e40c1bce..a5eba3da77 100644
--- a/crates/openhuman-core/src/config/migrations/phase_out_profile_md.rs
+++ b/crates/openhuman-core/src/config/migrations/phase_out_profile_md.rs
@@ -21,9 +21,12 @@
//! date-grouped subdirs), reads each file, and — if the first
//! message is a system message containing a `### PROFILE.md`
//! heading — removes the heading and everything beneath it up to
-//! the next `### ` heading (or end-of-prompt). The transcript is
-//! rewritten in place via the same [`transcript::write_transcript`]
-//! used at runtime so the on-disk shape stays byte-compatible.
+//! the next `### ` heading (or end-of-prompt). The walk and the
+//! rewrite are TinyAgents' legacy maintenance
+//! (`tinyagents_session::legacy::rewrite_legacy_transcripts`), which
+//! owns the format, so the on-disk shape stays byte-compatible and this
+//! module names no transcript file. It runs before the workspace's
+//! one-time import into the session store.
//! 3. **Sweeps `.md` companions** under `{workspace}/sessions/**/*.md`,
//! rewriting in place any file whose body still contains a
//! `### PROFILE.md` heading. The rest of the transcript
@@ -46,10 +49,10 @@
//! migration short-circuits without scanning. The caller still bumps
//! `schema_version` so future launches don't re-check.
-use anyhow::{Context, Result};
+use anyhow::Result;
use std::fs;
use std::path::{Path, PathBuf};
-use tinyagents_session::transcript::{self, SessionTranscript};
+use tinyagents_session::transcript::SessionTranscript;
/// Line that opens a `PROFILE.md` block in a system prompt. Matches the
/// output of `inject_workspace_file_capped` in `agent/prompts/mod.rs`.
@@ -88,43 +91,24 @@ pub fn run(workspace_dir: &Path) -> Result<PhaseOutStats> {
// transcript walk so that a partial run still removes the file.
stats.profile_md_removed = remove_workspace_profile_md(workspace_dir, &mut stats);
- let raw_root = workspace_dir.join("session_raw");
- let transcripts = collect_jsonl_transcripts(&raw_root);
- if transcripts.is_empty() {
+ // The legacy JSONL transcripts are rewritten by TinyAgents' legacy
+ // maintenance walk, which owns that format and its layout (flat and
+ // `DDMMYYYY/` date-grouped). This runs before the boot-time import of
+ // the workspace, so what is imported is already clean.
+ let report = tinyagents_session::legacy::rewrite_legacy_transcripts(
+ workspace_dir,
+ strip_profile_md_in_first_system_message,
+ );
+ stats.scanned = report.scanned;
+ stats.cleaned = report.rewritten;
+ stats.skipped = report.unchanged;
+ stats.errors += report.errors;
+ if report.scanned == 0 {
log::info!(
- "[migration:phase-out-profile-md] no transcripts under {} — \
- continuing to .md sweep",
- raw_root.display()
+ "[migration:phase-out-profile-md] no legacy transcripts — continuing to .md sweep"
);
}
- for path in transcripts {
- stats.scanned += 1;
- match process_transcript(&path) {
- Ok(true) => {
- stats.cleaned += 1;
- log::info!(
- "[migration:phase-out-profile-md] cleaned path={}",
- path.display()
- );
- }
- Ok(false) => {
- stats.skipped += 1;
- log::debug!(
- "[migration:phase-out-profile-md] skipped (already clean) path={}",
- path.display()
- );
- }
- Err(err) => {
- stats.errors += 1;
- log::warn!(
- "[migration:phase-out-profile-md] failed path={}: {err:#}",
- path.display()
- );
- }
- }
- }
-
// Sweep stale `.md` companions and legacy-format transcripts that
// still carry a `### PROFILE.md` block. The JSONL above is the
// source of truth and was rewritten in-place where needed; these
@@ -158,10 +142,9 @@ pub fn run(workspace_dir: &Path) -> Result<PhaseOutStats> {
/// by [`tinyagents_session::transcript`]
/// (`sessions/YYYY_MM_DD/{stem}.md` for the new format, legacy
/// `sessions/DDMMYYYY/{stem}.md` for the date-grouped fallback). The
-/// JSONL walk in [`collect_jsonl_transcripts`] makes the same
-/// assumption. If a future change starts producing deeper nesting
-/// (e.g. `sessions/YYYY/MM/DD/`), both walkers will silently miss the
-/// inner files and this comment needs to be revisited.
+/// legacy JSONL walk makes the same assumption. If a future change starts
+/// producing deeper nesting (e.g. `sessions/YYYY/MM/DD/`), the walk will
+/// silently miss the inner files and this comment needs to be revisited.
///
/// Read/IO errors are folded into `stats.errors` and the walk continues.
fn sweep_tainted_md_companions(workspace_dir: &Path, stats: &mut PhaseOutStats) -> usize {
@@ -259,22 +242,6 @@ fn remove_workspace_profile_md(workspace_dir: &Path, stats: &mut PhaseOutStats)
}
}
-/// Process one transcript file. Returns `true` when the file was
-/// rewritten with a cleaned system prompt.
-fn process_transcript(path: &Path) -> Result<bool> {
- let mut session = transcript::read_transcript(path)
- .with_context(|| format!("read transcript {}", path.display()))?;
-
- if !strip_profile_md_in_first_system_message(&mut session) {
- return Ok(false);
- }
-
- transcript::write_transcript(path, &session.messages, &session.meta, None)
- .with_context(|| format!("rewrite cleaned transcript {}", path.display()))?;
-
- Ok(true)
-}
-
/// Strip a `### PROFILE.md` block from the first system message of a
/// transcript. Returns `true` when the message was mutated.
pub(super) fn strip_profile_md_in_first_system_message(session: &mut SessionTranscript) -> bool {
@@ -304,7 +271,7 @@ pub(super) fn strip_profile_md_in_first_system_message(session: &mut SessionTran
/// the new `.md` companion format ([`render_markdown`]).
/// - `## [` — the next-message header in a `.md` companion.
/// - `<!--/MSG-->` — the close tag in the legacy HTML-comment `.md`
-/// format read by [`transcript::read_transcript_legacy_md`].
+/// format read by `tinyagents_session::transcript::read_transcript_legacy_md`.
///
/// The extra boundaries make the same function safe to apply to either
/// a raw system-prompt string or a `.md` transcript body, without
@@ -367,40 +334,6 @@ fn is_block_boundary(line: &str) -> bool {
|| trimmed == "<!--/MSG-->"
}
-/// Collect every `*.jsonl` under `session_raw/` (flat) and its legacy
-/// `DDMMYYYY/` subdirectories. Returns empty when the root does not
-/// exist. Directory-iteration errors are swallowed — the migration
-/// should never abort startup on a single unreadable directory.
-fn collect_jsonl_transcripts(raw_root: &Path) -> Vec<PathBuf> {
- let mut paths = Vec::new();
- if !raw_root.is_dir() {
- return paths;
- }
- push_jsonl_in_dir(raw_root, &mut paths);
- if let Ok(entries) = fs::read_dir(raw_root) {
- for entry in entries.flatten() {
- let sub = entry.path();
- if sub.is_dir() {
- push_jsonl_in_dir(&sub, &mut paths);
- }
- }
- }
- paths.sort();
- paths
-}
-
-fn push_jsonl_in_dir(dir: &Path, out: &mut Vec<PathBuf>) {
- let Ok(entries) = fs::read_dir(dir) else {
- return;
- };
- for entry in entries.flatten() {
- let path = entry.path();
- if path.is_file() && path.extension().and_then(|s| s.to_str()) == Some("jsonl") {
- out.push(path);
- }
- }
-}
-
#[cfg(test)]
#[path = "phase_out_profile_md_tests.rs"]
mod tests;
diff --git a/crates/openhuman-core/src/config/migrations/phase_out_profile_md_tests.rs b/crates/openhuman-core/src/config/migrations/phase_out_profile_md_tests.rs
index dea7afd884..8dbe9aedeb 100644
--- a/crates/openhuman-core/src/config/migrations/phase_out_profile_md_tests.rs
+++ b/crates/openhuman-core/src/config/migrations/phase_out_profile_md_tests.rs
@@ -164,8 +164,11 @@ fn sanitize_only_touches_first_system_message() {
));
write_transcript(&path, &session.messages, &session.meta, None).unwrap();
- let mutated = process_transcript(&path).unwrap();
- assert!(mutated, "first system message had a block, must mutate");
+ let stats = run(dir.path()).unwrap();
+ assert_eq!(
+ stats.cleaned, 1,
+ "first system message had a block, must mutate"
+ );
let session = read_transcript(&path).unwrap();
assert!(!session.messages[0].content.contains("### PROFILE.md"));
diff --git a/crates/openhuman-core/src/cron/README.md b/crates/openhuman-core/src/cron/README.md
index 91fdc432f3..5977bc4eb6 100644
--- a/crates/openhuman-core/src/cron/README.md
+++ b/crates/openhuman-core/src/cron/README.md
@@ -155,8 +155,9 @@ nothing is sent and no alert is raised. For a web origin, the reply is stored in
the origin thread under `run_reply_message_id("cron:<job>:<run>")`, the
web-channel `proactive_message` event is emitted with that `thread_id` and
`request_id`, and `append_to_origin_transcript` appends it to the thread's agent
-transcript (idempotent on the same key, and it waits out a live turn on the
-session, up to 120 seconds). For a channel origin, the reply goes to the
+transcript in the session store, under the key the session host wrote it with
+(`agent_key_for` of the job's tenant and agent), idempotent on the same key, and
+it waits out a live turn on the session, up to 120 seconds. For a channel origin, the reply goes to the
origin's `reply_target` through `cron::channel_bridge` and is appended to that
chat's in-memory history.
diff --git a/crates/openhuman-core/src/cron/scheduler/origin_delivery.rs b/crates/openhuman-core/src/cron/scheduler/origin_delivery.rs
index 99b3d17a41..74e88021d0 100644
--- a/crates/openhuman-core/src/cron/scheduler/origin_delivery.rs
+++ b/crates/openhuman-core/src/cron/scheduler/origin_delivery.rs
@@ -42,6 +42,10 @@ pub(crate) struct TranscriptAppend<'a> {
/// The agent that owns the thread's session (its transcript is keyed by
/// thread id and agent id).
pub agent_id: &'a str,
+ /// The session store key the thread's transcripts were written under
+ /// ([`agent_key_for`](crate::agent::session_store::agent_key_for) of the
+ /// job's tenant and `agent_id`), resolved by the caller.
+ pub store_key: &'a str,
pub text: &'a str,
/// `cron:<job_id>:<run_id>`; the append is idempotent on it.
pub idempotency_key: &'a str,
@@ -57,29 +61,26 @@ const TRANSCRIPT_APPEND_TIMEOUT: std::time::Duration = std::time::Duration::from
/// model-facing `SessionRef` transcript) as an assistant message, so the next
/// live turn in that thread sees the reminder.
///
-/// Uses `tinyagents_session::transcript::append_background_message`: it waits
-/// for any live turn of the session (the per-session turn lock), dedupes on the
-/// idempotency key and records `{kind: "cron", job_id, run_id}` provenance.
-/// The session is addressed exactly as the session host does it
-/// (`SessionRef::scoped(thread_id, agent_id)` over the workspace path). A
-/// thread that never had an agent turn has no transcript (`NoSession`) and is
-/// skipped. Must never be called from inside a turn of the same session.
+/// Uses `tinyagents_session::transcript::append_background_message_in`: it
+/// waits for any live turn of the session (the per-session turn lock), dedupes
+/// on the idempotency key and records `{kind: "cron", job_id, run_id}`
+/// provenance. The session is addressed exactly as the session host does it
+/// (`SessionRef::scoped(thread_id, agent_id)`) in the store the host wrote it
+/// to: the transcript port for `append.store_key` (the installed session
+/// store, else the workspace's own). A thread that never had an agent turn has
+/// no transcript (`NoSession`) and is skipped. Must never be called from
+/// inside a turn of the same session.
pub(crate) async fn append_to_origin_transcript(
workspace_dir: &Path,
append: &TranscriptAppend<'_>,
) -> Result<(), String> {
use tinyagents_session::transcript::{
- append_background_message, BackgroundAppend, BackgroundAppendOutcome,
- FileTranscriptLocator, SessionRef, TranscriptMessage,
+ append_background_message_in, BackgroundAppend, BackgroundAppendOutcome, SessionRef,
+ TranscriptMessage,
};
let session = SessionRef::scoped(append.thread_id.to_string(), append.agent_id.to_string());
- if let Some(agent) = crate::agent::session_store::current_embedded_agent() {
- use tinyagents_session::transcript::TranscriptLocator;
- tinyagents_session::transcript::AgentTranscriptFiles::new(workspace_dir, &agent)
- .session_exists(&session);
- }
let locator =
- FileTranscriptLocator::new(crate::agent::session_store::transcript_root(workspace_dir));
+ crate::agent::session_store::transcripts_or_files(append.store_key, workspace_dir);
let options = BackgroundAppend::new(
append.idempotency_key,
serde_json::json!({
@@ -90,8 +91,8 @@ pub(crate) async fn append_to_origin_transcript(
);
let outcome = tokio::time::timeout(
TRANSCRIPT_APPEND_TIMEOUT,
- append_background_message(
- &locator,
+ append_background_message_in(
+ locator.as_ref(),
&session,
TranscriptMessage::assistant(append.text),
options,
@@ -152,9 +153,11 @@ pub(crate) async fn deliver_to_origin(
};
let text = output.trim();
- // A hosted profile's or an embedded agent's host routes the reply itself.
- let owner = crate::core::runtime::current_tenant()
- .ok()
+ // The job's tenant: a hosted profile's or an embedded agent's host routes
+ // the reply itself; otherwise it keys the transcript store below.
+ let tenant = crate::core::runtime::current_tenant().ok();
+ let owner = tenant
+ .clone()
.filter(|tenant| tenant.profile.is_some() || tenant.agent.is_some());
if let (Some(sink), Some(owner)) = (crate::cron::host_delivery::installed(), owner) {
let thread_id = match origin {
@@ -186,7 +189,18 @@ pub(crate) async fn deliver_to_origin(
JobOrigin::Web {
thread_id,
agent_id,
- } => deliver_to_web_thread(config, job, run_id, thread_id, agent_id.as_deref(), text).await,
+ } => {
+ deliver_to_web_thread(
+ config,
+ tenant.as_ref(),
+ job,
+ run_id,
+ thread_id,
+ agent_id.as_deref(),
+ text,
+ )
+ .await
+ }
JobOrigin::Channel {
channel,
reply_target,
@@ -218,6 +232,7 @@ pub(crate) async fn deliver_to_origin(
async fn deliver_to_web_thread(
config: &Config,
+ tenant: Option<&crate::core::runtime::Tenant>,
job: &CronJob,
run_id: &str,
thread_id: &str,
@@ -262,11 +277,23 @@ async fn deliver_to_web_thread(
// After the announcement: waiting out a live turn of this session must not
// delay the user seeing the reply (the thread row is already stored).
+ // A job with no tenant (SaaS work that lost its scope) has no store to
+ // append to and must not guess one.
+ let Some(tenant) = tenant else {
+ tracing::warn!(
+ job_id = %job.id,
+ run_id = %run_id,
+ "[cron] origin transcript append skipped: the job has no tenant"
+ );
+ return Ok(DeliveryStatus::Delivered);
+ };
+ let store_key = crate::agent::session_store::agent_key_for(tenant, &agent_id);
if let Err(e) = append_to_origin_transcript(
&config.workspace_dir,
&TranscriptAppend {
thread_id,
agent_id: &agent_id,
+ store_key: &store_key,
text,
idempotency_key: &request_id,
job_id: &job.id,
diff --git a/crates/openhuman-core/src/cron/scheduler/origin_delivery_tests.rs b/crates/openhuman-core/src/cron/scheduler/origin_delivery_tests.rs
index eafc253ee3..8a56a7ee06 100644
--- a/crates/openhuman-core/src/cron/scheduler/origin_delivery_tests.rs
+++ b/crates/openhuman-core/src/cron/scheduler/origin_delivery_tests.rs
@@ -1,8 +1,7 @@
use super::*;
use crate::threads::store::{self as conversations, CreateConversationThread};
use tinyagents_session::transcript::{
- read_transcript, resolve_keyed_transcript_path, session_stem, FileTranscriptLocator,
- SessionRef, TranscriptLocator, TranscriptMessage, TranscriptMeta, TranscriptTurn,
+ SessionRef, TranscriptMessage, TranscriptMeta, TranscriptTurn,
};
use {
tinyflows_schedule::types::DeliveryConfig, tinyflows_schedule::types::JobType,
@@ -183,8 +182,10 @@ async fn web_delivery_appends_to_the_resumed_agent_transcript() {
let cfg = config(&tmp);
seed_thread(&cfg, "t-1");
- // A prior live turn on the thread, written the way the session host does.
- let locator = FileTranscriptLocator::new(cfg.workspace_dir.clone());
+ // A prior live turn on the thread, written the way the session host does:
+ // through the store port, under the desktop tenant's key for the agent.
+ let locator =
+ crate::agent::session_store::transcripts_or_files("orchestrator", &cfg.workspace_dir);
let session = SessionRef::scoped("t-1", "orchestrator");
let next = vec![
TranscriptMessage::user("remind me to drink water"),
@@ -216,8 +217,12 @@ async fn web_delivery_appends_to_the_resumed_agent_transcript() {
.unwrap();
let head = locator.head_generation(&session);
- let path = resolve_keyed_transcript_path(&cfg.workspace_dir, &session_stem(&head)).unwrap();
- let resumed = read_transcript(&path).unwrap();
+ let resumed = locator
+ .read_session_transcript(&head)
+ .expect("the session's head is in the store")
+ .read_session()
+ .unwrap()
+ .unwrap();
assert_eq!(resumed.messages.len(), 3, "reply appended once");
let last = resumed.messages.last().unwrap();
assert_eq!(last.role, "assistant");
@@ -229,9 +234,10 @@ async fn web_delivery_appends_to_the_resumed_agent_transcript() {
async fn transcript_append_waits_for_a_live_turn() {
let tmp = tempfile::TempDir::new().unwrap();
let cfg = config(&tmp);
- let locator = FileTranscriptLocator::new(cfg.workspace_dir.clone());
+ let locator =
+ crate::agent::session_store::transcripts_or_files("orchestrator", &cfg.workspace_dir);
let session = SessionRef::scoped("t-1", "orchestrator");
- let guard = tinyagents_session::transcript::lock_session_turn(&locator, &session)
+ let guard = tinyagents_session::transcript::lock_session_turn(locator.as_ref(), &session)
.await
.expect("lock");
@@ -242,6 +248,7 @@ async fn transcript_append_waits_for_a_live_turn() {
&TranscriptAppend {
thread_id: "t-1",
agent_id: "orchestrator",
+ store_key: "orchestrator",
text: "hi",
idempotency_key: "cron:job-1:run-1",
job_id: "job-1",
@@ -255,3 +262,68 @@ async fn transcript_append_waits_for_a_live_turn() {
drop(guard);
task.await.unwrap().unwrap();
}
+
+/// The append lands in the store the caller's key names: a SaaS profile's
+/// `<profile>~<agent>` transcript, never the unprefixed one of the same
+/// workspace.
+#[tokio::test]
+async fn transcript_append_uses_the_store_key_it_is_given() {
+ let tmp = tempfile::TempDir::new().unwrap();
+ let cfg = config(&tmp);
+ let tenant = crate::core::runtime::Tenant {
+ profile: Some("profile-a".into()),
+ agent: None,
+ };
+ let key = crate::agent::session_store::agent_key_for(&tenant, "orchestrator");
+ assert_eq!(key, "profile-a~default");
+ let locator = crate::agent::session_store::transcripts_or_files(&key, &cfg.workspace_dir);
+ let session = SessionRef::scoped("t-p", "orchestrator");
+ let next = vec![
+ TranscriptMessage::user("remind me"),
+ TranscriptMessage::assistant("Scheduled."),
+ ];
+ locator
+ .open_session(&session, meta())
+ .unwrap()
+ .append_turn(TranscriptTurn {
+ prev: &[],
+ next: &next,
+ meta: &meta(),
+ turn_usage: None,
+ request_id: None,
+ tools: None,
+ })
+ .unwrap();
+
+ let append = |store_key: &'static str| TranscriptAppend {
+ thread_id: "t-p",
+ agent_id: "orchestrator",
+ store_key,
+ text: "Ping!",
+ idempotency_key: "cron:job-p:run-1",
+ job_id: "job-p",
+ run_id: "run-1",
+ };
+ // The unprefixed key has no such session: nothing is written anywhere.
+ append_to_origin_transcript(&cfg.workspace_dir, &append("orchestrator"))
+ .await
+ .unwrap();
+ append_to_origin_transcript(&cfg.workspace_dir, &append("profile-a~default"))
+ .await
+ .unwrap();
+
+ let head = locator.head_generation(&session);
+ let messages = locator
+ .read_session_transcript(&head)
+ .unwrap()
+ .read_session()
+ .unwrap()
+ .unwrap()
+ .messages;
+ assert_eq!(
+ messages.len(),
+ 3,
+ "appended once, to the profile's transcript"
+ );
+ assert_eq!(messages.last().unwrap().content, "Ping!");
+}
diff --git a/crates/openhuman-core/src/threads/README.md b/crates/openhuman-core/src/threads/README.md
index 083c981583..35c65c961a 100644
--- a/crates/openhuman-core/src/threads/README.md
+++ b/crates/openhuman-core/src/threads/README.md
@@ -26,13 +26,17 @@ A thread has three separate records on disk, all under the workspace:
threads/<hex(thread_id)>.jsonl the thread's message log (what the UI lists)
turn_states/<hex(thread)>/<hex(request)>.json
snapshot of one turn's progress
-<workspace>/session_raw/*.jsonl model-facing transcript (agent session host)
+session store (agent::session_store) model-facing transcript (agent session host)
```
The message log is the user-facing history: one row per user message and
agent reply, which `threads.messages_list` returns. The transcript is what
-the model sees, written by the agent session host, and is the source for
-`threads.transcript_get` and `threads.token_usage`. The turn-state snapshots
+the model sees, written by the agent session host through the session store
+port, and is the source for `threads.transcript_get` and `threads.token_usage`.
+Every transcript read here goes through that port under the key the session
+host wrote with: `ops::support::transcript_store(ctx)` resolves it from the
+request's own context (`<profile>~<agent>` for a SaaS profile, else the
+context's agent, else the chat agent id), never from ambient state. The turn-state snapshots
record what a turn was doing (phase, tool timeline, streamed text) so a client
that reloads mid-turn, or after a restart, can rebuild the process view.
@@ -164,12 +168,12 @@ label from threads and renames `welcome*` session transcripts to
| [`ops/title_generation.rs`](./ops/title_generation.rs) | Model-generated titles and the replaceable-title rule. |
| [`ops/working_dir.rs`](./ops/working_dir.rs) | Validating and binding a thread's working folder. |
| [`ops/search.rs`](./ops/search.rs) | `threads.search`: cross-thread search with snippets for the global `Cmd`/`Ctrl+K` search. |
-| [`ops/transcript.rs`](./ops/transcript.rs) | `threads.transcript_get`: paginated display items from `tinyagents_session::transcript::view`. |
-| [`ops/usage.rs`](./ops/usage.rs) | `threads.token_usage`: token and cost totals from `transcript::spend::thread_spend`, re-priced, with per-sub-agent rows and the last turn's tokens for the context gauge. |
+| [`ops/transcript.rs`](./ops/transcript.rs) | `threads.transcript_get`: paginated display items from `tinyagents_session::transcript::view::get_page_in` over the request's transcript store. |
+| [`ops/usage.rs`](./ops/usage.rs) | `threads.token_usage`: token and cost totals from `transcript::spend::thread_spend_in` over the request's transcript store, re-priced, with per-sub-agent rows and the last turn's tokens for the context gauge. |
| [`ops/live_state.rs`](./ops/live_state.rs) | `threads.goal_get` and `threads.todos_get`: one-shot reads of the thread's agent goal and todo list for hydration on load. |
| [`ops/turn_state_ops.rs`](./ops/turn_state_ops.rs) | `threads.turn_state_*` over the snapshot store. |
| [`ops/purge.rs`](./ops/purge.rs) | Workspace-wide purge. |
-| [`ops/support.rs`](./ops/support.rs) | Envelopes, workspace resolution, `run_to_completion`, type conversions, fallback titles. |
+| [`ops/support.rs`](./ops/support.rs) | Envelopes, workspace and transcript-store resolution (`transcript_store`), `run_to_completion`, type conversions, fallback titles. |
| [`schemas/`](./schemas/) | `schema_defs.rs` (controller schemas), `handlers.rs` (param parsing, thin handlers), `registry.rs` (the controller list). |
| [`store/`](./store/) | Re-export of `tinyagents_session::threads`, the `blocking` wrappers and the channel bus subscriber. See [store/README.md](store/README.md). |
| [`turn_state/`](./turn_state/) | `mirror/observe.rs` (progress projection) and `rpc_types.rs` (turn-state RPC payloads). |
diff --git a/crates/openhuman-core/src/threads/ops/edit.rs b/crates/openhuman-core/src/threads/ops/edit.rs
index 5b507341ce..1736d6162b 100644
--- a/crates/openhuman-core/src/threads/ops/edit.rs
+++ b/crates/openhuman-core/src/threads/ops/edit.rs
@@ -42,15 +42,15 @@ use serde::{Deserialize, Serialize};
use serde_json::{json, Value};
use tinyagents_session::transcript::{
- SessionRef, SessionTranscript, TranscriptLocator, TranscriptMessage,
- TranscriptMeta, TruncateCut,
+ SessionRef, SessionTranscript, TranscriptLocator, TranscriptMessage, TranscriptMeta,
+ TruncateCut,
};
use crate::core::Outcome;
use crate::threads::store::{self as conversations, reply_run_id, run_reply_message_id};
use crate::threads::ThreadsError;
-use super::support::workspace_dir;
+use super::support::{transcript_store, workspace_dir, TranscriptStore};
#[derive(Debug, Clone, Deserialize)]
#[serde(deny_unknown_fields)]
@@ -87,7 +87,9 @@ pub async fn edit_message(
let client_id = request.client_id.unwrap_or_else(|| "system".to_string());
let thread_id = request.thread_id;
let dir = workspace_dir().await.map_err(ThreadsError::Message)?;
- let store_key = transcript_store_key().await;
+ // The request's own tenant picks the store key, so a SaaS profile edits
+ // the transcript its turns were written to.
+ let store = transcript_store(ctx).await.map_err(ThreadsError::Message)?;
crate::web_chat::cancel_chat_scoped(&client_id, &thread_id, None)
.await
@@ -101,17 +103,11 @@ pub async fn edit_message(
.map_err(ThreadsError::Message)?;
if let Some(cut_request_id) = &cut_request_id {
- let dir_for_blocking = dir.clone();
- let store_key_owned = store_key.clone();
+ let store_owned = store.clone();
let thread_id_owned = thread_id.clone();
let cut_request_id_owned = cut_request_id.clone();
- tokio::task::spawn_blocking(move || {
- truncate_transcript_before_turn(
- &dir_for_blocking,
- &store_key_owned,
- &thread_id_owned,
- &cut_request_id_owned,
- )
+ crate::core::runtime::spawn_blocking_scoped(move || {
+ truncate_transcript_before_turn(&store_owned, &thread_id_owned, &cut_request_id_owned)
})
.await
.map_err(|e| ThreadsError::Message(format!("truncate transcript task: {e}")))?
@@ -158,7 +154,9 @@ pub async fn regenerate(
let client_id = request.client_id.unwrap_or_else(|| "system".to_string());
let thread_id = request.thread_id;
let dir = workspace_dir().await.map_err(ThreadsError::Message)?;
- let store_key = transcript_store_key().await;
+ // The request's own tenant picks the store key, so a SaaS profile edits
+ // the transcript its turns were written to.
+ let store = transcript_store(ctx).await.map_err(ThreadsError::Message)?;
crate::web_chat::cancel_chat_scoped(&client_id, &thread_id, None)
.await
@@ -175,14 +173,12 @@ pub async fn regenerate(
None => None,
};
- let dir_for_blocking = dir.clone();
- let store_key_for_blocking = store_key.clone();
+ let store_for_blocking = store.clone();
let thread_id_for_blocking = thread_id.clone();
let target_for_blocking = target_request_id.clone();
- let (prompt, cut_request_id) = tokio::task::spawn_blocking(move || {
+ let (prompt, cut_request_id) = crate::core::runtime::spawn_blocking_scoped(move || {
truncate_transcript_for_regenerate(
- &dir_for_blocking,
- &store_key_for_blocking,
+ &store_for_blocking,
&thread_id_for_blocking,
target_for_blocking.as_deref(),
)
@@ -240,39 +236,21 @@ async fn next_reply_request_id_after(
.find_map(|m| reply_run_id(&m.id).map(str::to_string)))
}
-/// Resolve the head generation of `thread_id`'s session transcript: the
-/// `SessionRef`, its locator, and its current content.
+/// Resolve the head generation of `thread_id`'s session transcript in
+/// `store`: the `SessionRef`, its locator, and its current content.
///
-/// `find_root_transcript_for_thread` locates *some* root file for the thread
-/// (used only to recover the `agent_id` a fresh [`SessionRef::scoped`]
-/// needs); the actual head — walking any compaction/edit generations already
-/// on disk — is then resolved through the locator itself
-/// (`TranscriptLocator::head_generation`), never by trusting file-name sort
-/// order (`tinyagents_session::transcript::view`'s resolver module doc explains why that
-/// is unsafe: `.g1` sorts before the un-suffixed root).
+/// The thread's newest root (`TranscriptLocator::root_for_thread`) only
+/// recovers the `agent_id` a fresh [`SessionRef::scoped`] needs; the actual
+/// head — walking any compaction/edit generations already written — is then
+/// resolved through the locator itself (`TranscriptLocator::head_generation`).
fn resolve_head_transcript(
- workspace_dir: &std::path::Path,
- store_key: &str,
+ store: &TranscriptStore,
thread_id: &str,
) -> Result<HeadTranscript, String> {
- find_head_transcript(workspace_dir, store_key, thread_id)?
+ find_head_transcript(store, thread_id)?
.ok_or_else(|| format!("thread {thread_id} has no session transcript"))
}
-/// The key the thread's session transcripts are stored under: the configured
-/// chat agent's id, derived from the config alone. It deliberately reads no
-/// ambient tenant or context (those accessors are being removed); the key is
-/// passed down explicitly to every helper below.
-async fn transcript_store_key() -> String {
- match crate::config::Config::load_or_init().await {
- Ok(config) => crate::web_chat::pick_target_agent_id(&config),
- Err(error) => {
- log::warn!("[threads][edit] config unavailable for the chat agent id: {error}");
- "orchestrator".to_string()
- }
- }
-}
-
type HeadTranscript = (
SessionRef,
std::sync::Arc<dyn TranscriptLocator>,
@@ -282,14 +260,13 @@ type HeadTranscript = (
/// [`resolve_head_transcript`], answering `Ok(None)` when the thread has never
/// written a session transcript. Read and resolve failures still error.
fn find_head_transcript(
- workspace_dir: &std::path::Path,
- store_key: &str,
+ store: &TranscriptStore,
thread_id: &str,
) -> Result<Option<HeadTranscript>, String> {
// The same store the session host writes the thread's turns to: the
- // installed provider, else the workspace's driver-backed store. No
- // transcript file is named here.
- let locator = crate::agent::session_store::transcripts_or_files(store_key, workspace_dir);
+ // installed provider, else the workspace's driver-backed store, under the
+ // key the caller resolved from the request. No transcript file is named.
+ let locator = store.locator();
let Some(root) = locator.root_for_thread(thread_id) else {
log::debug!("[threads][edit] thread {thread_id} has no session transcript");
return Ok(None);
@@ -331,12 +308,11 @@ fn truncation_seed(head: &SessionRef, current: &TranscriptMeta) -> TranscriptMet
/// everything after — backs `edit_message`'s correlation-through-next-reply
/// path.
fn truncate_transcript_before_turn(
- workspace_dir: &std::path::Path,
- store_key: &str,
+ store: &TranscriptStore,
thread_id: &str,
request_id: &str,
) -> Result<(), String> {
- let (head, locator, transcript) = resolve_head_transcript(workspace_dir, store_key, thread_id)?;
+ let (head, locator, transcript) = resolve_head_transcript(store, thread_id)?;
let cut_index = transcript
.messages
.iter()
@@ -356,14 +332,13 @@ fn truncate_transcript_before_turn(
/// dropped turn's `request_id`, or `Ok(None)` when the thread has no turn to
/// regenerate (no transcript yet, or an empty one).
fn truncate_transcript_for_regenerate(
- workspace_dir: &std::path::Path,
- store_key: &str,
+ store: &TranscriptStore,
thread_id: &str,
target_request_id: Option<&str>,
) -> Result<Option<(String, String)>, String> {
// Sentry TAURI-REACT-AK: a thread that never wrote a transcript has no turn
// to regenerate — the caller turns `None` into that friendly error.
- let Some((head, locator, transcript)) = find_head_transcript(workspace_dir, store_key, thread_id)? else {
+ let Some((head, locator, transcript)) = find_head_transcript(store, thread_id)? else {
return Ok(None);
};
let cut = match target_request_id {
diff --git a/crates/openhuman-core/src/threads/ops/edit_tests.rs b/crates/openhuman-core/src/threads/ops/edit_tests.rs
index c48fadda99..c0ef3c4782 100644
--- a/crates/openhuman-core/src/threads/ops/edit_tests.rs
+++ b/crates/openhuman-core/src/threads/ops/edit_tests.rs
@@ -1,25 +1,30 @@
//! Transcript-level tests for `threads::ops::edit`'s private truncation
//! helpers (`truncate_transcript_before_turn`, `truncate_transcript_for_regenerate`).
//!
-//! Every fixture is written with the session crate's own writer
-//! (`append_transcript_turn`), never hand-rolled JSONL, so a wire-format
-//! change upstream surfaces here as a failure instead of silently diverging
-//! from what the core actually persists. See `edit_turn_state_tests.rs` for
-//! `clear_dropped_turn_states` / `next_reply_request_id_after`, which need
-//! different fixtures (turn-state snapshots, the message-log store) and are
-//! split out to keep both files well under the layout line limit.
+//! Every fixture is written through the transcript port the session host
+//! writes through (`TranscriptStore::locator` -> `open_session` +
+//! `append_turn`), never through a file path, so the helpers are exercised
+//! against exactly the store and key a real turn lands in. See
+//! `edit_turn_state_tests.rs` for `clear_dropped_turn_states` /
+//! `next_reply_request_id_after`, which need different fixtures (turn-state
+//! snapshots, the message-log store).
use super::*;
-use std::path::{Path, PathBuf};
+use std::path::Path;
use tempfile::TempDir;
-use tinyagents_session::transcript::{
- append_transcript_turn, resolve_keyed_transcript_path, session_stem, MessageUsage, TurnUsage,
-};
+use tinyagents_session::transcript::{MessageUsage, TranscriptTurn, TurnUsage};
const AGENT_ID: &str = "test-agent";
-/// The store key the fixtures' legacy JSONL is imported under.
+/// The store key a desktop turn of the default chat agent is written under.
const STORE_KEY: &str = "orchestrator";
+fn store(workspace: &Path) -> TranscriptStore {
+ TranscriptStore {
+ workspace_dir: workspace.to_path_buf(),
+ key: STORE_KEY.to_string(),
+ }
+}
+
fn base_meta(agent_id: &str, thread_id: &str) -> TranscriptMeta {
TranscriptMeta {
agent_name: agent_id.to_string(),
@@ -62,16 +67,17 @@ fn turn_usage() -> TurnUsage {
}
}
-/// Write a two-turn root transcript for `thread_id`/`AGENT_ID` using the same
-/// writer the runtime uses (`append_transcript_turn`), and return the file
-/// path plus the two turns' `request_id`s.
-fn write_two_turn_transcript(workspace: &Path, thread_id: &str) -> (PathBuf, String, String) {
+/// Write a two-turn root transcript for `thread_id`/`AGENT_ID` into `store`
+/// the way the session host does, and return the two turns' `request_id`s.
+fn write_two_turn_transcript(store: &TranscriptStore, thread_id: &str) -> (String, String) {
let session = SessionRef::scoped(thread_id, AGENT_ID);
- let path = resolve_keyed_transcript_path(workspace, &session_stem(&session))
- .expect("resolve fixture transcript path");
+ let meta = base_meta(AGENT_ID, thread_id);
+ let history = store
+ .locator()
+ .open_session(&session, meta.clone())
+ .expect("open fixture session");
let req1 = "turn-1".to_string();
let req2 = "turn-2".to_string();
- let meta = base_meta(AGENT_ID, thread_id);
let turn1 = vec![
TranscriptMessage::new("user", "user prompt 1"),
@@ -79,66 +85,85 @@ fn write_two_turn_transcript(workspace: &Path, thread_id: &str) -> (PathBuf, Str
];
let mut turn1_meta = meta.clone();
turn1_meta.turn_count = 1;
- append_transcript_turn(
- &path,
- &[],
- &turn1,
- &turn1_meta,
- Some(&turn_usage()),
- Some(&req1),
- )
- .expect("append turn 1");
+ history
+ .append_turn(TranscriptTurn {
+ prev: &[],
+ next: &turn1,
+ meta: &turn1_meta,
+ turn_usage: Some(&turn_usage()),
+ request_id: Some(&req1),
+ tools: None,
+ })
+ .expect("append turn 1");
let mut turn2 = turn1.clone();
turn2.push(TranscriptMessage::new("user", "user prompt 2"));
turn2.push(TranscriptMessage::assistant("answer 2"));
- let mut turn2_meta = meta.clone();
+ let mut turn2_meta = meta;
turn2_meta.turn_count = 2;
- append_transcript_turn(
- &path,
- &turn1,
- &turn2,
- &turn2_meta,
- Some(&turn_usage()),
- Some(&req2),
- )
- .expect("append turn 2");
+ history
+ .append_turn(TranscriptTurn {
+ prev: &turn1,
+ next: &turn2,
+ meta: &turn2_meta,
+ turn_usage: Some(&turn_usage()),
+ request_id: Some(&req2),
+ tools: None,
+ })
+ .expect("append turn 2");
- (path, req1, req2)
+ (req1, req2)
}
/// A root transcript with a single system row and no user/assistant turn at
/// all — feeds the "nothing to regenerate" `Ok(None)` case.
-fn write_turnless_transcript(workspace: &Path, thread_id: &str) -> PathBuf {
+fn write_turnless_transcript(store: &TranscriptStore, thread_id: &str) {
let session = SessionRef::scoped(thread_id, AGENT_ID);
- let path = resolve_keyed_transcript_path(workspace, &session_stem(&session))
- .expect("resolve fixture transcript path");
let meta = base_meta(AGENT_ID, thread_id);
let messages = vec![TranscriptMessage::new("system", "boot preamble")];
- append_transcript_turn(&path, &[], &messages, &meta, None, None).expect("append system row");
- path
+ store
+ .locator()
+ .open_session(&session, meta.clone())
+ .expect("open fixture session")
+ .append_turn(TranscriptTurn {
+ prev: &[],
+ next: &messages,
+ meta: &meta,
+ turn_usage: None,
+ request_id: None,
+ tools: None,
+ })
+ .expect("append system row");
+}
+
+/// The first (sealed) generation of the thread's session, read back through
+/// the store: a fork never erases it.
+fn sealed_generation(store: &TranscriptStore, thread_id: &str) -> Vec<TranscriptMessage> {
+ store
+ .locator()
+ .read_session_transcript(&SessionRef::scoped(thread_id, AGENT_ID))
+ .expect("sealed generation stays in the store")
+ .read_session()
+ .expect("read sealed")
+ .expect("sealed transcript exists")
+ .messages
}
#[test]
-fn truncate_transcript_before_turn_cuts_head_and_seals_original_untouched() {
+fn truncate_transcript_before_turn_cuts_head_and_keeps_the_sealed_generation() {
let dir = TempDir::new().expect("tempdir");
+ let store = store(dir.path());
let thread_id = "thread-before-turn";
- let (path, req1, req2) = write_two_turn_transcript(dir.path(), thread_id);
-
- let original_bytes = std::fs::read(&path).expect("read original transcript");
+ let (req1, req2) = write_two_turn_transcript(&store, thread_id);
- truncate_transcript_before_turn(dir.path(), STORE_KEY, thread_id, &req2).expect("truncate");
+ truncate_transcript_before_turn(&store, thread_id, &req2).expect("truncate");
- // Sealed generation preserved byte-for-byte: "a compaction never
- // erases" applies identically to this edit-driven fork.
- let bytes_after = std::fs::read(&path).expect("re-read original transcript");
+ // Head truncated: the new head ends right before turn 2's first row.
+ let (head_ref, _, head) = resolve_head_transcript(&store, thread_id).expect("resolve head");
assert_eq!(
- original_bytes, bytes_after,
- "sealed generation must stay byte-for-byte untouched"
+ head_ref.generation, 1,
+ "the fork opened the next generation"
);
-
- // Head truncated: the new head ends right before turn 2's first row.
- let (_, _, head) = resolve_head_transcript(dir.path(), STORE_KEY, thread_id).expect("resolve head");
assert!(
head.messages
.iter()
@@ -147,33 +172,27 @@ fn truncate_transcript_before_turn_cuts_head_and_seals_original_untouched() {
head.messages
);
let last = head.messages.last().expect("head keeps turn 1");
- // The sealed generation is still readable through the store port, with
- // both turns, even though the model now reads only the new head.
- let locator = crate::agent::session_store::transcripts_or_files(STORE_KEY, dir.path());
- let sealed = locator
- .read_session_transcript(&SessionRef::scoped(thread_id, AGENT_ID))
- .expect("sealed generation stays in the store")
- .read_session()
- .expect("read sealed")
- .expect("sealed transcript exists");
+ assert_eq!(last.request_id.as_deref(), Some(req1.as_str()));
+ assert_eq!(last.content, "answer 1", "turn 1's answer is kept intact");
+
+ // "A compaction never erases" applies identically to this edit-driven
+ // fork: the sealed generation still holds both turns.
assert!(
- sealed
- .messages
+ sealed_generation(&store, thread_id)
.iter()
.any(|m| m.request_id.as_deref() == Some(req2.as_str())),
"the sealed generation keeps the dropped turn"
);
- assert_eq!(last.request_id.as_deref(), Some(req1.as_str()));
- assert_eq!(last.content, "answer 1", "turn 1's answer is kept intact");
}
#[test]
fn truncate_transcript_before_turn_errs_when_turn_not_found() {
let dir = TempDir::new().expect("tempdir");
+ let store = store(dir.path());
let thread_id = "thread-missing-turn";
- write_two_turn_transcript(dir.path(), thread_id);
+ write_two_turn_transcript(&store, thread_id);
- let err = truncate_transcript_before_turn(dir.path(), STORE_KEY, thread_id, "no-such-turn")
+ let err = truncate_transcript_before_turn(&store, thread_id, "no-such-turn")
.expect_err("unknown request_id must fail");
assert!(
err.contains("no-such-turn"),
@@ -181,27 +200,28 @@ fn truncate_transcript_before_turn_errs_when_turn_not_found() {
);
}
+#[test]
+fn truncate_transcript_before_turn_errs_when_thread_has_no_transcript() {
+ let dir = TempDir::new().expect("tempdir");
+ let err = truncate_transcript_before_turn(&store(dir.path()), "thread-none", "turn-1")
+ .expect_err("a thread with no transcript has nothing to cut");
+ assert!(err.contains("has no session transcript"), "{err}");
+}
+
#[test]
fn truncate_transcript_for_regenerate_targets_specific_turn() {
let dir = TempDir::new().expect("tempdir");
+ let store = store(dir.path());
let thread_id = "thread-regen-target";
- let (path, req1, req2) = write_two_turn_transcript(dir.path(), thread_id);
- let original_bytes = std::fs::read(&path).expect("read original transcript");
+ let (_req1, req2) = write_two_turn_transcript(&store, thread_id);
- let (prompt, request_id) =
- truncate_transcript_for_regenerate(dir.path(), STORE_KEY, thread_id, Some(&req2))
- .expect("truncate")
- .expect("a turn to regenerate");
+ let (prompt, request_id) = truncate_transcript_for_regenerate(&store, thread_id, Some(&req2))
+ .expect("truncate")
+ .expect("a turn to regenerate");
assert_eq!(prompt, "user prompt 2");
assert_eq!(request_id, req2);
- let bytes_after = std::fs::read(&path).expect("re-read original transcript");
- assert_eq!(
- original_bytes, bytes_after,
- "sealed generation must stay byte-for-byte untouched"
- );
-
- let (_, _, head) = resolve_head_transcript(dir.path(), STORE_KEY, thread_id).expect("resolve head");
+ let (_, _, head) = resolve_head_transcript(&store, thread_id).expect("resolve head");
let last = head.messages.last().expect("head keeps turn 2's prompt");
assert_eq!(last.role, "user");
assert_eq!(last.content, "user prompt 2");
@@ -210,16 +230,22 @@ fn truncate_transcript_for_regenerate_targets_specific_turn() {
"turn 2's answer must be dropped: {:?}",
head.messages
);
- let _ = req1;
+ assert!(
+ sealed_generation(&store, thread_id)
+ .iter()
+ .any(|m| m.content == "answer 2"),
+ "the sealed generation keeps the dropped answer"
+ );
}
#[test]
fn truncate_transcript_for_regenerate_none_resolves_last_turn() {
let dir = TempDir::new().expect("tempdir");
+ let store = store(dir.path());
let thread_id = "thread-regen-last";
- let (_, _req1, req2) = write_two_turn_transcript(dir.path(), thread_id);
+ let (_req1, req2) = write_two_turn_transcript(&store, thread_id);
- let (prompt, request_id) = truncate_transcript_for_regenerate(dir.path(), STORE_KEY, thread_id, None)
+ let (prompt, request_id) = truncate_transcript_for_regenerate(&store, thread_id, None)
.expect("truncate")
.expect("a turn to regenerate");
@@ -230,10 +256,11 @@ fn truncate_transcript_for_regenerate_none_resolves_last_turn() {
#[test]
fn truncate_transcript_for_regenerate_returns_none_when_no_turn_exists() {
let dir = TempDir::new().expect("tempdir");
+ let store = store(dir.path());
let thread_id = "thread-no-turns";
- write_turnless_transcript(dir.path(), thread_id);
+ write_turnless_transcript(&store, thread_id);
- let result = truncate_transcript_for_regenerate(dir.path(), STORE_KEY, thread_id, None).expect("truncate");
+ let result = truncate_transcript_for_regenerate(&store, thread_id, None).expect("truncate");
assert_eq!(result, None, "no user/assistant turn to regenerate");
}
@@ -244,7 +271,110 @@ fn truncate_transcript_for_regenerate_returns_none_when_no_turn_exists() {
fn truncate_transcript_for_regenerate_returns_none_when_thread_has_no_transcript() {
let dir = TempDir::new().expect("tempdir");
- let result = truncate_transcript_for_regenerate(dir.path(), STORE_KEY, "thread-without-transcript", None)
- .expect("a thread with no transcript has no turn to regenerate, not an error");
+ let result =
+ truncate_transcript_for_regenerate(&store(dir.path()), "thread-without-transcript", None)
+ .expect("a thread with no transcript has no turn to regenerate, not an error");
assert_eq!(result, None);
}
+
+/// A SaaS profile's turns are written under `<profile>~<agent>`. The edit
+/// path resolves its key from the request's tenant (not the config alone),
+/// so it finds and forks that same transcript, and the unprefixed key of the
+/// same workspace never sees it.
+#[test]
+fn a_profile_prefixed_key_round_trips_through_edit_and_regenerate() {
+ let dir = TempDir::new().expect("tempdir");
+ let mut config = crate::config::Config::default();
+ config.workspace_dir = dir.path().to_path_buf();
+ let tenant = crate::core::runtime::Tenant {
+ profile: Some("profile-a".to_string()),
+ agent: None,
+ };
+
+ // What the session host writes under: the ambient-tenant resolution, fed
+ // the same tenant the request carries.
+ let writer_key = crate::agent::session_store::agent_key_for(
+ &tenant,
+ &crate::web_chat::pick_target_agent_id(&config),
+ );
+ let store = super::super::support::transcript_store_for(&config, &tenant);
+ assert_eq!(
+ store.key, writer_key,
+ "the reader resolves the writer's key"
+ );
+ assert_eq!(
+ store.key, "profile-a~default",
+ "the key keeps the profile prefix"
+ );
+ assert_eq!(store.workspace_dir, dir.path());
+
+ let thread_id = "thread-profile";
+ let (req1, req2) = write_two_turn_transcript(&store, thread_id);
+
+ let unprefixed = TranscriptStore {
+ workspace_dir: dir.path().to_path_buf(),
+ key: crate::web_chat::pick_target_agent_id(&config),
+ };
+ assert_eq!(
+ truncate_transcript_for_regenerate(&unprefixed, thread_id, None).expect("lookup"),
+ None,
+ "the config-only key does not see the profile's transcript"
+ );
+
+ truncate_transcript_before_turn(&store, thread_id, &req2).expect("edit forks the transcript");
+ let (_, _, head) = resolve_head_transcript(&store, thread_id).expect("resolve head");
+ assert_eq!(
+ head.messages.last().and_then(|m| m.request_id.as_deref()),
+ Some(req1.as_str()),
+ "the edit cut the profile's own transcript"
+ );
+
+ let (prompt, request_id) = truncate_transcript_for_regenerate(&store, thread_id, None)
+ .expect("regenerate")
+ .expect("turn 1 is left to regenerate");
+ assert_eq!(prompt, "user prompt 1");
+ assert_eq!(request_id, req1);
+}
+
+#[test]
+fn transcript_store_for_a_desktop_tenant_uses_the_chat_agent_and_an_embedded_agent_its_own() {
+ let dir = TempDir::new().expect("tempdir");
+ let mut config = crate::config::Config::default();
+ config.workspace_dir = dir.path().to_path_buf();
+
+ let desktop = super::super::support::transcript_store_for(
+ &config,
+ &crate::core::runtime::Tenant::default(),
+ );
+ assert_eq!(desktop.key, crate::web_chat::pick_target_agent_id(&config));
+
+ let embedded = super::super::support::transcript_store_for(
+ &config,
+ &crate::core::runtime::Tenant {
+ profile: None,
+ agent: Some("agent-7".to_string()),
+ },
+ );
+ assert_eq!(embedded.key, "agent-7");
+}
+
+/// The handler-level resolution: the key comes from the request's own
+/// `DispatchCtx` (its profile), with no ambient context in scope.
+#[tokio::test]
+async fn transcript_store_reads_the_profile_from_the_request_context() {
+ use crate::core::runtime::{ContextOverlay, CoreContext, DispatchCtx, DomainSet};
+ let dir = TempDir::new().expect("tempdir");
+ let mut config = crate::config::Config::default();
+ config.workspace_dir = dir.path().to_path_buf();
+ let overlay = ContextOverlay::new(
+ config,
+ DomainSet::kernel(),
+ crate::tools::toolpacks::ToolGroups::none(),
+ )
+ .profile("profile-b");
+ let ctx = DispatchCtx::new(CoreContext::for_test(DomainSet::full(), None).derive_with(overlay));
+
+ let store = transcript_store(&ctx).await.expect("resolve the store");
+ assert_eq!(store.key, "profile-b~default");
+ assert_eq!(store.workspace_dir, dir.path());
+}
diff --git a/crates/openhuman-core/src/threads/ops/support.rs b/crates/openhuman-core/src/threads/ops/support.rs
index 931ba66b4c..13d1a1f77a 100644
--- a/crates/openhuman-core/src/threads/ops/support.rs
+++ b/crates/openhuman-core/src/threads/ops/support.rs
@@ -21,6 +21,69 @@ pub(super) async fn workspace_dir() -> Result<PathBuf, String> {
.map_err(|e| format!("load config: {e}"))
}
+/// Where a thread's session transcripts live for one request: the workspace
+/// and the agent key the session host stored them under.
+#[derive(Debug, Clone, PartialEq, Eq)]
+pub(crate) struct TranscriptStore {
+ pub workspace_dir: PathBuf,
+ /// The store key ([`agent_key_for`](crate::agent::session_store::agent_key_for)):
+ /// `<profile>~<agent>` for a SaaS profile, else the agent, else the chat agent id.
+ pub key: String,
+}
+
+impl TranscriptStore {
+ /// The transcript port for this key: the installed session store, else
+ /// the workspace's own store.
+ pub(crate) fn locator(
+ &self,
+ ) -> std::sync::Arc<dyn tinyagents_session::transcript::TranscriptLocator> {
+ crate::agent::session_store::transcripts_or_files(&self.key, &self.workspace_dir)
+ }
+}
+
+/// The transcript store of the request `ctx` carries, resolved exactly as the
+/// session host resolved it when it wrote the thread: the config's chat agent
+/// as the fallback id, and the request's own tenant (never the ambient one),
+/// so a SaaS profile's key keeps its profile prefix.
+///
+/// # Errors
+///
+/// The config cannot be loaded, or the request has no tenant in SaaS mode.
+pub(crate) async fn transcript_store(
+ ctx: &crate::core::runtime::DispatchCtx,
+) -> Result<TranscriptStore, String> {
+ let config = ctx
+ .load_config()
+ .await
+ .map_err(|e| format!("load config: {e}"))?;
+ let tenant = crate::core::runtime::tenant::tenant_in(
+ crate::core::runtime::is_saas(),
+ ctx.resolved().as_deref(),
+ )
+ .map_err(|no_tenant| no_tenant.to_string())?;
+ Ok(transcript_store_for(&config, &tenant))
+}
+
+/// [`transcript_store`] for an already-resolved config and tenant.
+pub(crate) fn transcript_store_for(
+ config: &Config,
+ tenant: &crate::core::runtime::Tenant,
+) -> TranscriptStore {
+ let key = crate::agent::session_store::agent_key_for(
+ tenant,
+ &crate::web_chat::pick_target_agent_id(config),
+ );
+ log::debug!(
+ "[threads] transcript store key resolved profile={} agent={}",
+ tenant.profile.is_some(),
+ tenant.agent.is_some()
+ );
+ TranscriptStore {
+ workspace_dir: config.workspace_dir.clone(),
+ key,
+ }
+}
+
/// Run a destructive sequence to completion even if the caller's future is
/// dropped (client disconnect, RPC timeout).
///
diff --git a/crates/openhuman-core/src/threads/ops/transcript.rs b/crates/openhuman-core/src/threads/ops/transcript.rs
index 032dfb2c13..6482304fa6 100644
--- a/crates/openhuman-core/src/threads/ops/transcript.rs
+++ b/crates/openhuman-core/src/threads/ops/transcript.rs
@@ -1,6 +1,7 @@
//! Paginated projection of a thread's settled transcript.
-use super::support::{counts, envelope, workspace_dir};
+use super::support::{counts, envelope, transcript_store};
+use crate::core::runtime::DispatchCtx;
use crate::core::Outcome;
use crate::threads::{ApiEnvelope, PaginationMeta};
@@ -16,23 +17,33 @@ pub struct TranscriptGetRequest {
pub limit: Option<usize>,
}
-/// Project a thread's settled transcript (derived from `session_raw/*.jsonl`)
-/// into typed display items, newest-first paginated. Returns an empty page with
-/// `hasTranscript: false` when the thread has no persisted transcript yet.
+/// Project a thread's settled transcript (read from the session store the
+/// request's tenant wrote it to) into typed display items, newest-first
+/// paginated. Returns an empty page with `hasTranscript: false` when the
+/// thread has no persisted transcript yet.
pub async fn transcript_get(
+ ctx: &DispatchCtx,
request: TranscriptGetRequest,
) -> Result<Outcome<ApiEnvelope<tinyagents_session::transcript::view::TranscriptPage>>, String> {
- let dir = workspace_dir().await?;
- let thread_id = request.thread_id.trim();
+ let thread_id = request.thread_id.trim().to_string();
if thread_id.is_empty() {
return Err("thread_id is required".to_string());
}
- let page = tinyagents_session::transcript::view::get_page(
- &dir,
- thread_id,
- request.cursor.as_deref(),
- request.limit,
- );
+ // Resolved here, in the request's scope; the projection itself is blocking.
+ let locator = transcript_store(ctx).await?.locator();
+ let cursor = request.cursor.clone();
+ let limit = request.limit;
+ let page = tokio::task::spawn_blocking(move || {
+ tinyagents_session::transcript::view::get_page_in(
+ locator.as_ref(),
+ &thread_id,
+ None,
+ cursor.as_deref(),
+ limit,
+ )
+ })
+ .await
+ .map_err(|e| format!("transcript page task: {e}"))?;
let counts = counts([
("items", page.items.len()),
("total", page.total),
diff --git a/crates/openhuman-core/src/threads/ops/usage.rs b/crates/openhuman-core/src/threads/ops/usage.rs
index 514dbaccec..ec7e472af9 100644
--- a/crates/openhuman-core/src/threads/ops/usage.rs
+++ b/crates/openhuman-core/src/threads/ops/usage.rs
@@ -1,9 +1,10 @@
//! Aggregated token/cost usage for a thread, re-audited at current pricing.
-use super::support::{counts, envelope, workspace_dir};
+use super::support::{counts, envelope, transcript_store};
+use crate::core::runtime::DispatchCtx;
use crate::core::Outcome;
use crate::threads::ApiEnvelope;
-use tinyagents_session::transcript::spend::thread_spend;
+use tinyagents_session::transcript::spend::thread_spend_in;
/// Request for [`token_usage`]: the thread whose persisted usage to total.
#[derive(Debug, Clone, serde::Deserialize)]
@@ -61,12 +62,19 @@ pub struct SubagentUsageDto {
pub runs: usize,
}
-/// Total a thread's persisted token/cost usage across its root transcripts.
+/// Total a thread's persisted token/cost usage across its root transcripts
+/// and their sub-agents, read from the store the request's tenant wrote them
+/// to.
pub async fn token_usage(
+ ctx: &DispatchCtx,
request: ThreadTokenUsageRequest,
) -> Result<Outcome<ApiEnvelope<ThreadTokenUsageResponse>>, String> {
- let dir = workspace_dir().await?;
- let spend = thread_spend(&dir, &request.thread_id);
+ // Resolved here, in the request's scope; the read itself is blocking.
+ let locator = transcript_store(ctx).await?.locator();
+ let thread_id = request.thread_id.clone();
+ let spend = tokio::task::spawn_blocking(move || thread_spend_in(locator.as_ref(), &thread_id))
+ .await
+ .map_err(|e| format!("thread usage task: {e}"))?;
if !spend.found_transcript {
return Ok(envelope(
diff --git a/crates/openhuman-core/src/threads/schemas/handlers.rs b/crates/openhuman-core/src/threads/schemas/handlers.rs
index 693b09b447..567bc91907 100644
--- a/crates/openhuman-core/src/threads/schemas/handlers.rs
+++ b/crates/openhuman-core/src/threads/schemas/handlers.rs
@@ -173,23 +173,20 @@ pub(super) fn handle_turn_state_clear(
})
}
-pub(super) fn handle_token_usage(
- _ctx: DispatchCtx,
- params: Map<String, Value>,
-) -> ControllerFuture {
+pub(super) fn handle_token_usage(ctx: DispatchCtx, params: Map<String, Value>) -> ControllerFuture {
Box::pin(async move {
let p = parse::<ops::ThreadTokenUsageRequest>(params)?;
- to_json(ops::token_usage(p).await?)
+ to_json(ops::token_usage(&ctx, p).await?)
})
}
pub(super) fn handle_transcript_get(
- _ctx: DispatchCtx,
+ ctx: DispatchCtx,
params: Map<String, Value>,
) -> ControllerFuture {
Box::pin(async move {
let p = parse::<ops::TranscriptGetRequest>(params)?;
- to_json(ops::transcript_get(p).await?)
+ to_json(ops::transcript_get(&ctx, p).await?)
})
}
@@ -220,7 +217,11 @@ pub(super) fn handle_edit_message(
) -> ControllerFuture {
Box::pin(async move {
let p = parse::<ops::EditMessageRequest>(params)?;
- to_json(ops::edit_message(&ctx, p).await.map_err(|e| e.to_string())?)
+ to_json(
+ ops::edit_message(&ctx, p)
+ .await
+ .map_err(|e| e.to_string())?,
+ )
})
}
diff --git a/crates/openhuman-core/src/threads/schemas/schema_defs.rs b/crates/openhuman-core/src/threads/schemas/schema_defs.rs
index 3e35499eb6..99c3b9d34c 100644
--- a/crates/openhuman-core/src/threads/schemas/schema_defs.rs
+++ b/crates/openhuman-core/src/threads/schemas/schema_defs.rs
@@ -401,7 +401,7 @@ pub(crate) fn schemas(function: &str) -> ControllerSchema {
namespace: "threads",
function: "transcript_get",
description:
- "Project a thread's settled transcript (derived from session_raw/*.jsonl) into typed display items, newest-first paginated.",
+ "Project a thread's settled transcript (read from the session store) into typed display items, newest-first paginated.",
inputs: vec![
FieldSchema {
name: "thread_id",