The fastest, cheapest, most efficient open-source agent harness. Run more than 500 agents on a $10 VPS.
Rust agent-orchestrationai-agentsai-assistantdesktopllmlocal-firstmcppersonal-aiprivacyrustsecond-braintauri
refactor(threads): restructure transcript view into dedicated module
Steven Enamakel0ac0c82fadc4
diff --git a/crates/openhuman-core/src/agent/messages.rs b/crates/openhuman-core/src/agent/messages.rsindex ea3d937981..87daccc16b 100644--- a/crates/openhuman-core/src/agent/messages.rs+++ b/crates/openhuman-core/src/agent/messages.rs@@ -14,12 +14,6 @@ const REPLAYED_METADATA_KEY: &str = "openhuman_replayed";const WRAPPED_VALUE_KEY: &str = "openhuman_wrapped_value";const WRAPPED_FLAG: &str = "wrapped";-/// Durable `extra_metadata` key on a text-dialect `[Tool results]` user row:-/// the call ids whose results in that row failed. The per-result analogue of-/// the `tool_failure` a native `tool` row carries; written by the session codec-/// and read by the thread transcript projection.-pub(crate) const TOOL_RESULT_FAILURES_METADATA_KEY: &str = "openhuman_tool_failures";-fn would_wrap(message: &ChatMessage) -> bool {matches!(&message.extra_metadata, Some(value) if !value.is_object())}diff --git a/crates/openhuman-core/src/agent/session_host/codec.rs b/crates/openhuman-core/src/agent/session_host/codec.rsindex 0db8d0f8c4..b5eaefbc21 100644--- a/crates/openhuman-core/src/agent/session_host/codec.rs+++ b/crates/openhuman-core/src/agent/session_host/codec.rs@@ -6,13 +6,11 @@use crate::agent::{message_convert,- messages::{- chat_message_from_transcript, transcript_message_from_chat,- TOOL_RESULT_FAILURES_METADATA_KEY,- },+ messages::{chat_message_from_transcript, transcript_message_from_chat},tinyagents::host::OpenHumanRunContext,};use tinyagents_runtime::{RuntimeError, TranscriptCodec, TranscriptTurnOptions};+use tinyagents_session::transcript::view::TOOL_RESULT_FAILURES_METADATA_KEY;use tinyagents_session::transcript::{MessageUsage, SessionTranscript, ToolFailure, TranscriptMessage, TranscriptToolCall, TurnUsage,};diff --git a/crates/openhuman-core/src/threads/README.md b/crates/openhuman-core/src/threads/README.mdindex 6a727be394..102da125ae 100644--- a/crates/openhuman-core/src/threads/README.md+++ b/crates/openhuman-core/src/threads/README.md@@ -35,7 +35,7 @@ replay. The welcome migration is guarded by- `ops/`: conversation, message, title, usage, transcript, and turn-state ops.- `schemas/`: controller schemas and thin handlers.- `turn_state/`: persisted turn snapshots and the progress-event mirror.-- `transcript_view/`: session transcript projection for the renderer.+- Transcript projection for the renderer lives in `tinyagents_session::transcript::view`; `ops/transcript.rs` serves it over RPC.- `welcome_migration.rs`: one-shot legacy conversation migration.Agent goal and todo integration lives in `crate::agent::{goals,todos}` and isdiff --git a/crates/openhuman-core/src/threads/mod.rs b/crates/openhuman-core/src/threads/mod.rsindex 0600465c50..e4b271310b 100644--- a/crates/openhuman-core/src/threads/mod.rs+++ b/crates/openhuman-core/src/threads/mod.rs@@ -7,7 +7,8 @@pub mod error;pub mod ops;pub mod schemas;-pub mod transcript_view;+#[cfg(test)]+mod transcript_host_tests;pub mod turn_state;pub mod welcome_migration;diff --git a/crates/openhuman-core/src/threads/ops/edit.rs b/crates/openhuman-core/src/threads/ops/edit.rsindex 4b3c0e5c28..6fc4791249 100644--- a/crates/openhuman-core/src/threads/ops/edit.rs+++ b/crates/openhuman-core/src/threads/ops/edit.rs@@ -234,7 +234,7 @@ async fn next_reply_request_id_after(/// 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 (`threads::transcript_view::resolve`'s module doc explains why that+/// order (`tinyagents_session::transcript::view`'s resolver module doc explains why that/// is unsafe: `.g1` sorts before the un-suffixed root).fn resolve_head_transcript(workspace_dir: &std::path::Path,diff --git a/crates/openhuman-core/src/threads/ops/transcript.rs b/crates/openhuman-core/src/threads/ops/transcript.rsindex 4f7cd82abd..c0f93acaff 100644--- a/crates/openhuman-core/src/threads/ops/transcript.rs+++ b/crates/openhuman-core/src/threads/ops/transcript.rs@@ -21,13 +21,13 @@ pub struct TranscriptGetRequest {/// `hasTranscript: false` when the thread has no persisted transcript yet.pub async fn transcript_get(request: TranscriptGetRequest,-) -> Result<Outcome<ApiEnvelope<crate::threads::transcript_view::TranscriptPage>>, String> {+) -> Result<Outcome<ApiEnvelope<tinyagents_session::transcript::view::TranscriptPage>>, String> {let dir = workspace_dir().await?;let thread_id = request.thread_id.trim();if thread_id.is_empty() {return Err("thread_id is required".to_string());}- let page = crate::threads::transcript_view::get_page(+ let page = tinyagents_session::transcript::view::get_page(&dir,thread_id,request.cursor.as_deref(),@@ -41,7 +41,7 @@ pub async fn transcript_get(let pagination = Some(PaginationMeta {limit: request.limit- .unwrap_or(crate::threads::transcript_view::DEFAULT_LIMIT),+ .unwrap_or(tinyagents_session::transcript::view::DEFAULT_LIMIT),offset: request.cursor.as_deref()diff --git a/crates/openhuman-core/src/threads/transcript_view/transcript_view_tool_round_tests.rs b/crates/openhuman-core/src/threads/transcript_host_tests.rssimilarity index 80%rename from crates/openhuman-core/src/threads/transcript_view/transcript_view_tool_round_tests.rsrename to crates/openhuman-core/src/threads/transcript_host_tests.rsindex db107ee5e1..edf5946979 100644--- a/crates/openhuman-core/src/threads/transcript_view/transcript_view_tool_round_tests.rs+++ b/crates/openhuman-core/src/threads/transcript_host_tests.rs@@ -1,10 +1,15 @@+//! Host-side transcript-view tests (the projection itself lives in+//! `tinyagents_session::transcript::view`): they drive it through OpenHuman's+//! own writer types (`ChatMessage`, the session codec).+//!//! Tool-round projection tests: text-dialect rounds persisted through the real//! session codec and writer, and transcripts written before calls rode their//! issuing row.-use super::project::{project_records, project_thread};-use super::types::{DisplayItem, ToolCallStatus};-use crate::agent::messages::ChatMessage;+use crate::agent::messages::{+ attach_chat_tool_failure_metadata, transcript_message_from_chat, ChatMessage,+};+use tinyagents_session::transcript::view::{project_records, project_thread, DisplayItem, ToolCallStatus};use tempfile::TempDir;use tinyagents_session::transcript::{self, read_transcript_display};@@ -311,3 +316,70 @@ fn calls_recorded_after_their_results_project_as_settled() {"{items:?}");}++#[test]+fn tool_failure_metadata_round_trips_write_to_display_line() {+ // Full write path: a failed tool ChatMessage stamped with failure metadata+ // must serialise the additive `failure` line field and read back as a failed+ // display message — proving the harness → transcript → projection seam.+ let dir = TempDir::new().unwrap();+ let now = "2026-07-21T09:00:00Z".to_string();+ let meta = transcript::TranscriptMeta {+ session_id: None,+ parent_session_id: None,+ agent_name: "orchestrator".into(),+ agent_id: Some("orchestrator".into()),+ agent_type: Some("root".into()),+ dispatcher: "native".into(),+ provider: Some("anthropic".into()),+ model: Some("m".into()),+ created: now.clone(),+ updated: now,+ turn_count: 1,+ prefix_message_count: None,+ input_tokens: 0,+ output_tokens: 0,+ cached_input_tokens: 0,+ charged_amount_usd: 0.0,+ thread_id: Some("thr_rt".into()),+ task_id: None,+ };++ let mut tool_msg = ChatMessage {+ id: Some("call-1".into()),+ role: "tool".into(),+ content: r#"{"tool_call_id":"call-1","content":"boom"}"#.into(),+ extra_metadata: None,+ cache_breakpoints: Vec::new(),+ };+ attach_chat_tool_failure_metadata(&mut tool_msg, Some("boom: exit 1"));++ let messages = vec![+ ChatMessage {+ id: None,+ role: "user".into(),+ content: "do it".into(),+ extra_metadata: None,+ cache_breakpoints: Vec::new(),+ },+ tool_msg,+ ];+ let path = transcript::resolve_keyed_transcript_path(dir.path(), "700_orchestrator").unwrap();+ let messages: Vec<_> = messages.iter().map(transcript_message_from_chat).collect();+ transcript::write_transcript(&path, &messages, &meta, None).unwrap();++ let display = read_transcript_display(&path).unwrap();+ let failed = display+ .records+ .iter()+ .find_map(|r| match r {+ transcript::DisplayRecord::Message(m) if m.message.role == "tool" => Some(m),+ _ => None,+ })+ .expect("tool display message present");+ assert!(+ failed.failure,+ "failure flag survived the write/read round trip"+ );+ assert_eq!(failed.failure_detail.as_deref(), Some("boom: exit 1"));+}diff --git a/crates/openhuman-core/src/threads/transcript_view/cache.rs b/crates/openhuman-core/src/threads/transcript_view/cache.rsdeleted file mode 100644index 426b7d2b05..0000000000--- a/crates/openhuman-core/src/threads/transcript_view/cache.rs+++ /dev/null@@ -1,157 +0,0 @@-//! In-memory, mtime-keyed projection cache for the transcript view.-//!-//! The settled transcript is derived from `session_raw/*.jsonl` on every-//! request. Re-projecting a long thread on each page fetch is wasteful, so we-//! memoize per-thread projections keyed on the backing files' `(path, mtime,-//! len)` signature. An append (new turn, interrupted partial, sub-agent file)-//! changes the signature and transparently invalidates the entry — there are-//! **no disk writes** and no explicit invalidation call. The cache is bounded-//! (LRU over a few dozen threads) so a long-lived core can't grow it without-//! limit.--use std::collections::HashMap;-use std::collections::VecDeque;-use std::path::{Path, PathBuf};-use std::sync::{Arc, Mutex, OnceLock};-use std::time::SystemTime;--use super::project;-use super::types::ProjectedTranscript;--const LOG_PREFIX: &str = "[threads][transcript][cache]";--/// Number of distinct threads whose projections are retained. Beyond this the-/// least-recently-used entry is evicted.-const CACHE_CAPACITY: usize = 32;--/// Signature of one backing file — changes on any append/rewrite.-#[derive(Debug, Clone, PartialEq, Eq)]-struct FileSig {- path: PathBuf,- mtime: Option<SystemTime>,- len: u64,-}--fn file_sig(path: &Path) -> FileSig {- let (mtime, len) = match std::fs::metadata(path) {- Ok(meta) => (meta.modified().ok(), meta.len()),- Err(_) => (None, 0),- };- FileSig {- path: path.to_path_buf(),- mtime,- len,- }-}--struct CacheEntry {- signature: Vec<FileSig>,- projected: Arc<ProjectedTranscript>,-}--#[derive(Default)]-struct CacheInner {- entries: HashMap<String, CacheEntry>,- /// LRU order — front is least-recently-used.- order: VecDeque<String>,-}--/// Bounded per-thread projection cache.-#[derive(Default)]-pub struct TranscriptViewCache {- inner: Mutex<CacheInner>,-}--impl TranscriptViewCache {- /// Project `thread_id`'s transcript, serving a cached result when the- /// backing files are unchanged. `None` when the thread has no transcript.- pub fn get_or_project(- &self,- workspace_dir: &Path,- thread_id: &str,- ) -> Option<Arc<ProjectedTranscript>> {- let (root_paths, sub_paths) = project::resolve_files(workspace_dir, thread_id)?;- let signature: Vec<FileSig> = root_paths- .iter()- .map(|path| file_sig(path))- .chain(sub_paths.iter().map(|p| file_sig(p)))- .collect();-- {- let mut inner = self.inner.lock().ok()?;- if let Some(entry) = inner.entries.get(thread_id) {- if entry.signature == signature {- let projected = entry.projected.clone();- touch(&mut inner, thread_id);- log::debug!(- "{LOG_PREFIX} hit thread={thread_id} items={}",- projected.items.len()- );- return Some(projected);- }- log::debug!("{LOG_PREFIX} miss (signature changed) thread={thread_id}");- } else {- log::debug!("{LOG_PREFIX} miss (cold) thread={thread_id}");- }- }-- let projected = Arc::new(project::project_from_files(- thread_id,- &root_paths,- &sub_paths,- Some(workspace_dir),- ));-- let mut inner = self.inner.lock().ok()?;- inner.entries.insert(- thread_id.to_string(),- CacheEntry {- signature,- projected: projected.clone(),- },- );- touch(&mut inner, thread_id);- evict_if_needed(&mut inner);- log::debug!(- "{LOG_PREFIX} stored thread={thread_id} items={} cache_size={}",- projected.items.len(),- inner.entries.len()- );- Some(projected)- }-- #[cfg(test)]- fn len(&self) -> usize {- self.inner.lock().unwrap().entries.len()- }-}--/// Move `thread_id` to the most-recently-used end of the LRU order.-fn touch(inner: &mut CacheInner, thread_id: &str) {- if let Some(pos) = inner.order.iter().position(|t| t == thread_id) {- inner.order.remove(pos);- }- inner.order.push_back(thread_id.to_string());-}--/// Evict least-recently-used entries until within [`CACHE_CAPACITY`].-fn evict_if_needed(inner: &mut CacheInner) {- while inner.entries.len() > CACHE_CAPACITY {- let Some(victim) = inner.order.pop_front() else {- break;- };- inner.entries.remove(&victim);- log::debug!("{LOG_PREFIX} evicted thread={victim}");- }-}--/// Process-wide cache singleton. The transcript view is read-only and derived,-/// so one shared cache across RPC calls is correct.-pub fn global() -> &'static TranscriptViewCache {- static CACHE: OnceLock<TranscriptViewCache> = OnceLock::new();- CACHE.get_or_init(TranscriptViewCache::default)-}--#[cfg(test)]-#[path = "cache_tests.rs"]-mod tests;diff --git a/crates/openhuman-core/src/threads/transcript_view/cache_tests.rs b/crates/openhuman-core/src/threads/transcript_view/cache_tests.rsdeleted file mode 100644index 1f25d355d9..0000000000--- a/crates/openhuman-core/src/threads/transcript_view/cache_tests.rs+++ /dev/null@@ -1,74 +0,0 @@-//! Cache hit/miss + invalidation tests for the transcript view cache.--use super::TranscriptViewCache;-use std::path::Path;-use tempfile::TempDir;-use tinyagents_session::transcript;--fn meta_line(thread_id: &str) -> String {- format!(- r#"{{"_meta":{{"version":1,"agent":"orchestrator","dispatcher":"native","created":"2026-07-21T00:00:00Z","updated":"2026-07-21T00:00:00Z","turn_count":1,"input_tokens":0,"output_tokens":0,"cached_input_tokens":0,"charged_amount_usd":0.0,"thread_id":"{thread_id}"}}}}"#- )-}--fn write_raw(workspace: &Path, stem: &str, thread_id: &str, body: &[&str]) -> std::path::PathBuf {- let path = transcript::resolve_keyed_transcript_path(workspace, stem).unwrap();- let mut buf = meta_line(thread_id);- buf.push('\n');- for line in body {- buf.push_str(line);- buf.push('\n');- }- std::fs::write(&path, buf).unwrap();- path-}--#[test]-fn recomputes_when_file_grows() {- let dir = TempDir::new().unwrap();- let path = write_raw(- dir.path(),- "100_orchestrator",- "thr_cache",- &[r#"{"role":"user","content":"first"}"#],- );- let cache = TranscriptViewCache::default();-- let a = cache- .get_or_project(dir.path(), "thr_cache")- .expect("first");- assert_eq!(a.items.len(), 1);-- // Second call, unchanged file → same cached Arc (hit).- let b = cache- .get_or_project(dir.path(), "thr_cache")- .expect("second");- assert!(- std::sync::Arc::ptr_eq(&a, &b),- "unchanged file must serve cached Arc"- );-- // Append a line → file length changes → signature invalidates → recompute.- let mut appended = std::fs::read_to_string(&path).unwrap();- appended.push_str(r#"{"role":"assistant","content":"second"}"#);- appended.push('\n');- std::fs::write(&path, appended).unwrap();-- let c = cache- .get_or_project(dir.path(), "thr_cache")- .expect("third");- assert!(!std::sync::Arc::ptr_eq(&a, &c), "grown file must recompute");- assert_eq!(- c.items.len(),- 2,- "recomputed projection reflects the append"- );-}--#[test]-fn missing_thread_returns_none() {- let dir = TempDir::new().unwrap();- let cache = TranscriptViewCache::default();- assert!(cache.get_or_project(dir.path(), "ghost").is_none());- assert_eq!(cache.len(), 0);-}diff --git a/crates/openhuman-core/src/threads/transcript_view/mod.rs b/crates/openhuman-core/src/threads/transcript_view/mod.rsdeleted file mode 100644index 5efb409a1a..0000000000--- a/crates/openhuman-core/src/threads/transcript_view/mod.rs+++ /dev/null@@ -1,122 +0,0 @@-//! Transcript-derived view: project the append-only `session_raw/*.jsonl`-//! source of truth into typed display items for the chat renderer, with-//! newest-first pagination over a bounded in-memory cache.-//!-//! Entry point: [`get_page`] (used by the `threads.transcript_get` RPC).--mod cache;-mod project;-mod prompt_tools;-mod resolve;-mod subagents;-pub mod types;--use std::path::Path;--use serde::Serialize;--pub use types::{DisplayItem, ProjectedTranscript, SubagentStatus, ToolCallStatus};--const LOG_PREFIX: &str = "[threads][transcript]";--/// Default page size — roughly one screen of chat items.-pub const DEFAULT_LIMIT: usize = 50;-/// Hard upper bound on a single page so a client can't request an unbounded-/// projection slice.-pub const MAX_LIMIT: usize = 500;--/// One newest-first page of a thread's projected transcript.-#[derive(Debug, Clone, Serialize)]-#[serde(rename_all = "camelCase")]-pub struct TranscriptPage {- pub thread_id: String,- /// Display items for this page, **newest-first**.- pub items: Vec<DisplayItem>,- /// Total top-level items available for the thread.- pub total: usize,- /// Opaque cursor to pass back for the next (older) page; `null` at the end.- #[serde(skip_serializing_if = "Option::is_none")]- pub next_cursor: Option<String>,- /// `true` when more (older) items remain beyond this page.- pub has_more: bool,- /// `false` when the thread has no persisted transcript yet (empty page).- pub has_transcript: bool,-}--/// Project `thread_id`'s transcript and return one newest-first page.-///-/// `cursor` is the opaque token returned as `next_cursor` by a previous call-/// (an offset from the newest item); `None`/empty starts at the newest item.-/// `limit` defaults to [`DEFAULT_LIMIT`] and is clamped to [`MAX_LIMIT`].-pub fn get_page(- workspace_dir: &Path,- thread_id: &str,- cursor: Option<&str>,- limit: Option<usize>,-) -> TranscriptPage {- let limit = limit.unwrap_or(DEFAULT_LIMIT).clamp(1, MAX_LIMIT);- let offset = parse_cursor(cursor);-- let Some(projected) = cache::global().get_or_project(workspace_dir, thread_id) else {- log::debug!("{LOG_PREFIX} get_page thread={thread_id}: no transcript");- return TranscriptPage {- thread_id: thread_id.to_string(),- items: Vec::new(),- total: 0,- next_cursor: None,- has_more: false,- has_transcript: false,- };- };-- let total = projected.items.len();- let start = offset.min(total);- let end = (offset + limit).min(total);- // Newest-first: item `offset` is the newest, walking backwards from the end.- let items: Vec<DisplayItem> = (start..end)- .map(|i| projected.items[total - 1 - i].clone())- .collect();- let has_more = end < total;- let next_cursor = has_more.then(|| end.to_string());-- log::debug!(- "{LOG_PREFIX} get_page thread={thread_id} total={total} offset={offset} returned={} has_more={has_more}",- items.len()- );-- TranscriptPage {- thread_id: thread_id.to_string(),- items,- total,- next_cursor,- has_more,- has_transcript: true,- }-}--/// Parse the opaque cursor into a numeric offset (0 on absent/invalid).-fn parse_cursor(cursor: Option<&str>) -> usize {- cursor- .map(str::trim)- .filter(|c| !c.is_empty())- .and_then(|c| c.parse::<usize>().ok())- .unwrap_or(0)-}--#[cfg(test)]-#[path = "transcript_subagent_anchor_tests.rs"]-mod subagent_anchor_tests;-#[cfg(test)]-#[path = "transcript_view_tests.rs"]-mod tests;-#[cfg(test)]-#[path = "transcript_view_tool_round_tests.rs"]-mod tool_round_tests;--#[cfg(test)]-#[path = "prompt_tools_tests.rs"]-mod prompt_tools_tests;--#[cfg(test)]-#[path = "transcript_ordering_tests.rs"]-mod ordering_tests;diff --git a/crates/openhuman-core/src/threads/transcript_view/project.rs b/crates/openhuman-core/src/threads/transcript_view/project.rsdeleted file mode 100644index 48fd2036db..0000000000--- a/crates/openhuman-core/src/threads/transcript_view/project.rs+++ /dev/null@@ -1,674 +0,0 @@-//! Project raw session-transcript records into typed display items.-//!-//! Turns the append-only log's [`DisplayRecord`]s (message lines, compaction-//! markers, interrupted partials) into the frontend's chat vocabulary-//! ([`DisplayItem`]), sanitizing injected scaffolding as it goes. File-//! resolution lives in [`super::resolve`]; sub-agent trails are placed by-//! [`super::subagents`].--use std::collections::{HashSet, VecDeque};-use std::path::{Path, PathBuf};--use tinyagents_session::transcript::{self, CompactionMarker, DisplayMessage, DisplayRecord};-use tinytools_agent::dialect::{parse_replayed_results, ToolResultEntry};--use crate::agent::messages::TOOL_RESULT_FAILURES_METADATA_KEY;--use super::prompt_tools::{self, CallRegistry, PromptToolResult};-use super::resolve;-use super::subagents;-use super::types::{DisplayItem, ProjectedTranscript, ToolCallFailure, ToolCallStatus};--const LOG_PREFIX: &str = "[threads][transcript]";--/// The scaffolding line injected onto every user message (see-/// `agent::prompts::current_datetime_line`). Stripped at projection so the UI-/// shows the user's actual words, not the per-turn time stamp.-const DATETIME_PREFIX: &str = "Current Date & Time:";--/// A legacy/alternate channel-context prefix. Kept for defensiveness; the-/// live injector currently only prepends [`DATETIME_PREFIX`].-const CHANNEL_CONTEXT_PREFIX: &str = "[Channel context]";--type NativeToolCall = (String, String, String);-type NativeToolEnvelope = (String, Vec<NativeToolCall>);--/// Resolve a thread's root transcript, discover its sub-agent siblings, and-/// project everything into display items. Returns `None` when the thread has-/// no root transcript yet (brand-new thread / first turn not persisted).-pub fn project_thread(workspace_dir: &Path, thread_id: &str) -> Option<ProjectedTranscript> {- let (root_paths, sub_paths) = resolve_files(workspace_dir, thread_id)?;- Some(project_from_files(- thread_id,- &root_paths,- &sub_paths,- Some(workspace_dir),- ))-}--/// Resolve the on-disk file set backing a thread's transcript view: the root-/// generations in chain order plus every sub-agent sibling file. `None` when-/// the thread has no root transcript yet. Exposed so the cache can key on-/// these paths (and their mtimes/lengths) without re-projecting.-pub fn resolve_files(- workspace_dir: &Path,- thread_id: &str,-) -> Option<(Vec<PathBuf>, Vec<PathBuf>)> {- resolve::resolve_files(workspace_dir, thread_id)-}--/// Project a thread from an already-resolved file set (root generations +-/// sub-agent siblings). Missing/unreadable files degrade to empty rather than-/// failing.-///-/// A root whose `_meta.parent_session_id` names the previous root is that-/// session's next compaction generation: it opens with the retained set-/// rewritten, so those rows are dropped (see [`resolve::drop_retained_rows`])-/// and a [`DisplayItem::Compaction`] marks the seam instead.-pub fn project_from_files(- thread_id: &str,- root_paths: &[PathBuf],- sub_paths: &[PathBuf],- workspace_dir: Option<&Path>,-) -> ProjectedTranscript {- log::debug!(- "{LOG_PREFIX} projecting thread={thread_id} roots={} subagent_files={}",- root_paths.len(),- sub_paths.len()- );-- let mut records: Vec<DisplayRecord> = Vec::new();- let mut previous: Option<(Option<String>, Vec<DisplayRecord>)> = None;- for root_path in root_paths {- let display = match transcript::read_transcript_display(root_path) {- Ok(display) => display,- Err(err) => {- log::warn!(- "{LOG_PREFIX} failed to read root transcript {}: {err}",- root_path.display()- );- continue;- }- };- let successor_of_previous = matches!(- (&previous, display.meta.parent_session_id.as_deref()),- (Some((Some(prev_id), _)), Some(parent)) if prev_id == parent- );- if successor_of_previous {- let predecessor = previous- .as_ref()- .map(|(_, prev_records)| resolve::generation_rows(prev_records))- .unwrap_or_default();- let (kept, retained) = resolve::drop_retained_rows(&display.records, predecessor);- log::debug!(- "{LOG_PREFIX} generation {} retained={} new_records={}",- root_path.display(),- retained.len(),- kept.len()- );- let first_kept = kept.iter().find_map(|record| match record {- DisplayRecord::Message(msg) => Some(msg),- DisplayRecord::Compaction(_) => None,- });- let request_id = first_kept.and_then(|message| message.request_id.clone());- records.push(DisplayRecord::Compaction(CompactionMarker {- replacement: retained,- ts: first_kept- .and_then(|message| message.ts.clone())- .or_else(|| Some(display.meta.created.clone()))- .filter(|ts| !ts.is_empty()),- request_id,- }));- records.extend(kept);- } else {- records.extend(display.records.iter().cloned());- }- previous = Some((display.meta.session_id.clone(), display.records));- }-- let mut items = project_records(&records);- let top_level = items.len();- subagents::attach(- &mut items,- sub_paths,- &subagents::turn_segments(&records),- workspace_dir,- );- log::debug!(- "{LOG_PREFIX} projected thread={thread_id} top_level_items={top_level} subagents={}",- items.len() - top_level- );-- ProjectedTranscript {- thread_id: thread_id.to_string(),- items,- }-}--/// Project one file's display records into display items, in file order.-///-/// - System lines are dropped (they carry the tool-policy preamble and other-/// scaffolding that must never render as a chat item).-/// - `reasoning_content` on an assistant line becomes a [`DisplayItem::Reasoning`]-/// preceding its message, carrying the same `iteration`.-/// - An assistant line's tool calls come from its native provider envelope.-/// Only a line that is *not* an envelope falls back to the calls recorded on-/// its usage (legacy text-dialect rows) — and never to a call id already-/// projected, which is how an aggregate list copied onto a final answer-/// would otherwise duplicate every call of the turn.-/// - Each call registers a pending [`DisplayItem::ToolCall`]; a later-/// `role:"tool"` line pairs to one by id, falling back to FIFO order.-/// - A prompt-guided round (calls in the visible text, results folded into one-/// `[Tool results]` user line) projects to the same shape: see-/// [`prompt_tools`].-/// - Interrupted partials and compaction markers pass through as their items.-/// - A [`DisplayItem::TurnBoundary`] is emitted whenever `request_id` changes.-pub fn project_records(records: &[DisplayRecord]) -> Vec<DisplayItem> {- let mut projector = Projector {- calls: CallRegistry::from_records(records),- ..Projector::default()- };- for (index, record) in records.iter().enumerate() {- match record {- DisplayRecord::Message(msg) => {- projector.turn_boundary(msg);- // A prompt-guided round's results are on the NEXT line; they are- // the only record of which calls this assistant line issued.- projector.next_results = match records.get(index + 1) {- Some(DisplayRecord::Message(next)) => prompt_tools::parse_tool_results(next),- _ => None,- };- projector.message(msg);- }- DisplayRecord::Compaction(marker) => {- project_compaction(marker, &mut projector.items);- // A compaction supersedes prior context; drop stale pending- // pairings so a post-compaction result never binds to them.- projector.pending.clear();- }- }- }- projector.items-}--#[derive(Default)]-struct Projector {- items: Vec<DisplayItem>,- /// Pending tool calls awaiting a result line: (call_id, index into `items`).- pending: VecDeque<(String, usize)>,- last_request_id: Option<String>,- /// Every tool-call id already projected, so a row repeating calls issued- /// earlier (the aggregate usage list) does not render them twice.- seen_call_ids: HashSet<String>,- /// The model-call ordinal of the last assistant row in the current turn —- /// the fallback `iteration` for rows written without one.- step: u32,- /// Every call the file records, for resolving a prompt-guided round.- calls: CallRegistry,- /// Result blocks of the line after the one being projected, when that line- /// is a prompt-guided `[Tool results]` turn.- next_results: Option<Vec<PromptToolResult>>,-}--impl Projector {- fn turn_boundary(&mut self, msg: &DisplayMessage) {- let Some(rid) = msg.request_id.as_deref() else {- return;- };- if self.last_request_id.as_deref() != Some(rid) {- self.items.push(DisplayItem::TurnBoundary {- request_id: rid.to_string(),- });- self.last_request_id = Some(rid.to_string());- self.step = 0;- self.seen_call_ids.clear();- }- }-- fn message(&mut self, msg: &DisplayMessage) {- // Interrupted partial: display-only, carries its own thinking.- if msg.interrupted {- self.items.push(DisplayItem::InterruptedPartial {- text: msg.message.content.clone(),- thinking: msg.reasoning_content.clone(),- });- return;- }-- match msg.message.role.as_str() {- "system" => {- // Scaffolding (tool-policy preamble, etc.) — never a display item.- log::debug!("{LOG_PREFIX} sanitize: dropped system line from projection");- }- "user" => {- // The strict dialect replay shape also starts with- // `[Tool results]`. Handle it first so its persisted failure- // IDs are applied rather than treating every block as success.- if let Some(results) = parse_replayed_results(&msg.message.content) {- self.text_tool_results(msg, results);- return;- }- if let Some(blocks) = prompt_tools::parse_tool_results(msg) {- // Tool plumbing, not something the user said.- for block in blocks {- self.pair_result(- block.id,- block.body,- ToolCallStatus::Success,- None,- msg.ts.clone(),- );- }- return;- }- // A legacy turn without request ids still restarts the step- // count at its prompt.- self.step = 0;- self.seen_call_ids.clear();- let raw = msg.message.content.clone();- let sanitized = sanitize_user_content(&raw);- if sanitized.is_some() {- log::debug!(- "{LOG_PREFIX} sanitize: stripped injected prefix from user message"- );- }- self.items.push(DisplayItem::UserMessage {- content: raw,- display_content: sanitized,- request_id: msg.request_id.clone(),- ts: msg.ts.clone(),- });- }- "assistant" => self.assistant(msg),- "tool" => self.tool_result(msg),- other => {- log::debug!("{LOG_PREFIX} projecting unknown role {other:?} as assistant message");- self.items.push(DisplayItem::AssistantMessage {- content: msg.message.content.clone(),- interim: false,- request_id: msg.request_id.clone(),- model: msg.turn_usage.as_ref().map(|tu| tu.model.clone()),- iteration: msg.iteration,- ts: msg.ts.clone(),- });- }- }- }-- fn assistant(&mut self, msg: &DisplayMessage) {- // Rows the writer stamped keep their own number; earlier writers only- // stamped the final row, so unstamped rows count up within the turn.- let iteration = msg.iteration.unwrap_or(self.step + 1);- self.step = iteration;-- // Reasoning precedes the message it belongs to.- if let Some(reasoning) = msg.reasoning_content.as_deref() {- if !reasoning.trim().is_empty() {- self.items.push(DisplayItem::Reasoning {- text: reasoning.to_string(),- iteration: Some(iteration),- });- }- }-- let native_envelope = parse_native_tool_envelope(&msg.message.content);- let tool_calls: Vec<NativeToolCall> = match &native_envelope {- Some((_, calls)) => calls.clone(),- None => {- let recorded: Vec<NativeToolCall> = msg- .turn_usage- .as_ref()- .map(|tu| {- tu.tool_calls- .iter()- .map(|call| {- (call.id.clone(), call.name.clone(), call.arguments.clone())- })- .collect()- })- .unwrap_or_default();- let total = recorded.len();- let fresh: Vec<NativeToolCall> = recorded- .into_iter()- .filter(|(id, _, _)| id.is_empty() || !self.seen_call_ids.contains(id))- .collect();- if fresh.len() < total {- log::debug!(- "{LOG_PREFIX} dropped {} already-projected tool call(s) repeated on an assistant row iteration={iteration}",- total - fresh.len()- );- }- fresh- }- };- // A prompt-guided line records no calls of its own; the `[Tool results]`- // line after it names the calls it made.- let tool_calls = match self.next_results.take() {- Some(blocks) if tool_calls.is_empty() => {- let inferred = self- .calls- .calls_for(&msg.request_id, &blocks, &self.seen_call_ids);- log::debug!(- "{LOG_PREFIX} prompt-guided round: {} call(s) inferred from the next [Tool results] line iteration={iteration}",- inferred.len()- );- inferred- }- _ => tool_calls,- };- let interim = !tool_calls.is_empty();-- // Native tool-call turns are persisted as their provider envelope so they- // can be replayed byte-faithfully. The display projection needs only the- // envelope's visible `content`; rendering/sanitizing the whole JSON object- // makes the narration disappear (and risks showing raw tool JSON).- let visible_content = native_envelope- .map(|(content, _)| content)- .unwrap_or_else(|| msg.message.content.clone());-- // The assistant's prose (if any) shows before its tool calls.- if !visible_content.trim().is_empty() {- self.items.push(DisplayItem::AssistantMessage {- content: visible_content,- interim,- request_id: msg.request_id.clone(),- model: msg.turn_usage.as_ref().map(|tu| tu.model.clone()),- iteration: Some(iteration),- ts: msg.ts.clone(),- });- }-- for (call_id, name, arguments) in tool_calls {- let args = parse_tool_args(&arguments);- if !call_id.is_empty() {- self.seen_call_ids.insert(call_id.clone());- }- // Transcripts written while the codec filed a turn's calls on its- // final row record a text-dialect call *after* its own result,- // which already projected as an orphan. Name that settled row- // rather than adding a second one that never settles.- if let Some(DisplayItem::ToolCall {- name: settled_name,- args: settled_args,- iteration: settled_iteration,- ..- }) = settled_orphan_mut(&mut self.items, &call_id)- {- log::debug!("{LOG_PREFIX} call {call_id} recorded after its result — merged");- *settled_name = name;- *settled_args = args;- *settled_iteration = Some(iteration);- continue;- }- self.items.push(DisplayItem::ToolCall {- call_id: call_id.clone(),- name,- iteration: Some(iteration),- args,- result: None,- status: ToolCallStatus::Running,- failure: None,- ts: msg.ts.clone(),- });- self.pending.push_back((call_id, self.items.len() - 1));- }- }-- fn tool_result(&mut self, msg: &DisplayMessage) {- let (result, wrapped_id) = unwrap_tool_result(&msg.message.content);- // A failed tool line (`ToolResult::is_error`, stamped at persistence)- // pairs to an error row with a failure payload instead of a false- // success.- let (status, failure) = if msg.failure {- (- ToolCallStatus::Error,- Some(ToolCallFailure {- detail: msg.failure_detail.clone(),- }),- )- } else {- (ToolCallStatus::Success, None)- };- let call_id = msg.message.id.clone().or(wrapped_id);- self.pair_result(call_id, result, status, failure, msg.ts.clone());- }-- /// Settle the pending call a result belongs to — by id first, else FIFO — or- /// emit an orphan row so the output is not lost.- fn pair_result(- &mut self,- call_id: Option<String>,- result: String,- status: ToolCallStatus,- failure: Option<ToolCallFailure>,- ts: Option<String>,- ) {- // Pair by explicit call id first, else FIFO.- let idx = call_id- .as_deref()- .and_then(|id| take_pending_by_id(&mut self.pending, id))- .or_else(|| self.pending.pop_front().map(|(_, idx)| idx));-- if let Some(idx) = idx {- if let Some(DisplayItem::ToolCall {- result: slot,- status: status_slot,- failure: failure_slot,- ..- }) = self.items.get_mut(idx)- {- *slot = Some(result);- *status_slot = status;- *failure_slot = failure;- return;- }- }-- // Orphan result (no matching assistant tool_call recorded) — surface it- // as a best-effort completed tool row so the output is not lost.- log::debug!("{LOG_PREFIX} tool result with no pending call — emitting orphan tool row");- self.items.push(DisplayItem::ToolCall {- call_id: call_id.unwrap_or_default(),- name: "tool".to_string(),- iteration: None,- args: None,- result: Some(result),- status,- failure,- ts,- });- }-}--/// Decode the native provider replay envelope embedded in `ChatMessage.content`.-/// Returns visible assistant prose plus `(id, name, arguments)` calls.-pub(super) fn parse_native_tool_envelope(raw: &str) -> Option<NativeToolEnvelope> {- let value = serde_json::from_str::<serde_json::Value>(raw).ok()?;- let object = value.as_object()?;- let calls = object.get("tool_calls")?.as_array()?;- let content = match object.get("content") {- Some(serde_json::Value::String(content)) => content.clone(),- Some(serde_json::Value::Null) | None => String::new(),- _ => return None,- };- let calls = calls- .iter()- .filter_map(|call| {- let call = call.as_object()?;- let id = call.get("id")?.as_str()?.to_string();- let name = call.get("name")?.as_str()?.to_string();- let arguments = match call.get("arguments") {- Some(serde_json::Value::String(arguments)) => arguments.clone(),- Some(arguments) => arguments.to_string(),- None => String::new(),- };- Some((id, name, arguments))- })- .collect();- Some((content, calls))-}--/// Keys a native tool-result replay envelope may carry besides `content`.-const TOOL_RESULT_ENVELOPE_KEYS: &[&str] = &["content", "tool_call_id", "tool_name", "name"];--/// Unwrap a native tool-result replay envelope-/// (`{"tool_call_id":…,"content":…}`) to the tool's own output plus the call-/// id it names. Anything else — including a tool whose genuine output happens-/// to be JSON with other keys — is returned verbatim.-fn unwrap_tool_result(raw: &str) -> (String, Option<String>) {- let Ok(serde_json::Value::Object(object)) = serde_json::from_str::<serde_json::Value>(raw)- else {- return (raw.to_string(), None);- };- let (Some(content), Some(call_id)) = (- object.get("content").and_then(serde_json::Value::as_str),- object- .get("tool_call_id")- .and_then(serde_json::Value::as_str),- ) else {- return (raw.to_string(), None);- };- if !object- .keys()- .all(|key| TOOL_RESULT_ENVELOPE_KEYS.contains(&key.as_str()))- {- return (raw.to_string(), None);- }- (- content.to_string(),- Some(call_id.to_string()).filter(|id| !id.is_empty()),- )-}--/// Pair each result of a text-dialect `[Tool results]` row with its pending-/// call. Failure status comes from the ids the session codec recorded on the-/// row ([`TOOL_RESULT_FAILURES_METADATA_KEY`]); a result with no pending call-/// surfaces as an orphan row, as for a native `tool` line.-impl Projector {- fn text_tool_results(&mut self, msg: &DisplayMessage, results: Vec<ToolResultEntry>) {- project_text_tool_results(msg, results, &mut self.items, &mut self.pending);- }-}--fn project_text_tool_results(- msg: &DisplayMessage,- results: Vec<ToolResultEntry>,- items: &mut Vec<DisplayItem>,- pending: &mut VecDeque<(String, usize)>,-) {- let failed: Vec<&str> = msg- .message- .extra_metadata- .as_ref()- .and_then(|meta| meta.get(TOOL_RESULT_FAILURES_METADATA_KEY))- .and_then(serde_json::Value::as_array)- .map(|ids| ids.iter().filter_map(serde_json::Value::as_str).collect())- .unwrap_or_default();- log::debug!(- "{LOG_PREFIX} text-dialect results row results={} failed={} pending={}",- results.len(),- failed.len(),- pending.len()- );- for result in results {- let (status, failure) = if failed.contains(&result.tool_call_id.as_str()) {- (- ToolCallStatus::Error,- Some(ToolCallFailure { detail: None }),- )- } else {- (ToolCallStatus::Success, None)- };- if let Some(idx) = take_pending_by_id(pending, &result.tool_call_id) {- if let Some(DisplayItem::ToolCall {- result: slot,- status: status_slot,- failure: failure_slot,- ..- }) = items.get_mut(idx)- {- *slot = Some(result.content);- *status_slot = status;- *failure_slot = failure;- continue;- }- }- items.push(DisplayItem::ToolCall {- call_id: result.tool_call_id,- name: "tool".to_string(),- iteration: None,- args: None,- result: Some(result.content),- status,- failure,- ts: msg.ts.clone(),- });- }-}--/// The already-settled orphan row for `call_id` in the current turn — a result-/// that projected before any call named it.-fn settled_orphan_mut<'a>(- items: &'a mut [DisplayItem],- call_id: &str,-) -> Option<&'a mut DisplayItem> {- let turn_start = items- .iter()- .rposition(|item| matches!(item, DisplayItem::TurnBoundary { .. }))- .map_or(0, |idx| idx + 1);- items[turn_start..].iter_mut().find(|item| {- matches!(- item,- DisplayItem::ToolCall { call_id: id, name, result: Some(_), .. }- if id == call_id && name == "tool"- )- })-}--/// Remove and return the pending entry whose call id matches `id`, if any.-fn take_pending_by_id(pending: &mut VecDeque<(String, usize)>, id: &str) -> Option<usize> {- let pos = pending.iter().position(|(cid, _)| cid == id)?;- pending.remove(pos).map(|(_, idx)| idx)-}--fn project_compaction(marker: &CompactionMarker, items: &mut Vec<DisplayItem>) {- items.push(DisplayItem::Compaction {- replaced_count: 0,- kept_count: marker.replacement.len(),- ts: marker.ts.clone(),- request_id: marker.request_id.clone(),- });-}--/// Parse a tool call's raw argument string into JSON when possible; a-/// non-JSON string is wrapped so the frontend still receives structured args.-fn parse_tool_args(raw: &str) -> Option<serde_json::Value> {- let trimmed = raw.trim();- if trimmed.is_empty() {- return None;- }- match serde_json::from_str::<serde_json::Value>(trimmed) {- Ok(value) => Some(value),- Err(_) => Some(serde_json::Value::String(trimmed.to_string())),- }-}--/// Strip the injected scaffolding prefix from a user message, returning the-/// sanitized body only when a prefix was actually present (so the caller can-/// tag rather than mutate — the raw `content` is preserved alongside).-fn sanitize_user_content(content: &str) -> Option<String> {- let trimmed_start = content.trim_start();- if trimmed_start.starts_with(DATETIME_PREFIX)- || trimmed_start.starts_with(CHANNEL_CONTEXT_PREFIX)- {- // The injector prepends the scaffolding line followed by a blank line,- // then the user's actual text. Strip the first paragraph.- if let Some(idx) = content.find("\n\n") {- let body = content[idx + 2..].to_string();- return Some(body);- }- // No body after the prefix — the whole message was scaffolding.- return Some(String::new());- }- None-}diff --git a/crates/openhuman-core/src/threads/transcript_view/prompt_tools.rs b/crates/openhuman-core/src/threads/transcript_view/prompt_tools.rsdeleted file mode 100644index 1224032e1f..0000000000--- a/crates/openhuman-core/src/threads/transcript_view/prompt_tools.rs+++ /dev/null@@ -1,165 +0,0 @@-//! Prompt-guided (text-mode) tool turns in the display projection.-//!-//! A provider without native tool calling persists a tool round differently-//! from a native one, and the projection used to read only the native shape:-//!-//! - the assistant line that issued the calls carries **no** `tool_calls`-//! (the calls rode its visible text and were parsed out of it);-//! - the results come back as ONE `user` line, `[Tool results]` followed by a-//! `<tool_result id="…">…</tool_result>` block per call, not as `tool` lines;-//! - the turn's calls are recorded once, on the FINAL assistant line's-//! `tool_calls`, which is the answer rather than a line that called anything.-//!-//! Read naively that inverts the turn: every narration projected as a final-//! answer (non-interim, so the UI dropped it), the real answer projected as an-//! interim tool-calling step with every call of the turn hung after it, and-//! the `[Tool results]` line projected as something the user said. A reopened-//! thread then showed the answer twice and its tools after it — nothing like-//! the turn the user watched stream.-//!-//! This module recognises that shape so `project` can put each call right-//! after the narration that issued it, pair each result block to its call, and-//! stop re-attaching already-shown calls to the answer.--use std::collections::HashMap;--use tinyagents_session::transcript::{DisplayMessage, DisplayRecord};--/// The prefix `messages_to_text_mode_chat` / `coalesce_prompt_tool_results`-/// write on a folded tool-results user turn.-const TOOL_RESULTS_MARKER: &str = "[Tool results]";-const RESULT_OPEN: &str = "<tool_result";-const RESULT_CLOSE: &str = "</tool_result>";--/// One `<tool_result>` block of a `[Tool results]` user line.-#[derive(Debug, Clone, PartialEq, Eq)]-pub(super) struct PromptToolResult {- /// The call id, when the block carries one (`<tool_result id="…">`).- pub id: Option<String>,- pub body: String,-}--/// The result blocks of a `[Tool results]` user line, or `None` when the line-/// is not one. A marker with no parseable block still returns `Some(vec![])`:-/// it is tool plumbing either way and must never render as a user message.-pub(super) fn parse_tool_results(msg: &DisplayMessage) -> Option<Vec<PromptToolResult>> {- if msg.message.role != "user" {- return None;- }- let rest = msg- .message- .content- .trim_start()- .strip_prefix(TOOL_RESULTS_MARKER)?;- let mut blocks = Vec::new();- let mut cursor = rest;- while let Some(start) = cursor.find(RESULT_OPEN) {- let after_open = &cursor[start + RESULT_OPEN.len()..];- let Some(tag_end) = after_open.find('>') else {- break;- };- let id = attribute(&after_open[..tag_end], "id");- let body_and_rest = &after_open[tag_end + 1..];- let (body, next) = match body_and_rest.find(RESULT_CLOSE) {- Some(end) => (- &body_and_rest[..end],- &body_and_rest[end + RESULT_CLOSE.len()..],- ),- None => (body_and_rest, ""),- };- blocks.push(PromptToolResult {- id,- body: body.trim_matches('\n').to_string(),- });- cursor = next;- }- Some(blocks)-}--/// `name="value"` out of a tag's attribute text.-fn attribute(attrs: &str, name: &str) -> Option<String> {- let needle = format!("{name}=\"");- let start = attrs.find(&needle)? + needle.len();- let value = &attrs[start..];- let value = &value[..value.find('"')?];- (!value.is_empty()).then(|| value.to_string())-}--/// `(name, arguments)` of every call a file records, by call id, plus each-/// turn's call ids in issue order (for id-less result blocks).-#[derive(Debug, Default)]-pub(super) struct CallRegistry {- by_id: HashMap<String, (String, String)>,- by_turn: HashMap<Option<String>, Vec<String>>,-}--impl CallRegistry {- /// Index the calls every assistant line records (native per-line calls,- /// and the turn-level list a prompt-guided turn stamps on its answer).- pub(super) fn from_records(records: &[DisplayRecord]) -> Self {- let mut registry = Self::default();- for record in records {- let DisplayRecord::Message(msg) = record else {- continue;- };- if msg.message.role != "assistant" {- continue;- }- let Some(usage) = msg.turn_usage.as_ref() else {- continue;- };- for call in &usage.tool_calls {- if call.id.is_empty() || registry.by_id.contains_key(&call.id) {- continue;- }- registry- .by_id- .insert(call.id.clone(), (call.name.clone(), call.arguments.clone()));- registry- .by_turn- .entry(msg.request_id.clone())- .or_default()- .push(call.id.clone());- }- }- registry- }-- /// The calls a `[Tool results]` line answers, as `(id, name, arguments)`,- /// in block order. A block with an id resolves by it; an id-less block- /// takes the turn's next call not yet `emitted`. Unknown ids keep their id- /// with the generic name `tool`, so the result still lands on a row.- pub(super) fn calls_for(- &self,- request_id: &Option<String>,- blocks: &[PromptToolResult],- emitted: &std::collections::HashSet<String>,- ) -> Vec<(String, String, String)> {- let mut taken: Vec<String> = Vec::new();- let mut turn_order = self- .by_turn- .get(request_id)- .into_iter()- .flatten()- .filter(|id| !emitted.contains(*id));- blocks- .iter()- .map(|block| {- let id = match &block.id {- Some(id) => id.clone(),- None => turn_order- .find(|id| !taken.contains(id))- .cloned()- .unwrap_or_default(),- };- taken.push(id.clone());- let (name, arguments) = self- .by_id- .get(&id)- .cloned()- .unwrap_or_else(|| ("tool".to_string(), String::new()));- (id, name, arguments)- })- .collect()- }-}diff --git a/crates/openhuman-core/src/threads/transcript_view/prompt_tools_tests.rs b/crates/openhuman-core/src/threads/transcript_view/prompt_tools_tests.rsdeleted file mode 100644index f9aff93575..0000000000--- a/crates/openhuman-core/src/threads/transcript_view/prompt_tools_tests.rs+++ /dev/null@@ -1,147 +0,0 @@-//! Prompt-guided (text-mode) tool rounds in the display projection — see-//! `prompt_tools.rs`.--use super::project::project_records;-use super::types::DisplayItem;-use std::path::{Path, PathBuf};-use tempfile::TempDir;-use tinyagents_session::transcript::{self, read_transcript_display};--fn write_raw(workspace: &Path, stem: &str, thread_id: &str, body: &[&str]) -> PathBuf {- let path = transcript::resolve_keyed_transcript_path(workspace, stem).expect("resolve");- let mut buf = format!(- r#"{{"_meta":{{"version":1,"agent":"orchestrator","dispatcher":"xml","created":"2026-09-24T00:00:00Z","updated":"2026-09-24T00:00:10Z","turn_count":1,"input_tokens":1,"output_tokens":1,"cached_input_tokens":0,"charged_amount_usd":0.0,"thread_id":"{thread_id}"}}}}"#- );- buf.push('\n');- for line in body {- buf.push_str(line);- buf.push('\n');- }- std::fs::write(&path, buf).expect("write raw transcript");- path-}--/// A native turn: the calling line carries its own `tool_calls`.-fn native_turn_body() -> Vec<&'static str> {- vec![- r#"{"role":"user","content":"What's the weather in NYC?","request_id":"req-1"}"#,- r#"{"role":"assistant","content":"Let me check.","provider":"anthropic","model":"claude-x","usage":{"input":10,"output":5,"cached_input":0,"cost_usd":0.001},"ts":"2026-07-21T09:00:01Z","tool_calls":[{"id":"call-1","name":"get_weather","arguments":"{\"city\":\"NYC\"}"}],"iteration":1,"request_id":"req-1"}"#,- r#"{"role":"tool","content":"72F and sunny","id":"call-1","request_id":"req-1"}"#,- r#"{"role":"assistant","content":"It's 72F and sunny in NYC.","provider":"anthropic","model":"claude-x","usage":{"input":20,"output":8,"cached_input":0,"cost_usd":0.002},"ts":"2026-07-21T09:00:02Z","iteration":2,"request_id":"req-1"}"#,- ]-}--/// A prompt-guided (text-mode) turn, as `session_raw` actually records it: the-/// calling lines carry no `tool_calls`, each round's results are ONE-/// `[Tool results]` user line, and the turn's calls are stamped once on the-/// final answer line.-fn prompt_guided_turn_body(result_ids: bool) -> Vec<String> {- let block = |id: &str, body: &str| {- if result_ids {- format!("<tool_result id=\\\"{id}\\\">\\n{body}\\n</tool_result>")- } else {- format!("<tool_result>\\n{body}\\n</tool_result>")- }- };- vec![- r#"{"role":"user","content":"Check the config, then search.","request_id":"req-p"}"#.to_string(),- r#"{"role":"assistant","content":"Let me read the config first.","request_id":"req-p"}"#.to_string(),- format!(- r#"{{"role":"user","content":"[Tool results]\n{}","request_id":"req-p"}}"#,- block("call-read", "port = 8080")- ),- r#"{"role":"assistant","content":"Now I will search for the setting.","request_id":"req-p"}"#.to_string(),- format!(- r#"{{"role":"user","content":"[Tool results]\n{}","request_id":"req-p"}}"#,- block("call-grep", "config.toml:3: setting = on")- ),- r#"{"role":"assistant","content":"The setting is on.","provider":"openhuman","model":"m","usage":{"input":1,"output":1,"cached_input":0,"cost_usd":0.0},"tool_calls":[{"id":"call-read","name":"file_read","arguments":"{\"path\":\"/etc/config.toml\"}"},{"id":"call-grep","name":"grep","arguments":"{\"pattern\":\"setting\"}"}],"iteration":3,"ts":"2026-09-24T05:20:52Z","request_id":"req-p"}"#.to_string(),- ]-}--/// What a reader sees of a projected turn, in order.-fn outline(items: &[DisplayItem]) -> Vec<String> {- items- .iter()- .filter_map(|item| match item {- DisplayItem::UserMessage { content, .. } => Some(format!("user:{content}")),- DisplayItem::AssistantMessage {- content, interim, ..- } => Some(format!(- "{}:{content}",- if *interim { "narration" } else { "answer" }- )),- DisplayItem::ToolCall {- call_id,- name,- status,- result,- ..- } => Some(format!(- "tool:{call_id}:{name}:{status:?}:{}",- result.as_deref().unwrap_or("-")- )),- _ => None,- })- .collect()-}--/// The prompt-guided turn used to project inverted: both narrations as final-/// answers, the answer as an interim step with every call after it, and each-/// `[Tool results]` line as something the user said. A reopened thread showed-/// the answer twice with its tools below it.-#[test]-fn prompt_guided_turn_projects_like_a_native_one() {- let dir = TempDir::new().unwrap();- let body = prompt_guided_turn_body(true);- let body: Vec<&str> = body.iter().map(String::as_str).collect();- let path = write_raw(dir.path(), "300_orchestrator", "thr_p", &body);- let display = read_transcript_display(&path).unwrap();-- assert_eq!(- outline(&project_records(&display.records)),- vec![- "user:Check the config, then search.".to_string(),- "narration:Let me read the config first.".to_string(),- "tool:call-read:file_read:Success:port = 8080".to_string(),- "narration:Now I will search for the setting.".to_string(),- "tool:call-grep:grep:Success:config.toml:3: setting = on".to_string(),- "answer:The setting is on.".to_string(),- ]- );-}--#[test]-fn prompt_guided_results_without_ids_pair_in_issue_order() {- let dir = TempDir::new().unwrap();- let body = prompt_guided_turn_body(false);- let body: Vec<&str> = body.iter().map(String::as_str).collect();- let path = write_raw(dir.path(), "301_orchestrator", "thr_q", &body);- let display = read_transcript_display(&path).unwrap();-- let outline = outline(&project_records(&display.records));- assert_eq!(outline[2], "tool:call-read:file_read:Success:port = 8080");- assert_eq!(- outline[4],- "tool:call-grep:grep:Success:config.toml:3: setting = on"- );- assert_eq!(outline[5], "answer:The setting is on.");-}--/// A native turn records its calls on the line that made them; the answer-/// line's calls are only skipped when they were already placed.-#[test]-fn native_turn_projection_is_unchanged() {- let dir = TempDir::new().unwrap();- let path = write_raw(dir.path(), "302_orchestrator", "thr_n", &native_turn_body());- let display = read_transcript_display(&path).unwrap();- assert_eq!(- outline(&project_records(&display.records)),- vec![- "user:What's the weather in NYC?".to_string(),- "narration:Let me check.".to_string(),- "tool:call-1:get_weather:Success:72F and sunny".to_string(),- "answer:It's 72F and sunny in NYC.".to_string(),- ]- );-}diff --git a/crates/openhuman-core/src/threads/transcript_view/resolve.rs b/crates/openhuman-core/src/threads/transcript_view/resolve.rsdeleted file mode 100644index 7d506d704f..0000000000--- a/crates/openhuman-core/src/threads/transcript_view/resolve.rs+++ /dev/null@@ -1,249 +0,0 @@-//! Which files back a thread's transcript view, and in what order.-//!-//! Two things make this more than "every root whose `_meta.thread_id`-//! matches":-//!-//! - **Session generations.** A compaction seals generation `n` and opens-//! `{stem}.g{n+1}`, which inherits `_meta.created` and opens with the-//! retained message set rewritten. Ordering by `created` then path put-//! `X.g1` before `X` (and `.g10` before `.g2`), and concatenating every-//! generation rendered the retained rows twice. Generations are ordered by-//! the tinyagents `session_chain` instead, and [`drop_retained_rows`] removes-//! the rewritten prefix when a successor is projected.-//! - **Adopted legacy roots.** A pre-identity conversation's timestamped roots-//! are folded into the session file on first resume and left untouched on-//! disk, so once a session file exists they are duplicates of its head.-//!-//! Sub-agent files are discovered by `_meta.thread_id` as well as by the-//! legacy `{root_stem}__` prefix: a sub-agent's stem chains the parent's-//! *session key* (`{unix}_{agent}`), which for a session-identity thread is not-//! the root file's stem (`{thread}.{agent}` with digests), so the prefix alone-//! found none of them.--use std::collections::{HashMap, HashSet};-use std::fs;-use std::io::{BufRead, BufReader};-use std::path::{Path, PathBuf};--use tinyagents_session::transcript::{- self, DisplayMessage, DisplayRecord, FileTranscriptLocator, SessionRef, TranscriptLocator,-};--const LOG_PREFIX: &str = "[threads][transcript][resolve]";--/// The `_meta` header fields resolution needs, read from a file's first line-/// only (the full reader parses the whole file).-#[derive(Debug, Default, Clone)]-pub(super) struct HeadMeta {- pub(super) thread_id: Option<String>,- pub(super) agent_id: Option<String>,- pub(super) session_id: Option<String>,-}--/// Read the first-line `_meta` header of a transcript. `None` when the file-/// cannot be read or does not start with a meta line.-pub(super) fn read_head_meta(path: &Path) -> Option<HeadMeta> {- let file = fs::File::open(path).ok()?;- let mut first = String::new();- BufReader::new(file).read_line(&mut first).ok()?;- let value: serde_json::Value = serde_json::from_str(first.trim()).ok()?;- let meta = value.get("_meta")?;- let field = |key: &str| {- meta.get(key)- .and_then(serde_json::Value::as_str)- .map(str::to_string)- };- Some(HeadMeta {- thread_id: field("thread_id"),- agent_id: field("agent_id"),- session_id: field("session_id"),- })-}--/// Resolve the root generations and sub-agent siblings backing `thread_id`.-/// `None` when the thread has no root transcript yet.-pub fn resolve_files(- workspace_dir: &Path,- thread_id: &str,-) -> Option<(Vec<PathBuf>, Vec<PathBuf>)> {- let found = transcript::find_root_transcripts_for_thread(workspace_dir, thread_id);- if found.is_empty() {- return None;- }- let raw_dir = found[0].parent()?.to_path_buf();- let roots = order_root_files(workspace_dir, thread_id, found);- let subs = discover_subagent_files(&raw_dir, thread_id, &roots);- log::debug!(- "{LOG_PREFIX} thread={thread_id} roots={} subagent_files={}",- roots.len(),- subs.len()- );- Some((roots, subs))-}--fn file_name(path: &Path) -> Option<&std::ffi::OsStr> {- path.file_name()-}--/// Order the thread's roots: each session's generations oldest-first (from-/// `session_chain`), legacy (pre-identity) roots dropped once a session file-/// exists. A thread with no session file keeps the scan's order unchanged.-fn order_root_files(workspace_dir: &Path, thread_id: &str, roots: Vec<PathBuf>) -> Vec<PathBuf> {- let metas: Vec<(PathBuf, HeadMeta)> = roots- .into_iter()- .map(|path| {- let meta = read_head_meta(&path).unwrap_or_default();- (path, meta)- })- .collect();- if !metas.iter().any(|(_, meta)| meta.session_id.is_some()) {- return metas.into_iter().map(|(path, _)| path).collect();- }-- let locator = FileTranscriptLocator::new(workspace_dir);- let mut seen: HashSet<std::ffi::OsString> = HashSet::new();- let mut ordered = Vec::new();- let mut dropped_legacy = 0usize;- for (path, meta) in &metas {- if meta.session_id.is_none() {- dropped_legacy += 1;- continue;- }- let Some(name) = file_name(path) else {- continue;- };- if seen.contains(name) {- continue;- }- let chain: Vec<PathBuf> = meta- .agent_id- .as_deref()- .map(|agent_id| {- let session = SessionRef::scoped(thread_id, agent_id);- locator- .session_chain(&session)- .iter()- .filter_map(|generation| {- transcript::resolve_keyed_transcript_path(- workspace_dir,- &transcript::session_stem(generation),- )- .ok()- })- .collect()- })- .unwrap_or_default();- if chain.iter().any(|link| file_name(link) == Some(name)) {- for link in chain {- if let Some(link_name) = file_name(&link) {- if seen.insert(link_name.to_os_string()) {- ordered.push(link);- }- }- }- } else {- // A session file this thread's own identity does not derive (a- // different key scheme): keep it where the scan put it.- seen.insert(name.to_os_string());- ordered.push(path.clone());- }- }- if dropped_legacy > 0 {- log::debug!(- "{LOG_PREFIX} thread={thread_id} dropped {dropped_legacy} adopted legacy root(s) \- in favour of the session chain"- );- }- ordered-}--/// Every sub-agent (`__`) transcript of this thread in `raw_dir`: those whose-/// stem extends a root stem (legacy layout), plus those whose `_meta.thread_id`-/// names the thread (session-identity layout). Sorted by path.-fn discover_subagent_files(raw_dir: &Path, thread_id: &str, roots: &[PathBuf]) -> Vec<PathBuf> {- let prefixes: Vec<String> = roots- .iter()- .filter_map(|root| root.file_stem().and_then(|stem| stem.to_str()))- .map(|stem| format!("{stem}__"))- .collect();- let entries = match fs::read_dir(raw_dir) {- Ok(entries) => entries,- Err(error) => {- log::debug!(- "{LOG_PREFIX} subagent discovery read_dir failed dir={} error={error}",- raw_dir.display()- );- return Vec::new();- }- };- let mut paths: Vec<PathBuf> = entries- .flatten()- .map(|entry| entry.path())- .filter(|path| path.extension().and_then(|ext| ext.to_str()) == Some("jsonl"))- .filter(|path| {- let Some(stem) = path.file_stem().and_then(|stem| stem.to_str()) else {- return false;- };- if !stem.contains("__") {- return false;- }- prefixes.iter().any(|prefix| stem.starts_with(prefix))- || read_head_meta(path)- .and_then(|meta| meta.thread_id)- .is_some_and(|id| id == thread_id)- })- .collect();- paths.sort();- paths-}--/// Identity of one message row for cross-generation de-duplication.-type RowKey = (String, String, Option<String>, Option<String>);--fn row_key(msg: &DisplayMessage) -> RowKey {- (- msg.message.role.clone(),- msg.message.content.clone(),- msg.message.id.clone(),- msg.request_id.clone(),- )-}--/// Multiset of the message rows of one generation, for [`drop_retained_rows`].-pub(super) fn generation_rows(records: &[DisplayRecord]) -> HashMap<RowKey, usize> {- let mut rows = HashMap::new();- for record in records {- if let DisplayRecord::Message(msg) = record {- *rows.entry(row_key(msg)).or_insert(0) += 1;- }- }- rows-}--/// Split a successor generation's records into `(new records, retained rows)`.-///-/// A successor opens with the retained set rewritten verbatim (same role,-/// content, id and — because retained rows keep their own correlation id —-/// the same `request_id`). Each such row consumes one occurrence from the-/// predecessor's multiset, so a genuinely repeated row beyond what the-/// predecessor held still renders.-pub(super) fn drop_retained_rows(- records: &[DisplayRecord],- mut predecessor: HashMap<RowKey, usize>,-) -> (Vec<DisplayRecord>, Vec<DisplayMessage>) {- let mut kept = Vec::with_capacity(records.len());- let mut retained = Vec::new();- for record in records {- if let DisplayRecord::Message(msg) = record {- if let Some(count) = predecessor.get_mut(&row_key(msg)) {- if *count > 0 {- *count -= 1;- retained.push((**msg).clone());- continue;- }- }- }- kept.push(record.clone());- }- (kept, retained)-}diff --git a/crates/openhuman-core/src/threads/transcript_view/subagents.rs b/crates/openhuman-core/src/threads/transcript_view/subagents.rsdeleted file mode 100644index df5656537a..0000000000--- a/crates/openhuman-core/src/threads/transcript_view/subagents.rs+++ /dev/null@@ -1,449 +0,0 @@-//! Sub-agent trails: project each delegated run's sibling transcript and-//! place it next to the tool call that spawned it.-//!-//! The transcript records no explicit delegation-call → file link: a child's-//! `_meta` carries its own `task_id`, the parent's rows carry only tool-call-//! ids, and neither names the other. So correlation is by evidence, in order:-//!-//! 1. **Turn** — the child's spawn time (the leading unix seconds of its stem-//! suffix) against the parent turns' commit timestamps-//! ([`anchor_request_id`]).-//! 2. **Call** — within that turn, the first unclaimed tool call that targets-//! the child's agent (`delegate_{agent}`, an `agent_id` argument, …), else-//! the first unclaimed delegation-shaped call.-//!-//! An uncorrelated child lands at the end of its turn (or of the list when-//! there are no turns) instead of after every root item, which is where all-//! sub-agents used to go.--use std::path::{Path, PathBuf};--use tinyagents_session::transcript::{self, DisplayRecord};--use super::project::{parse_native_tool_envelope, project_records};-use super::types::{DisplayItem, SubagentStatus, ToolCallStatus};--const LOG_PREFIX: &str = "[threads][transcript][subagents]";--/// Max sub-agent nesting depth the projection descends; bounded so a worker-/// that itself delegates still surfaces, without unbounded fan-out.-const MAX_SUBAGENT_DEPTH: usize = 3;--/// Prefix the delegation runner puts on a result it gave up on.-const INCOMPLETE_MARKER: &str = "[SUBAGENT_INCOMPLETE]";--/// Prefix of an async spawn's acknowledgement — success of the *spawn*, not-/// of the run, so it says nothing about the child's terminal state.-const ASYNC_ACCEPTED_PREFIX: &str = "Accepted async sub-agent";--/// Argument keys a spawn/delegate tool uses to name its target agent.-const TARGET_ARG_KEYS: &[&str] = &["agent_id", "agent", "subagent", "subagent_type", "target"];--/// A projected child run awaiting placement.-struct ChildRun {- /// Unix seconds the child was spawned at, from its stem.- spawn_unix: Option<i64>,- agent_id: Option<String>,- /// Spawn task id, when the transcript recorded one — the key the run- /// ledger's `AgentRunUpsert.id` uses, so it's also the key for the exact- /// `parentCallId` correlation in [`find_exact_spawning_call`].- task_id: Option<String>,- item: DisplayItem,- /// The child's own terminal evidence, before the spawning call is known.- own_state: OwnState,-}--#[derive(Clone, Copy, PartialEq, Eq)]-enum OwnState {- Completed,- Interrupted,- Unknown,-}--/// Place every direct child of the root (`__`-once stems) into `items`.-/// `segments` are the root turns' `(request_id, commit unix)` pairs.-pub(super) fn attach(- items: &mut Vec<DisplayItem>,- sub_paths: &[PathBuf],- segments: &[(String, i64)],- workspace_dir: Option<&Path>,-) {- let children = build_children(sub_paths, None, 0, workspace_dir);- place(items, children, segments, workspace_dir);-}--/// Project the direct children of `parent_stem` (or of the roots, when-/// `None`), recursing into their own children.-fn build_children(- sub_paths: &[PathBuf],- parent_stem: Option<&str>,- depth: usize,- workspace_dir: Option<&Path>,-) -> Vec<ChildRun> {- if depth >= MAX_SUBAGENT_DEPTH {- return Vec::new();- }- let mut children = Vec::new();- for path in sub_paths {- let Some(stem) = path.file_stem().and_then(|s| s.to_str()) else {- continue;- };- let suffix = match parent_stem {- Some(parent) => match stem.strip_prefix(parent).and_then(|r| r.strip_prefix("__")) {- Some(rest) if !rest.contains("__") => rest,- _ => continue,- },- // A root's direct child has exactly one `__` separator.- None => match stem.split_once("__") {- Some((_, rest)) if !rest.contains("__") => rest,- _ => continue,- },- };- if let Some(child) = build_child(path, stem, suffix, sub_paths, depth, workspace_dir) {- children.push(child);- }- }- children.sort_by_key(|child| child.spawn_unix);- children-}--fn build_child(- path: &Path,- stem: &str,- suffix: &str,- sub_paths: &[PathBuf],- depth: usize,- workspace_dir: Option<&Path>,-) -> Option<ChildRun> {- let display = match transcript::read_transcript_display(path) {- Ok(display) => display,- Err(err) => {- log::warn!(- "{LOG_PREFIX} failed to read sub-agent transcript {}: {err}",- path.display()- );- return None;- }- };- let own_state = own_state(&display.records);- let mut items = project_records(&display.records);- let grandchildren = build_children(sub_paths, Some(stem), depth + 1, workspace_dir);- place(- &mut items,- grandchildren,- &turn_segments(&display.records),- workspace_dir,- );-- let task_id = display.meta.task_id.clone().filter(|id| !id.is_empty());- let agent_id = display- .meta- .agent_id- .clone()- .or_else(|| Some(display.meta.agent_name.clone()))- .filter(|id| !id.is_empty());- let id = task_id.clone().unwrap_or_else(|| suffix.to_string());- let spawn_unix = child_spawn_unix(suffix);- // The spawn timestamp encoded in the sub-agent's own file stem (used- // above to anchor it to a parent turn) doubles as this item's `ts` —- // sub-agent transcripts carry no back-link to a delegating request, so- // there is no per-message `ts` to inherit the way the root projector- // pulls one from `DisplayMessage.ts`.- let ts = spawn_unix- .and_then(|unix| chrono::DateTime::from_timestamp(unix, 0).map(|dt| dt.to_rfc3339()));- Some(ChildRun {- spawn_unix,- agent_id: agent_id.clone(),- task_id: task_id.clone(),- item: DisplayItem::Subagent {- id,- agent_id,- task_id,- call_id: None,- status: SubagentStatus::Running,- request_id: None,- ts,- items,- },- own_state,- })-}--/// Exact correlation: the run ledger's `AgentRunUpsert.metadata.parentCallId`-/// for this task (stamped by `progress_bridge`'s `SubagentSpawned` handling),-/// resolved to the unclaimed [`DisplayItem::ToolCall`] with that `call_id`.-///-/// Preferred over [`find_spawning_call`]'s timestamp/target-argument-/// heuristic whenever it resolves — the ledger has the actual call id, no-/// guessing required. `None` on any miss (no workspace, no task id, no-/// ledger row, no matching/unclaimed call), so callers fall back to the-/// heuristic unconditionally.-fn find_exact_spawning_call(- items: &[DisplayItem],- claimed: &[bool],- task_id: Option<&str>,- workspace_dir: Option<&Path>,-) -> Option<usize> {- let workspace_dir = workspace_dir?;- let task_id = task_id?;- let run = tinyagents_session::run_ledger::get_agent_run(workspace_dir, task_id)- .ok()- .flatten()?;- let parent_call_id = run.metadata.get("parentCallId")?.as_str()?;- items- .iter()- .enumerate()- .find_map(|(index, item)| match item {- DisplayItem::ToolCall { call_id, .. }- if !claimed[index] && call_id == parent_call_id =>- {- Some(index)- }- _ => None,- })-}--/// What the child's own transcript says about how it ended.-fn own_state(records: &[DisplayRecord]) -> OwnState {- let last = records.iter().rev().find_map(|record| match record {- DisplayRecord::Message(msg) if msg.message.role != "system" => Some(msg),- _ => None,- });- match last {- Some(msg) if msg.interrupted => OwnState::Interrupted,- Some(msg)- if msg.message.role == "assistant"- && parse_native_tool_envelope(&msg.message.content)- .is_none_or(|(_, calls)| calls.is_empty()) =>- {- OwnState::Completed- }- _ => OwnState::Unknown,- }-}--/// Insert `children` into `items`, each after its correlated spawning call-/// (claimed at most once), else at the end of its anchored turn.-fn place(- items: &mut Vec<DisplayItem>,- children: Vec<ChildRun>,- segments: &[(String, i64)],- workspace_dir: Option<&Path>,-) {- if children.is_empty() {- return;- }- let mut claimed = vec![false; items.len()];- // (insert position, order) — applied back-to-front afterwards.- let mut inserts: Vec<(usize, usize, DisplayItem)> = Vec::new();- for (order, mut child) in children.into_iter().enumerate() {- let request_id = anchor_request_id(child.spawn_unix, segments);- let (start, end) = turn_range(items, request_id.as_deref());- let pick =- find_exact_spawning_call(items, &claimed, child.task_id.as_deref(), workspace_dir)- .or_else(|| {- find_spawning_call(items, &claimed, start, end, child.agent_id.as_deref())- });- let (position, call) = match pick {- Some(index) => {- claimed[index] = true;- (index + 1, Some(index))- }- None => (end, None),- };- let (call_id, call_status, call_result) = match call.and_then(|i| items.get(i)) {- Some(DisplayItem::ToolCall {- call_id,- status,- result,- ..- }) => (Some(call_id.clone()), Some(*status), result.clone()),- _ => (None, None, None),- };- let status = derive_status(child.own_state, call_status, call_result.as_deref());- if let DisplayItem::Subagent {- id,- call_id: call_slot,- status: status_slot,- request_id: request_slot,- ..- } = &mut child.item- {- log::debug!(- "{LOG_PREFIX} subagent id={id} agent={:?} request_id={request_id:?} call_id={call_id:?} status={status:?}",- child.agent_id- );- *call_slot = call_id;- *status_slot = status;- *request_slot = request_id;- }- inserts.push((position, order, child.item));- }- // Back-to-front keeps earlier positions valid; for one position, the- // later child is inserted first so spawn order is preserved.- inserts.sort_by(|a, b| b.0.cmp(&a.0).then(b.1.cmp(&a.1)));- for (position, _, item) in inserts {- items.insert(position.min(items.len()), item);- }-}--/// Terminal state from the spawning call's outcome and the child's own-/// transcript. A failed or incomplete delegation wins; then the child's own-/// ending; then a settled synchronous call.-fn derive_status(- own: OwnState,- call_status: Option<ToolCallStatus>,- call_result: Option<&str>,-) -> SubagentStatus {- let result = call_result.map(str::trim_start).unwrap_or_default();- if call_status == Some(ToolCallStatus::Error) || result.starts_with(INCOMPLETE_MARKER) {- return SubagentStatus::Failed;- }- match own {- OwnState::Interrupted => SubagentStatus::Interrupted,- OwnState::Completed => SubagentStatus::Completed,- OwnState::Unknown- if call_status == Some(ToolCallStatus::Success)- && !result.starts_with(ASYNC_ACCEPTED_PREFIX) =>- {- SubagentStatus::Completed- }- OwnState::Unknown => SubagentStatus::Running,- }-}--/// `[start, end)` of `request_id`'s items (after its boundary, up to the next-/// one); the whole list when the turn is unknown.-fn turn_range(items: &[DisplayItem], request_id: Option<&str>) -> (usize, usize) {- let Some(request_id) = request_id else {- return (0, items.len());- };- let Some(boundary) = items.iter().position(- |item| matches!(item, DisplayItem::TurnBoundary { request_id: rid } if rid == request_id),- ) else {- return (0, items.len());- };- let end = items[boundary + 1..]- .iter()- .position(|item| matches!(item, DisplayItem::TurnBoundary { .. }))- .map_or(items.len(), |offset| boundary + 1 + offset);- (boundary + 1, end)-}--fn find_spawning_call(- items: &[DisplayItem],- claimed: &[bool],- start: usize,- end: usize,- agent_id: Option<&str>,-) -> Option<usize> {- let candidates = || {- (start..end).filter_map(|index| match &items[index] {- DisplayItem::ToolCall { name, args, .. } if !claimed[index] => {- Some((index, name.as_str(), args.as_ref()))- }- _ => None,- })- };- if let Some(agent_id) = agent_id {- if let Some((index, ..)) =- candidates().find(|(_, name, args)| call_targets_agent(name, *args, agent_id))- {- return Some(index);- }- }- candidates()- .find(|(_, name, _)| is_delegation_tool(name))- .map(|(index, ..)| index)-}--/// Whether a tool call names `agent_id` as its delegation target.-fn call_targets_agent(name: &str, args: Option<&serde_json::Value>, agent_id: &str) -> bool {- let agent = agent_id.to_ascii_lowercase();- let name = name.to_ascii_lowercase();- if name == format!("delegate_{agent}") || name == format!("delegate_to_{agent}") {- return true;- }- let named_in_args = args- .and_then(serde_json::Value::as_object)- .is_some_and(|args| {- TARGET_ARG_KEYS.iter().any(|key| {- args.get(*key)- .and_then(serde_json::Value::as_str)- .is_some_and(|value| value.eq_ignore_ascii_case(&agent))- })- });- if named_in_args {- return true;- }- // Alias tools such as `plan` → `planner`. The length floor keeps a- // short generic tool name from matching an agent by accident.- let stripped = name- .strip_prefix("delegate_to_")- .or_else(|| name.strip_prefix("delegate_"))- .unwrap_or(&name);- stripped.len() >= 5 && agent.starts_with(stripped)-}--fn is_delegation_tool(name: &str) -> bool {- name.starts_with("delegate") || name.starts_with("spawn_")-}--/// The turns' `(request_id, commit unix)` pairs, in file order: the last-/// parseable timestamp of each `request_id` run.-///-/// Every stamped row of a turn carries the turn's *commit* time (the writer-/// stamps it when the turn is appended), so this is when the turn ended, not-/// when it began.-pub(super) fn turn_segments(records: &[DisplayRecord]) -> Vec<(String, i64)> {- let mut segments: Vec<(String, i64)> = Vec::new();- for record in records {- let DisplayRecord::Message(msg) = record else {- continue;- };- let (Some(rid), Some(ts)) = (msg.request_id.as_deref(), msg.ts.as_deref()) else {- continue;- };- let Some(unix) = parse_rfc3339_unix(ts) else {- continue;- };- match segments.last_mut() {- Some((last, end)) if last == rid => *end = (*end).max(unix),- _ => segments.push((rid.to_string(), unix)),- }- }- segments-}--/// Extract a sub-agent's spawn unix timestamp (seconds) from its stem suffix-/// (`{unix}_{nanos}_{agent}…`). `None` for non-numeric legacy stems.-fn child_spawn_unix(stem_suffix: &str) -> Option<i64> {- stem_suffix- .split('_')- .next()- .and_then(|s| s.parse::<i64>().ok())-}--fn parse_rfc3339_unix(ts: &str) -> Option<i64> {- chrono::DateTime::parse_from_rfc3339(ts)- .ok()- .map(|dt| dt.timestamp())-}--/// Anchor a sub-agent to the turn that was running at `child_unix`: the first-/// turn whose commit time is at or after the spawn.-///-/// Fallbacks: no segments → `None` (unanchored); unknown spawn time, or a-/// spawn after every recorded commit (a turn still in flight) → the newest-/// turn.-fn anchor_request_id(child_unix: Option<i64>, segments: &[(String, i64)]) -> Option<String> {- let last = segments.last()?;- let Some(child_unix) = child_unix else {- return Some(last.0.clone());- };- segments- .iter()- .find(|(_, end)| *end >= child_unix)- .or(Some(last))- .map(|(rid, _)| rid.clone())-}diff --git a/crates/openhuman-core/src/threads/transcript_view/transcript_ordering_tests.rs b/crates/openhuman-core/src/threads/transcript_view/transcript_ordering_tests.rsdeleted file mode 100644index 7f8f6e46e5..0000000000--- a/crates/openhuman-core/src/threads/transcript_view/transcript_ordering_tests.rs+++ /dev/null@@ -1,566 +0,0 @@-//! Turn-ordering tests for the transcript view that go through the **real-//! writer** (`append_transcript_turn`) rather than hand-built JSONL: tool-call-//! de-duplication, tool-result unwrapping, per-step iterations, sub-agent-//! placement, and compaction-generation chains.--use super::project::{project_records, project_thread, resolve_files};-use super::types::{DisplayItem, SubagentStatus, ToolCallStatus};-use std::path::{Path, PathBuf};-use tempfile::TempDir;-use tinyagents_session::transcript::{- self, read_transcript, read_transcript_display, SessionRef, TranscriptMessage, TranscriptMeta,- TranscriptToolCall, TurnUsage,-};--fn meta(thread_id: &str, session_id: Option<String>, parent: Option<String>) -> TranscriptMeta {- TranscriptMeta {- session_id,- parent_session_id: parent,- agent_name: "orchestrator".into(),- agent_id: Some("orchestrator".into()),- agent_type: Some("root".into()),- dispatcher: "native".into(),- provider: Some("anthropic".into()),- model: Some("claude-x".into()),- created: "2023-11-14T22:00:00+00:00".into(),- updated: "2023-11-14T22:00:00+00:00".into(),- turn_count: 1,- prefix_message_count: None,- input_tokens: 0,- output_tokens: 0,- cached_input_tokens: 0,- charged_amount_usd: 0.0,- thread_id: Some(thread_id.into()),- task_id: None,- }-}--fn rfc3339(unix: i64) -> String {- chrono::DateTime::from_timestamp(unix, 0)- .unwrap()- .to_rfc3339()-}--fn usage(iteration: u32, unix: i64, tool_calls: Vec<TranscriptToolCall>) -> TurnUsage {- TurnUsage {- provider: "anthropic".into(),- model: "claude-x".into(),- usage: transcript::MessageUsage {- input: 10,- output: 5,- cached_input: 0,- context_window: 0,- cost_usd: 0.001,- },- ts: rfc3339(unix),- reasoning_content: None,- tool_calls,- iteration,- }-}--fn call(id: &str, name: &str, arguments: &str) -> TranscriptToolCall {- TranscriptToolCall {- id: id.into(),- name: name.into(),- arguments: arguments.into(),- extra_content: None,- }-}--/// An assistant row as the native dialect persists it: the provider replay-/// envelope, with its reasoning in `extra_metadata`.-fn envelope(content: &str, calls: &[(&str, &str, &str)], reasoning: &str) -> TranscriptMessage {- let calls: Vec<serde_json::Value> = calls- .iter()- .map(|(id, name, args)| serde_json::json!({"id": id, "name": name, "arguments": args}))- .collect();- let mut row = TranscriptMessage::assistant(- serde_json::json!({"content": content, "tool_calls": calls}).to_string(),- );- row.extra_metadata = Some(serde_json::json!({ "reasoning_content": reasoning }));- row-}--/// A tool-result row as the native dialect persists it: wrapped.-fn tool_result(id: &str, output: &str) -> TranscriptMessage {- let mut row = TranscriptMessage::new(- "tool",- serde_json::json!({"tool_call_id": id, "content": output}).to_string(),- );- row.id = Some(id.into());- row-}--fn final_answer(text: &str, reasoning: &str) -> TranscriptMessage {- let mut row = TranscriptMessage::assistant(text);- row.extra_metadata = Some(serde_json::json!({ "reasoning_content": reasoning }));- row-}--/// One two-step tool turn: step 1 narrates and calls `get_weather`, step 2-/// calls two tools in parallel with no narration, step 3 answers.-fn weather_turn() -> Vec<TranscriptMessage> {- vec![- TranscriptMessage::new("system", "policy"),- TranscriptMessage::new("user", "Weather in NYC and SF?"),- envelope(- "Let me check.",- &[("c1", "get_weather", r#"{"city":"NYC"}"#)],- "think one",- ),- tool_result("c1", "72F"),- envelope(- "",- &[- ("c2", "get_weather", r#"{"city":"SF"}"#),- ("c3", "web_search", r#"{"q":"sf fog"}"#),- ],- "think two",- ),- tool_result("c2", "60F"),- tool_result("c3", "foggy"),- final_answer("NYC 72F, SF 60F and foggy.", "think three"),- ]-}--fn write_turn(path: &Path, rows: &[TranscriptMessage], turn_usage: &TurnUsage) {- transcript::append_transcript_turn(- path,- &[],- rows,- &meta("thr_w", None, None),- Some(turn_usage),- Some("req-1"),- )- .unwrap();-}--fn assert_weather_projection(items: &[DisplayItem]) {- let tools: Vec<(&str, u32, &str, ToolCallStatus)> = items- .iter()- .filter_map(|item| match item {- DisplayItem::ToolCall {- call_id,- iteration,- result,- status,- ..- } => Some((- call_id.as_str(),- iteration.unwrap_or_default(),- result.as_deref().unwrap_or_default(),- *status,- )),- _ => None,- })- .collect();- assert_eq!(- tools,- vec![- ("c1", 1, "72F", ToolCallStatus::Success),- ("c2", 2, "60F", ToolCallStatus::Success),- ("c3", 2, "foggy", ToolCallStatus::Success),- ],- "each call once, settled, with its unwrapped output: {items:#?}"- );-- let answers: Vec<(&str, bool, Option<u32>)> = items- .iter()- .filter_map(|item| match item {- DisplayItem::AssistantMessage {- content,- interim,- iteration,- ..- } => Some((content.as_str(), *interim, *iteration)),- _ => None,- })- .collect();- assert_eq!(- answers,- vec![- ("Let me check.", true, Some(1)),- ("NYC 72F, SF 60F and foggy.", false, Some(3)),- ]- );-- // Each reasoning block carries the iteration of the step it precedes.- let reasoning: Vec<(&str, Option<u32>)> = items- .iter()- .filter_map(|item| match item {- DisplayItem::Reasoning { text, iteration } => Some((text.as_str(), *iteration)),- _ => None,- })- .collect();- assert_eq!(- reasoning,- vec![- ("think one", Some(1)),- ("think two", Some(2)),- ("think three", Some(3)),- ]- );-}--/// The shape every turn written before this fix has on disk: the turn's-/// aggregate tool outcomes were copied onto the usage of the final answer,-/// which the writer then stamped as that row's `tool_calls`.-#[test]-fn real_writer_turn_with_aggregate_usage_calls_projects_each_call_once() {- let dir = TempDir::new().unwrap();- let path = transcript::resolve_keyed_transcript_path(dir.path(), "1_orchestrator").unwrap();- let aggregate = vec![- call("c1", "get_weather", r#"{"city":"NYC"}"#),- call("c2", "get_weather", r#"{"city":"SF"}"#),- call("c3", "web_search", r#"{"q":"sf fog"}"#),- ];- write_turn(&path, &weather_turn(), &usage(3, 1_700_000_000, aggregate));-- let raw = std::fs::read_to_string(&path).unwrap();- assert!(- raw.lines()- .any(|line| line.contains("NYC 72F") && line.contains("\"tool_calls\"")),- "precondition: the legacy final answer row carries the duplicated calls"- );- let display = read_transcript_display(&path).unwrap();- assert_weather_projection(&project_records(&display.records));-}--/// The shape the codec writes now: usage without tool calls. Every step is-/// also stamped with its own iteration by the writer.-#[test]-fn real_writer_turn_projects_steps_in_order() {- let dir = TempDir::new().unwrap();- let path = transcript::resolve_keyed_transcript_path(dir.path(), "2_orchestrator").unwrap();- write_turn(&path, &weather_turn(), &usage(3, 1_700_000_000, Vec::new()));-- let raw = std::fs::read_to_string(&path).unwrap();- assert!(- !raw.lines()- .any(|line| line.contains("NYC 72F") && line.contains("\"tool_calls\"")),- "the final answer row carries no tool calls"- );- let display = read_transcript_display(&path).unwrap();- assert_weather_projection(&project_records(&display.records));-}--/// Only the native `{tool_call_id, content}` wrapper is unwrapped; a tool-/// whose real output is JSON with other keys is shown verbatim.-#[test]-fn tool_output_that_is_not_the_replay_wrapper_is_kept_verbatim() {- let dir = TempDir::new().unwrap();- let path = transcript::resolve_keyed_transcript_path(dir.path(), "3_orchestrator").unwrap();- let mut rows = vec![- TranscriptMessage::new("user", "go"),- envelope("", &[("c1", "fetch_json", "{}")], ""),- ];- let mut own_json = TranscriptMessage::new("tool", r#"{"content":"x","status":200}"#);- own_json.id = Some("c1".into());- rows.push(own_json);- rows.push(final_answer("done", ""));- write_turn(&path, &rows, &usage(2, 1_700_000_000, Vec::new()));-- let display = read_transcript_display(&path).unwrap();- let result = project_records(&display.records)- .into_iter()- .find_map(|item| match item {- DisplayItem::ToolCall { result, .. } => result,- _ => None,- })- .expect("tool result projected");- assert_eq!(result, r#"{"content":"x","status":200}"#);-}--/// Write a session-identity root for `thread_id` (the stem the host binds via-/// `SessionRef::scoped`) and return its path.-fn session_root(workspace: &Path, thread_id: &str) -> (SessionRef, PathBuf) {- let session = SessionRef::scoped(thread_id, "orchestrator");- let path =- transcript::resolve_keyed_transcript_path(workspace, &transcript::session_stem(&session))- .unwrap();- (session, path)-}--/// A session-identity root is named `{thread}.{agent}` (with digests) while a-/// sub-agent's file chains the parent's *session key* (`{unix}_{agent}…`), so-/// prefix discovery never found it. It is discovered by `_meta.thread_id`,-/// placed right after the call that spawned it, and keyed by its task id.-#[test]-fn subagent_of_a_session_root_is_discovered_and_placed_after_its_spawning_call() {- let dir = TempDir::new().unwrap();- let thread_id = "thr_sub_place";- let (session, root) = session_root(dir.path(), thread_id);- let root_meta = meta(thread_id, Some(session.session_id()), None);-- let turn1 = vec![- TranscriptMessage::new("user", "hi"),- final_answer("hello", ""),- ];- transcript::append_transcript_turn(- &root,- &[],- &turn1,- &root_meta,- Some(&usage(1, 1_700_000_000, Vec::new())),- Some("req-1"),- )- .unwrap();- let persisted = read_transcript(&root).unwrap().messages;- let mut turn2 = persisted.clone();- turn2.extend([- TranscriptMessage::new("user", "research bali"),- envelope(- "On it.",- &[- ("c-fetch", "web_fetch", r#"{"url":"https://x"}"#),- ("c-research", "research", r#"{"prompt":"bali"}"#),- ],- "",- ),- tool_result("c-fetch", "page"),- tool_result("c-research", "Bali is great."),- final_answer("Here's the plan.", ""),- ]);- transcript::append_transcript_turn(- &root,- &persisted,- &turn2,- &root_meta,- Some(&usage(2, 1_700_000_200, Vec::new())),- Some("req-2"),- )- .unwrap();-- // Spawned during turn 2 (after turn 1 committed at …000, before …200).- let child_stem = "1699999990_orchestrator_thread-x__1700000100_000000001_researcher_sub-abc";- let child = transcript::resolve_keyed_transcript_path(dir.path(), child_stem).unwrap();- let mut child_meta = meta(thread_id, None, None);- child_meta.agent_name = "researcher".into();- child_meta.agent_id = Some("researcher".into());- child_meta.agent_type = Some("subagent".into());- child_meta.task_id = Some("sub-abc-123".into());- transcript::write_transcript(- &child,- &[- TranscriptMessage::new("user", "bali"),- TranscriptMessage::assistant("Bali is great."),- ],- &child_meta,- None,- )- .unwrap();-- let (_, subs) = resolve_files(dir.path(), thread_id).expect("thread resolves");- assert_eq!(subs, vec![child.clone()], "discovered by _meta.thread_id");-- let projected = project_thread(dir.path(), thread_id).expect("project");- let items = &projected.items;- let research_call = items- .iter()- .position(- |item| matches!(item, DisplayItem::ToolCall { call_id, .. } if call_id == "c-research"),- )- .expect("research call projected");- match &items[research_call + 1] {- DisplayItem::Subagent {- id,- agent_id,- task_id,- call_id,- status,- request_id,- items,- ..- } => {- assert_eq!(id, "sub-abc-123");- assert_eq!(agent_id.as_deref(), Some("researcher"));- assert_eq!(task_id.as_deref(), Some("sub-abc-123"));- assert_eq!(call_id.as_deref(), Some("c-research"));- assert_eq!(*status, SubagentStatus::Completed);- assert_eq!(request_id.as_deref(), Some("req-2"));- assert!(items.iter().any(|inner| matches!(- inner,- DisplayItem::AssistantMessage { content, .. } if content == "Bali is great."- )));- }- other => panic!("expected the sub-agent right after its call, got {other:?}"),- }- // Not also appended after everything else.- assert_eq!(- items- .iter()- .filter(|item| matches!(item, DisplayItem::Subagent { .. }))- .count(),- 1- );- assert!(- matches!(items.last(), Some(DisplayItem::AssistantMessage { content, .. }) if content == "Here's the plan."),- "the turn's final answer still closes the list"- );-}--/// A delegation reported incomplete by the runner is a failed run, whatever-/// the child's last row says.-#[test]-fn subagent_status_follows_an_incomplete_delegation_result() {- let dir = TempDir::new().unwrap();- let root_stem = "900_orchestrator";- let thread_id = "thr_sub_fail";- let root = transcript::resolve_keyed_transcript_path(dir.path(), root_stem).unwrap();- transcript::append_transcript_turn(- &root,- &[],- &[- TranscriptMessage::new("user", "go"),- envelope("", &[("c1", "delegate_coder", "{}")], ""),- tool_result("c1", "[SUBAGENT_INCOMPLETE] gave up"),- final_answer("Sorry.", ""),- ],- &meta(thread_id, None, None),- Some(&usage(2, 1_700_000_000, Vec::new())),- Some("req-1"),- )- .unwrap();- let child = transcript::resolve_keyed_transcript_path(- dir.path(),- &format!("{root_stem}__1699999999_000000001_coder_sub-1"),- )- .unwrap();- let mut child_meta = meta(thread_id, None, None);- child_meta.agent_id = Some("coder".into());- transcript::write_transcript(- &child,- &[- TranscriptMessage::new("user", "task"),- TranscriptMessage::assistant("partial thoughts"),- ],- &child_meta,- None,- )- .unwrap();-- let projected = project_thread(dir.path(), thread_id).expect("project");- let status = projected- .items- .iter()- .find_map(|item| match item {- DisplayItem::Subagent {- status, call_id, ..- } => Some((*status, call_id.clone())),- _ => None,- })- .expect("sub-agent projected");- assert_eq!(status, (SubagentStatus::Failed, Some("c1".to_string())));-}--/// A compaction opens `{stem}.g1`, which inherits `created` and starts with-/// the retained rows rewritten. The chain is projected oldest-first, the-/// retained rows once, with a compaction marker at the seam — and an adopted-/// legacy root of the same thread is not projected a second time.-#[test]-fn generation_chain_projects_in_order_without_duplicating_retained_rows() {- let dir = TempDir::new().unwrap();- let thread_id = "thr_generations";- let (session, g0) = session_root(dir.path(), thread_id);- let successor = session.next_generation();- let g1 = transcript::resolve_keyed_transcript_path(- dir.path(),- &transcript::session_stem(&successor),- )- .unwrap();-- // A pre-identity root of the same thread, already adopted into g0.- let legacy =- transcript::resolve_keyed_transcript_path(dir.path(), "1600000000_orchestrator").unwrap();- transcript::append_transcript_turn(- &legacy,- &[],- &[- TranscriptMessage::new("user", "one"),- final_answer("answer one", ""),- ],- &meta(thread_id, None, None),- None,- Some("req-1"),- )- .unwrap();-- let g0_meta = meta(thread_id, Some(session.session_id()), None);- transcript::append_transcript_turn(- &g0,- &[],- &[- TranscriptMessage::new("user", "one"),- final_answer("answer one", ""),- ],- &g0_meta,- None,- Some("req-1"),- )- .unwrap();- let after_one = read_transcript(&g0).unwrap().messages;- let mut two = after_one.clone();- two.extend([- TranscriptMessage::new("user", "two"),- final_answer("answer two", ""),- ]);- transcript::append_transcript_turn(&g0, &after_one, &two, &g0_meta, None, Some("req-2"))- .unwrap();-- // Compaction during turn 3: turn 2 is retained, turn 1 summarised away.- let persisted = read_transcript(&g0).unwrap().messages;- let mut retained: Vec<TranscriptMessage> = persisted[2..].to_vec();- retained.extend([- TranscriptMessage::new("user", "three"),- final_answer("answer three", ""),- ]);- let g1_meta = meta(- thread_id,- Some(successor.session_id()),- Some(session.session_id()),- );- transcript::append_transcript_turn(&g1, &[], &retained, &g1_meta, None, Some("req-3")).unwrap();-- let (roots, _) = resolve_files(dir.path(), thread_id).expect("thread resolves");- assert_eq!(- roots,- vec![g0.clone(), g1.clone()],- "chain order, legacy dropped"- );-- let items = project_thread(dir.path(), thread_id)- .expect("project")- .items;- let users: Vec<&str> = items- .iter()- .filter_map(|item| match item {- DisplayItem::UserMessage { content, .. } => Some(content.as_str()),- _ => None,- })- .collect();- assert_eq!(users, vec!["one", "two", "three"], "{items:#?}");- let answers = items- .iter()- .filter(|item| matches!(item, DisplayItem::AssistantMessage { content, .. } if content == "answer two"))- .count();- assert_eq!(answers, 1, "the retained answer renders once");- assert!(items.iter().any(|item| matches!(- item,- DisplayItem::Compaction { kept_count, .. } if *kept_count == 2- )));-}--#[test]-fn get_page_missing_thread_is_empty_not_error() {- let dir = TempDir::new().unwrap();- let page = super::get_page(- dir.path(),- "no_such_thread",- None,- Some(super::DEFAULT_LIMIT),- );- assert!(!page.has_transcript);- assert_eq!(page.total, 0);- assert!(page.items.is_empty());-}diff --git a/crates/openhuman-core/src/threads/transcript_view/transcript_subagent_anchor_tests.rs b/crates/openhuman-core/src/threads/transcript_view/transcript_subagent_anchor_tests.rsdeleted file mode 100644index a62e3a16ae..0000000000--- a/crates/openhuman-core/src/threads/transcript_view/transcript_subagent_anchor_tests.rs+++ /dev/null@@ -1,67 +0,0 @@-use super::project::project_thread;-use super::tests::write_raw;-use super::types::DisplayItem;-use tempfile::TempDir;--#[test]-fn subagent_anchors_to_parent_turn_by_spawn_timestamp() {- let dir = TempDir::new().unwrap();- let root_stem = "800_orchestrator";- let thread_id = "thr_anchor";- let t1 = chrono::DateTime::from_timestamp(1_000_000, 0)- .unwrap()- .to_rfc3339();- let t2 = chrono::DateTime::from_timestamp(2_000_000, 0)- .unwrap()- .to_rfc3339();- let root_body = vec![- r#"{"role":"user","content":"one","request_id":"req-1"}"#.to_string(),- format!(- r#"{{"role":"assistant","content":"a1","provider":"anthropic","model":"m","usage":{{"input":1,"output":1,"cached_input":0,"cost_usd":0.0}},"ts":"{t1}","iteration":1,"request_id":"req-1"}}"#- ),- r#"{"role":"user","content":"two","request_id":"req-2"}"#.to_string(),- format!(- r#"{{"role":"assistant","content":"a2","provider":"anthropic","model":"m","usage":{{"input":1,"output":1,"cached_input":0,"cost_usd":0.0}},"ts":"{t2}","iteration":1,"request_id":"req-2"}}"#- ),- ];- let root_refs: Vec<&str> = root_body.iter().map(String::as_str).collect();- write_raw(dir.path(), root_stem, thread_id, &root_refs);- write_raw(- dir.path(),- &format!("{root_stem}__999950_coder"),- thread_id,- &[r#"{"role":"assistant","content":"coder work"}"#],- );- write_raw(- dir.path(),- &format!("{root_stem}__1999950_planner"),- thread_id,- &[r#"{"role":"assistant","content":"planner work"}"#],- );-- let mut anchors: Vec<(String, Option<String>)> = project_thread(dir.path(), thread_id)- .expect("project thread")- .items- .iter()- .filter_map(|item| match item {- DisplayItem::Subagent {- request_id, items, ..- } => items.iter().find_map(|inner| match inner {- DisplayItem::AssistantMessage { content, .. } => {- Some((content.clone(), request_id.clone()))- }- _ => None,- }),- _ => None,- })- .collect();- anchors.sort();-- assert_eq!(- anchors,- vec![- ("coder work".to_string(), Some("req-1".to_string())),- ("planner work".to_string(), Some("req-2".to_string())),- ]- );-}diff --git a/crates/openhuman-core/src/threads/transcript_view/transcript_view_subagent_tests.rs b/crates/openhuman-core/src/threads/transcript_view/transcript_view_subagent_tests.rsdeleted file mode 100644index 3cb2494b46..0000000000--- a/crates/openhuman-core/src/threads/transcript_view/transcript_view_subagent_tests.rs+++ /dev/null@@ -1,139 +0,0 @@-use super::*;--#[test]-fn subagent_anchors_to_parent_turn_by_spawn_timestamp() {- let dir = TempDir::new().unwrap();- let root_stem = "800_orchestrator";- let thread_id = "thr_anchor";- let t1 = chrono::DateTime::from_timestamp(1_000_000, 0)- .unwrap()- .to_rfc3339();- let t2 = chrono::DateTime::from_timestamp(2_000_000, 0)- .unwrap()- .to_rfc3339();- let root_body = vec![- r#"{"role":"user","content":"one","request_id":"req-1"}"#.to_string(),- format!(- r#"{{"role":"assistant","content":"a1","provider":"anthropic","model":"m","usage":{{"input":1,"output":1,"cached_input":0,"cost_usd":0.0}},"ts":"{t1}","iteration":1,"request_id":"req-1"}}"#- ),- r#"{"role":"user","content":"two","request_id":"req-2"}"#.to_string(),- format!(- r#"{{"role":"assistant","content":"a2","provider":"anthropic","model":"m","usage":{{"input":1,"output":1,"cached_input":0,"cost_usd":0.0}},"ts":"{t2}","iteration":1,"request_id":"req-2"}}"#- ),- ];- let root_refs: Vec<&str> = root_body.iter().map(String::as_str).collect();- write_raw(dir.path(), root_stem, thread_id, &root_refs);- write_raw(- dir.path(),- &format!("{root_stem}__999950_coder"),- thread_id,- &[r#"{"role":"assistant","content":"coder work"}"#],- );- write_raw(- dir.path(),- &format!("{root_stem}__1000050_planner"),- thread_id,- &[r#"{"role":"assistant","content":"planner work"}"#],- );-- let projected = project_thread(dir.path(), thread_id).expect("project thread");- let mut anchors: Vec<(String, Option<String>)> = projected- .items- .iter()- .filter_map(|item| match item {- DisplayItem::Subagent {- request_id, items, ..- } => {- let marker = items.iter().find_map(|inner| match inner {- DisplayItem::AssistantMessage { content, .. } => Some(content.clone()),- _ => None,- })?;- Some((marker, request_id.clone()))- }- _ => None,- })- .collect();- anchors.sort();- assert_eq!(- anchors,- vec![- ("coder work".to_string(), Some("req-1".to_string())),- ("planner work".to_string(), Some("req-2".to_string())),- ]- );-}--/// Exact correlation (#C1): when the run ledger records the spawning-/// `parentCallId` for this task, it wins over the timestamp/target-argument-/// heuristic — which would otherwise pick the first unclaimed-/// delegation-shaped call, regardless of which one actually spawned this-/// child.-#[test]-fn subagent_correlates_by_ledger_parent_call_id_over_the_heuristic() {- let dir = TempDir::new().unwrap();- let root_stem = "800_orch_exact";- let thread_id = "thr_exact";- let commit_ts = chrono::DateTime::from_timestamp(1_900_000, 0)- .unwrap()- .to_rfc3339();- let root_body = vec![- r#"{"role":"user","content":"do research","request_id":"req-1"}"#.to_string(),- format!(- r#"{{"role":"assistant","content":"","provider":"test","model":"test","usage":{{"input":1,"output":1,"cached_input":0,"cost_usd":0.0}},"tool_calls":[{{"id":"call-decoy","name":"spawn_async_subagent","arguments":"{{}}"}},{{"id":"call-real","name":"spawn_async_subagent","arguments":"{{}}"}}],"iteration":1,"request_id":"req-1","ts":"{commit_ts}"}}"#- ),- ];- let root_refs: Vec<&str> = root_body.iter().map(String::as_str).collect();- write_raw(dir.path(), root_stem, thread_id, &root_refs);-- // Spawned at unix 2_000_000 — after the only turn's commit, so it- // anchors to that turn either way; the heuristic would still pick the- // first unclaimed `spawn_*`-shaped call (`call-decoy`) since neither- // call names an agent. Only the exact ledger lookup can tell them apart.- let child_stem = format!("{root_stem}__2000000_000000001_researcher");- let child = transcript::resolve_keyed_transcript_path(dir.path(), &child_stem).unwrap();- // Written by hand (not `write_raw_at`'s default `meta_line`) so the- // `_meta` header carries `task_id`/`agent_id` — the ledger correlation- // key `build_child` reads.- let child_meta_line = format!(- r#"{{"_meta":{{"version":1,"agent":"researcher","agent_id":"researcher","agent_type":"subagent","dispatcher":"native","created":"2026-07-21T00:00:00Z","updated":"2026-07-21T00:00:10Z","turn_count":1,"input_tokens":1,"output_tokens":1,"cached_input_tokens":0,"charged_amount_usd":0.0,"thread_id":"{thread_id}","task_id":"sub-exact-1"}}}}"#- );- std::fs::write(- &child,- format!("{child_meta_line}\n{{\"role\":\"assistant\",\"content\":\"Bali is great.\"}}\n"),- )- .unwrap();-- tinyagents_session::run_ledger::upsert_agent_run(- dir.path(),- tinyagents_session::run_ledger::AgentRunUpsert {- id: "sub-exact-1".to_string(),- kind: tinyagents_session::run_ledger::AgentRunKind::Subagent,- parent_run_id: None,- parent_thread_id: Some(thread_id.to_string()),- agent_id: Some("researcher".to_string()),- status: tinyagents_session::run_ledger::AgentRunStatus::Completed,- prompt_ref: None,- worker_thread_id: None,- checkpoint_path: None,- checkpoint: None,- summary: None,- error: None,- metadata: serde_json::json!({ "parentCallId": "call-real" }),- started_at: None,- completed_at: None,- },- )- .expect("seed run ledger row");-- let projected = project_thread(dir.path(), thread_id).expect("project thread");- let subagent_call_id = projected.items.iter().find_map(|item| match item {- DisplayItem::Subagent { call_id, .. } => Some(call_id.clone()),- _ => None,- });- assert_eq!(- subagent_call_id,- Some(Some("call-real".to_string())),- "exact ledger correlation must win over the first-unclaimed heuristic; items={:#?}",- projected.items- );-}diff --git a/crates/openhuman-core/src/threads/transcript_view/transcript_view_tests.rs b/crates/openhuman-core/src/threads/transcript_view/transcript_view_tests.rsdeleted file mode 100644index a8647ce381..0000000000--- a/crates/openhuman-core/src/threads/transcript_view/transcript_view_tests.rs+++ /dev/null@@ -1,729 +0,0 @@-//! Projection + pagination + sanitization tests for the transcript view.--use super::get_page;-use super::project::{project_records, project_thread};-use super::types::{DisplayItem, ToolCallStatus};-use crate::agent::messages::{- attach_chat_tool_failure_metadata, transcript_message_from_chat, ChatMessage,-};-use std::path::{Path, PathBuf};-use tempfile::TempDir;-use tinyagents_session::transcript::{self, read_transcript_display};--fn meta_line(thread_id: &str) -> String {- format!(- r#"{{"_meta":{{"version":1,"agent":"orchestrator","dispatcher":"native","created":"2026-07-21T00:00:00Z","updated":"2026-07-21T00:00:10Z","turn_count":1,"input_tokens":30,"output_tokens":13,"cached_input_tokens":0,"charged_amount_usd":0.003,"thread_id":"{thread_id}"}}}}"#- )-}--/// Write a raw JSONL transcript (meta header + given body lines) into-/// `session_raw/{stem}.jsonl` and return the path.-pub(super) fn write_raw(workspace: &Path, stem: &str, thread_id: &str, body: &[&str]) -> PathBuf {- let path = transcript::resolve_keyed_transcript_path(workspace, stem).expect("resolve");- write_raw_at(&path, thread_id, body);- path-}--fn write_raw_at(path: &Path, thread_id: &str, body: &[&str]) {- let mut buf = meta_line(thread_id);- buf.push('\n');- for line in body {- buf.push_str(line);- buf.push('\n');- }- std::fs::write(&path, buf).expect("write raw transcript");-}--/// A full turn: system scaffolding, a user prompt with the injected datetime-/// prefix, an assistant tool-calling step (reasoning + tool_calls), a tool-/// result, then the final assistant answer.-fn full_turn_body() -> Vec<&'static str> {- vec![- r#"{"role":"system","content":"[tool-policy preamble] you may use tools ..."}"#,- r#"{"role":"user","content":"Current Date & Time: 2026-07-21 09:00:00 UTC\n\nWhat's the weather in NYC?","request_id":"req-1"}"#,- r#"{"role":"assistant","content":"Let me check.","provider":"anthropic","model":"claude-x","usage":{"input":10,"output":5,"cached_input":0,"cost_usd":0.001},"ts":"2026-07-21T09:00:01Z","reasoning_content":"I should call the weather tool.","tool_calls":[{"id":"call-1","name":"get_weather","arguments":"{\"city\":\"NYC\"}"}],"iteration":1,"request_id":"req-1"}"#,- r#"{"role":"tool","content":"72F and sunny","id":"call-1","request_id":"req-1"}"#,- r#"{"role":"assistant","content":"It's 72F and sunny in NYC.","provider":"anthropic","model":"claude-x","usage":{"input":20,"output":8,"cached_input":0,"cost_usd":0.002},"ts":"2026-07-21T09:00:02Z","iteration":2,"request_id":"req-1"}"#,- ]-}--#[test]-fn projects_turn_with_tools_reasoning_and_sanitization() {- let dir = TempDir::new().unwrap();- let path = write_raw(dir.path(), "100_orchestrator", "thr_w", &full_turn_body());- let display = read_transcript_display(&path).unwrap();- let items = project_records(&display.records);-- // Expected order: turnBoundary, userMessage, reasoning, assistant(interim),- // toolCall(paired), assistant(final). System line dropped.- assert_eq!(items.len(), 6, "unexpected items: {items:#?}");-- match &items[0] {- DisplayItem::TurnBoundary { request_id } => assert_eq!(request_id, "req-1"),- other => panic!("expected turnBoundary, got {other:?}"),- }- match &items[1] {- DisplayItem::UserMessage {- content,- display_content,- request_id,- ..- } => {- assert!(content.starts_with("Current Date & Time:"), "raw kept");- assert_eq!(- display_content.as_deref(),- Some("What's the weather in NYC?"),- "datetime prefix stripped into displayContent"- );- assert_eq!(request_id.as_deref(), Some("req-1"));- }- other => panic!("expected userMessage, got {other:?}"),- }- match &items[2] {- DisplayItem::Reasoning { text, iteration } => {- assert_eq!(text, "I should call the weather tool.");- assert_eq!(- *iteration,- Some(1),- "reasoning carries its step's iteration"- );- }- other => panic!("expected reasoning, got {other:?}"),- }- match &items[3] {- DisplayItem::AssistantMessage {- content,- interim,- ts,- ..- } => {- assert_eq!(content, "Let me check.");- assert!(*interim, "tool-calling assistant step is interim");- assert_eq!(- ts.as_deref(),- Some("2026-07-21T09:00:01Z"),- "assistantMessage carries the underlying record's ts"- );- }- other => panic!("expected interim assistantMessage, got {other:?}"),- }- match &items[4] {- DisplayItem::ToolCall {- call_id,- name,- args,- result,- status,- failure,- ..- } => {- assert_eq!(call_id, "call-1");- assert_eq!(name, "get_weather");- assert_eq!(- args.as_ref()- .and_then(|v| v.get("city"))- .and_then(|v| v.as_str()),- Some("NYC")- );- assert_eq!(result.as_deref(), Some("72F and sunny"), "paired by id");- assert_eq!(*status, ToolCallStatus::Success);- assert!(failure.is_none(), "successful tool carries no failure");- }- other => panic!("expected toolCall, got {other:?}"),- }- match &items[5] {- DisplayItem::AssistantMessage {- content,- interim,- ts,- ..- } => {- assert_eq!(content, "It's 72F and sunny in NYC.");- assert!(!*interim, "final answer is not interim");- assert_eq!(- ts.as_deref(),- Some("2026-07-21T09:00:02Z"),- "final assistantMessage carries its own record's ts, not the interim step's"- );- }- other => panic!("expected final assistantMessage, got {other:?}"),- }-}--#[test]-fn reuses_synthetic_tool_call_ids_in_a_later_turn() {- let dir = TempDir::new().unwrap();- let path = write_raw(- dir.path(),- "synthetic_ids",- "thr_synthetic",- &[- r#"{"role":"user","content":"one","request_id":"req-1"}"#,- r#"{"role":"assistant","content":"","provider":"test","model":"test","usage":{"input":1,"output":1,"cached_input":0,"cost_usd":0.0},"ts":"2026-07-21T00:00:01Z","tool_calls":[{"id":"call_0","name":"first","arguments":"{}"}],"request_id":"req-1"}"#,- r#"{"role":"tool","content":"first result","id":"call_0","request_id":"req-1"}"#,- r#"{"role":"user","content":"two","request_id":"req-2"}"#,- r#"{"role":"assistant","content":"","provider":"test","model":"test","usage":{"input":1,"output":1,"cached_input":0,"cost_usd":0.0},"ts":"2026-07-21T00:00:02Z","tool_calls":[{"id":"call_0","name":"second","arguments":"{}"}],"request_id":"req-2"}"#,- r#"{"role":"tool","content":"second result","id":"call_0","request_id":"req-2"}"#,- ],- );- let display = read_transcript_display(&path).unwrap();- let items = project_records(&display.records);-- let calls: Vec<_> = items- .iter()- .filter_map(|item| match item {- DisplayItem::ToolCall { name, result, .. } => Some((name.as_str(), result.as_deref())),- _ => None,- })- .collect();- assert_eq!(- calls,- vec![- ("first", Some("first result")),- ("second", Some("second result"))- ]- );-}--#[test]-fn recovers_tool_name_from_native_envelope_without_turn_usage() {- let dir = TempDir::new().unwrap();- let envelope = serde_json::json!({- "content": null,- "tool_calls": [{- "id": "call-web-1",- "name": "web_fetch",- "arguments": { "url": "https://example.com" }- }]- })- .to_string();- let assistant = serde_json::json!({- "role": "assistant",- "content": envelope,- "request_id": "req-native"- })- .to_string();- let result =- r#"{"role":"tool","content":"Example Domain","id":"call-web-1","request_id":"req-native"}"#;- let path = write_raw(- dir.path(),- "101_orchestrator",- "thr_native",- &[assistant.as_str(), result],- );- let display = read_transcript_display(&path).unwrap();- let items = project_records(&display.records);-- let tool = items- .iter()- .find_map(|item| match item {- DisplayItem::ToolCall {- name,- args,- result,- status,- ..- } => Some((name, args, result, status)),- _ => None,- })- .expect("native envelope tool call projected");- assert_eq!(tool.0, "web_fetch");- assert_eq!(- tool.1- .as_ref()- .and_then(|args| args.get("url"))- .and_then(serde_json::Value::as_str),- Some("https://example.com")- );- assert_eq!(tool.2.as_deref(), Some("Example Domain"));- assert_eq!(*tool.3, ToolCallStatus::Success);-}--#[test]-fn projects_compaction_and_interrupted_partial() {- let dir = TempDir::new().unwrap();- let body = vec![- r#"{"role":"user","content":"hi","request_id":"req-1"}"#,- r#"{"kind":"compaction","replacement":[{"role":"user","content":"summary so far"}],"ts":"2026-07-21T09:05:00Z","request_id":"req-2"}"#,- r#"{"role":"assistant","content":"partial ans","interrupted":true,"reasoning_content":"mid-thought","iteration":3,"request_id":"req-2"}"#,- ];- let path = write_raw(dir.path(), "200_orchestrator", "thr_c", &body);- let display = read_transcript_display(&path).unwrap();- let items = project_records(&display.records);-- let has_compaction = items.iter().any(|i| {- matches!(- i,- DisplayItem::Compaction { kept_count, .. } if *kept_count == 1- )- });- assert!(has_compaction, "compaction projected: {items:#?}");-- let partial = items- .iter()- .find_map(|i| match i {- DisplayItem::InterruptedPartial { text, thinking } => Some((text, thinking)),- _ => None,- })- .expect("interrupted partial projected");- assert_eq!(partial.0, "partial ans");- assert_eq!(partial.1.as_deref(), Some("mid-thought"));-}--#[test]-fn legacy_file_without_version_or_request_id_projects() {- let dir = TempDir::new().unwrap();- // Legacy meta: no `version`, messages carry no `request_id`.- let path = transcript::resolve_keyed_transcript_path(dir.path(), "300_orchestrator").unwrap();- let raw = concat!(- r#"{"_meta":{"agent":"orchestrator","dispatcher":"native","created":"2026-01-01T00:00:00Z","updated":"2026-01-01T00:00:00Z","turn_count":1,"input_tokens":0,"output_tokens":0,"cached_input_tokens":0,"charged_amount_usd":0.0,"thread_id":"thr_legacy"}}"#,- "\n",- r#"{"role":"user","content":"plain question"}"#,- "\n",- r#"{"role":"assistant","content":"plain answer"}"#,- "\n",- );- std::fs::write(&path, raw).unwrap();- let display = read_transcript_display(&path).unwrap();- let items = project_records(&display.records);-- // No request_id → no turn boundary; user + assistant still project, and an- // un-prefixed user message keeps no displayContent (nothing to strip).- assert!(- !items- .iter()- .any(|i| matches!(i, DisplayItem::TurnBoundary { .. })),- "legacy lines have no request_id, so no boundary"- );- match items.first() {- Some(DisplayItem::UserMessage {- content,- display_content,- ..- }) => {- assert_eq!(content, "plain question");- assert_eq!(- display_content.as_deref(),- None,- "no prefix, no displayContent"- );- }- other => panic!("expected userMessage first, got {other:?}"),- }- assert!(items.iter().any(- |i| matches!(i, DisplayItem::AssistantMessage { content, .. } if content == "plain answer")- ));-}--#[test]-fn subagent_file_projects_as_nested_item() {- let dir = TempDir::new().unwrap();- let root_stem = "400_orchestrator";- write_raw(- dir.path(),- root_stem,- "thr_s",- &[r#"{"role":"user","content":"delegate please","request_id":"req-1"}"#],- );- // Sub-agent sibling shares the root stem with a `__` suffix.- write_raw(- dir.path(),- &format!("{root_stem}__100_coder"),- "thr_s",- &[- r#"{"role":"assistant","content":"sub work done","provider":"anthropic","model":"claude-x","usage":{"input":5,"output":3,"cached_input":0,"cost_usd":0.0},"ts":"2026-07-21T09:10:00Z","iteration":1}"#,- ],- );-- let projected = project_thread(dir.path(), "thr_s").expect("project thread");- let subagent = projected- .items- .iter()- .find_map(|i| match i {- DisplayItem::Subagent { id, items, .. } => Some((id, items)),- _ => None,- })- .expect("subagent item present");- assert_eq!(subagent.0, "100_coder", "unique run id, not the agent name");- assert!(subagent.1.iter().any(- |i| matches!(i, DisplayItem::AssistantMessage { content, .. } if content == "sub work done")- ));-}--#[test]-fn canonical_root_and_subagent_project_together() {- let dir = TempDir::new().unwrap();- let raw_dir = dir.path().join("session_raw");- std::fs::create_dir_all(&raw_dir).unwrap();- let root_stem = "450_orchestrator";- let thread_id = "thr_canonical";-- write_raw_at(- &raw_dir.join(format!("{root_stem}.jsonl")),- thread_id,- &[r#"{"role":"user","content":"delegate","request_id":"req-1"}"#],- );- write_raw_at(- &raw_dir.join(format!("{root_stem}__451_coder.jsonl")),- thread_id,- &[r#"{"role":"assistant","content":"scoped sub work"}"#],- );-- let projected = project_thread(dir.path(), thread_id).expect("project scoped thread");- assert!(projected.items.iter().any(|item| matches!(- item,- DisplayItem::Subagent { items, .. }- if items.iter().any(|inner| matches!(- inner,- DisplayItem::AssistantMessage { content, .. }- if content == "scoped sub work"- ))- )));-}--#[test]-fn get_page_paginates_newest_first_with_cursor() {- let dir = TempDir::new().unwrap();- // Five plain user messages → five top-level items.- let body: Vec<String> = (0..5)- .map(|i| format!(r#"{{"role":"user","content":"msg-{i}"}}"#))- .collect();- let body_refs: Vec<&str> = body.iter().map(String::as_str).collect();- write_raw(dir.path(), "500_orchestrator", "thr_p", &body_refs);-- // First page: newest first, limit 2 → msg-4, msg-3.- let page1 = get_page(dir.path(), "thr_p", None, Some(2));- assert_eq!(page1.total, 5);- assert!(page1.has_more);- assert_eq!(page1.items.len(), 2);- assert!(- matches!(&page1.items[0], DisplayItem::UserMessage { content, .. } if content == "msg-4")- );- assert!(- matches!(&page1.items[1], DisplayItem::UserMessage { content, .. } if content == "msg-3")- );-- let cursor = page1.next_cursor.clone().expect("next cursor");- let page2 = get_page(dir.path(), "thr_p", Some(&cursor), Some(2));- assert!(- matches!(&page2.items[0], DisplayItem::UserMessage { content, .. } if content == "msg-2")- );-- // Walk to the end.- let last = get_page(dir.path(), "thr_p", page2.next_cursor.as_deref(), Some(2));- assert!(!last.has_more, "final page exhausts the thread");- assert!(last.next_cursor.is_none());-}--#[test]-fn failed_tool_line_projects_error_status_with_failure_payload() {- let dir = TempDir::new().unwrap();- // Assistant issues a tool call; the paired tool result line carries the- // additive `failure` flag (stamped at persistence from `is_error`).- let body = vec![- r#"{"role":"assistant","content":"trying","provider":"anthropic","model":"m","usage":{"input":1,"output":1,"cached_input":0,"cost_usd":0.0},"ts":"2026-07-21T09:00:01Z","tool_calls":[{"id":"call-9","name":"shell","arguments":"{\"cmd\":\"boom\"}"}],"iteration":1,"request_id":"req-1"}"#,- r#"{"role":"tool","content":"error: command not found","id":"call-9","request_id":"req-1","failure":true,"failure_detail":"error: command not found"}"#,- ];- let path = write_raw(dir.path(), "600_orchestrator", "thr_f", &body);- let display = read_transcript_display(&path).unwrap();- let items = project_records(&display.records);-- let tool = items- .iter()- .find_map(|i| match i {- DisplayItem::ToolCall {- status, failure, ..- } => Some((status, failure)),- _ => None,- })- .expect("toolCall projected");- assert_eq!(*tool.0, ToolCallStatus::Error, "failed tool → error status");- let failure = tool.1.as_ref().expect("failure payload present");- assert_eq!(failure.detail.as_deref(), Some("error: command not found"));-}--#[test]-fn tool_failure_metadata_round_trips_write_to_display_line() {- // Full write path: a failed tool ChatMessage stamped with failure metadata- // must serialise the additive `failure` line field and read back as a failed- // display message — proving the harness → transcript → projection seam.- let dir = TempDir::new().unwrap();- let now = "2026-07-21T09:00:00Z".to_string();- let meta = transcript::TranscriptMeta {- session_id: None,- parent_session_id: None,- agent_name: "orchestrator".into(),- agent_id: Some("orchestrator".into()),- agent_type: Some("root".into()),- dispatcher: "native".into(),- provider: Some("anthropic".into()),- model: Some("m".into()),- created: now.clone(),- updated: now,- turn_count: 1,- prefix_message_count: None,- input_tokens: 0,- output_tokens: 0,- cached_input_tokens: 0,- charged_amount_usd: 0.0,- thread_id: Some("thr_rt".into()),- task_id: None,- };-- let mut tool_msg = ChatMessage {- id: Some("call-1".into()),- role: "tool".into(),- content: r#"{"tool_call_id":"call-1","content":"boom"}"#.into(),- extra_metadata: None,- cache_breakpoints: Vec::new(),- };- attach_chat_tool_failure_metadata(&mut tool_msg, Some("boom: exit 1"));-- let messages = vec![- ChatMessage {- id: None,- role: "user".into(),- content: "do it".into(),- extra_metadata: None,- cache_breakpoints: Vec::new(),- },- tool_msg,- ];- let path = transcript::resolve_keyed_transcript_path(dir.path(), "700_orchestrator").unwrap();- let messages: Vec<_> = messages.iter().map(transcript_message_from_chat).collect();- transcript::write_transcript(&path, &messages, &meta, None).unwrap();-- let display = read_transcript_display(&path).unwrap();- let failed = display- .records- .iter()- .find_map(|r| match r {- transcript::DisplayRecord::Message(m) if m.message.role == "tool" => Some(m),- _ => None,- })- .expect("tool display message present");- assert!(- failed.failure,- "failure flag survived the write/read round trip"- );- assert_eq!(failed.failure_detail.as_deref(), Some("boom: exit 1"));-}--/// The **golden test for the turn path's write call site**.-///-/// Every other test in this file hand-writes JSONL string literals, so they pin-/// the reader/projector but say nothing about the writer the live turn loop-/// actually calls. `tool_failure_metadata_round_trips_write_to_display_line`-/// goes through `write_transcript`, not `append_transcript_turn`. That left the-/// seam this test covers — `append_transcript_turn` → `read_transcript_display`-/// → `project_thread` — with no coverage at all, which is exactly the seam the-/// tinyagents `ChatHistory` migration touches.-///-/// It fails loudly if a write ever drops `request_id` or `turn_usage`: without-/// `request_id` there is no `DisplayItem::TurnBoundary` (project.rs-/// `maybe_emit_turn_boundary`) and `turn_segments` goes empty, unanchoring every-/// sub-agent; without `turn_usage` every `DisplayItem::ToolCall` disappears-/// (tool calls are read off `turn_usage.tool_calls`), `Reasoning` vanishes, and-/// `AssistantMessage.{model,iteration,interim}` collapse to `None`/`false`.-///-/// All timestamps are fixed literals so nothing here is clock-dependent.-#[test]-fn append_transcript_turn_projects_full_display_shape() {- let dir = TempDir::new().unwrap();- let now = "2026-07-21T09:00:00Z".to_string();- let meta = transcript::TranscriptMeta {- session_id: None,- parent_session_id: None,- agent_name: "orchestrator".into(),- agent_id: Some("orchestrator".into()),- agent_type: Some("root".into()),- dispatcher: "native".into(),- provider: Some("anthropic".into()),- model: Some("claude-x".into()),- created: now.clone(),- updated: now,- turn_count: 1,- prefix_message_count: None,- input_tokens: 30,- output_tokens: 13,- cached_input_tokens: 0,- charged_amount_usd: 0.003,- thread_id: Some("thr_golden".into()),- task_id: None,- };-- let usage = |cost: f64| transcript::MessageUsage {- input: 20,- output: 8,- cached_input: 0,- context_window: 200_000,- cost_usd: cost,- };-- // Iteration 1 of the turn: the model reasons and emits a native tool call.- // `turn_usage` attaches to the last assistant row of the written slice, so- // this one lands on the interim assistant.- let interim_usage = transcript::TurnUsage {- provider: "anthropic".into(),- model: "claude-x".into(),- usage: usage(0.001),- ts: "2026-07-21T09:00:01Z".into(),- reasoning_content: Some("I should call the weather tool.".into()),- tool_calls: vec![transcript::TranscriptToolCall {- id: "call-1".into(),- name: "get_weather".into(),- arguments: r#"{"city":"NYC"}"#.into(),- extra_content: None,- }],- iteration: 1,- };- // Iteration 2: the final answer, no further tool calls.- let final_usage = transcript::TurnUsage {- provider: "anthropic".into(),- model: "claude-x".into(),- usage: usage(0.002),- ts: "2026-07-21T09:00:02Z".into(),- reasoning_content: None,- tool_calls: vec![],- iteration: 2,- };-- let msg = |id: Option<&str>, role: &str, content: &str| transcript::TranscriptMessage {- id: id.map(str::to_string),- role: role.into(),- content: content.into(),- extra_metadata: None,- cache_breakpoints: Vec::new(),- turn_usage: None,- request_id: None,- preserve_request_id: false,- interrupted: false,- tool_failure: None,- };-- let first = vec![- msg(None, "user", "What's the weather in NYC?"),- msg(None, "assistant", "Let me check."),- ];- let mut second = first.clone();- second.push(msg(Some("call-1"), "tool", "72F and sunny"));- second.push(msg(None, "assistant", "It's 72F and sunny in NYC."));-- let path = transcript::resolve_keyed_transcript_path(dir.path(), "900_orchestrator").unwrap();- // First write creates the file (meta + all lines); the second is a pure- // extension appending only the new tail — both are the real turn-path shape.- transcript::append_transcript_turn(- &path,- &[],- &first,- &meta,- Some(&interim_usage),- Some("req-1"),- )- .unwrap();- transcript::append_transcript_turn(- &path,- &first,- &second,- &meta,- Some(&final_usage),- Some("req-1"),- )- .unwrap();-- let display = read_transcript_display(&path).unwrap();- let items = project_records(&display.records);-- // A turn boundary must be emitted from the stamped request_id.- let boundary = items- .iter()- .find_map(|i| match i {- DisplayItem::TurnBoundary { request_id } => Some(request_id.clone()),- _ => None,- })- .expect("turnBoundary projected from request_id");- assert_eq!(boundary, "req-1");-- // Reasoning comes off turn_usage.reasoning_content.- let reasoning = items- .iter()- .find_map(|i| match i {- DisplayItem::Reasoning { text, .. } => Some(text.clone()),- _ => None,- })- .expect("reasoning projected from turn_usage");- assert_eq!(reasoning, "I should call the weather tool.");-- // The tool call itself is read off turn_usage.tool_calls, and pairs with the- // role:"tool" line by id.- let tool = items- .iter()- .find_map(|i| match i {- DisplayItem::ToolCall {- call_id,- name,- args,- result,- status,- ..- } => Some((- call_id.clone(),- name.clone(),- args.clone(),- result.clone(),- *status,- )),- _ => None,- })- .expect("toolCall projected from turn_usage.tool_calls");- assert_eq!(tool.0, "call-1");- assert_eq!(tool.1, "get_weather");- assert_eq!(- tool.2- .as_ref()- .and_then(|v| v.get("city"))- .and_then(|v| v.as_str()),- Some("NYC")- );- assert_eq!(tool.3.as_deref(), Some("72F and sunny"));- assert_eq!(tool.4, ToolCallStatus::Success);-- // Model / iteration / request_id / interim all come off the persisted- // `turn_usage` + `request_id`; each is `None`/`false` if either is dropped.- let assistants: Vec<_> = items- .iter()- .filter_map(|i| match i {- DisplayItem::AssistantMessage {- content,- model,- iteration,- request_id,- interim,- ..- } => Some((- content.clone(),- model.clone(),- *iteration,- request_id.clone(),- *interim,- )),- _ => None,- })- .collect();- assert_eq!(assistants.len(), 2, "unexpected items: {items:#?}");-- assert_eq!(assistants[0].0, "Let me check.");- assert_eq!(assistants[0].1.as_deref(), Some("claude-x"));- assert_eq!(assistants[0].2, Some(1));- assert_eq!(assistants[0].3.as_deref(), Some("req-1"));- assert!(assistants[0].4, "tool-calling step is interim");-- assert_eq!(assistants[1].0, "It's 72F and sunny in NYC.");- assert_eq!(assistants[1].1.as_deref(), Some("claude-x"));- assert_eq!(assistants[1].2, Some(2));- assert_eq!(assistants[1].3.as_deref(), Some("req-1"));- assert!(!assistants[1].4, "final answer is not interim");-}--#[path = "transcript_view_subagent_tests.rs"]-mod subagent_tests;diff --git a/crates/openhuman-core/src/threads/transcript_view/types.rs b/crates/openhuman-core/src/threads/transcript_view/types.rsdeleted file mode 100644index fd1322f7b7..0000000000--- a/crates/openhuman-core/src/threads/transcript_view/types.rs+++ /dev/null@@ -1,189 +0,0 @@-//! Typed display items for the transcript projection RPC-//! (`threads.transcript_get`).-//!-//! These mirror the frontend's existing chat vocabulary (user/assistant-//! bubbles, reasoning drawer, tool timeline rows, sub-agent activity) so the-//! Phase C renderer can map them onto the same components. Serde is camelCase-//! on the wire — the frontend reads `displayContent`, `callId`, `requestId`,-//! etc.--use serde::Serialize;--/// Terminal state of a projected tool call. Mirrors the live timeline's-/// `ToolTimelineStatus` vocabulary (`running` / `success` / `error`) so the-/// settled projection and the live stream render identically.-#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]-#[serde(rename_all = "snake_case")]-pub enum ToolCallStatus {- /// Call issued but no result line has been paired yet.- Running,- /// A result line was paired to the call.- Success,- /// A result line the projection identified as a **failure**: the persisted- /// tool line carried the additive `failure` flag (stamped at turn-loop- /// persistence from the tool's `ToolResult::is_error` outcome). Paired with- /// a [`ToolCallFailure`] payload on the item.- Error,-}--/// Terminal state of a projected sub-agent run.-#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]-#[serde(rename_all = "snake_case")]-pub enum SubagentStatus {- /// The run ended with a final answer.- Completed,- /// The spawning call failed, or reported the run incomplete.- Failed,- /// The run's last record is an interrupted partial answer.- Interrupted,- /// No terminal record yet (still running, or never settled).- Running,-}--/// Failure payload attached to an errored [`DisplayItem::ToolCall`]. Minimal by-/// design: the persisted transcript only records that the call failed plus an-/// optional short reason. The frontend mapper expands this into its richer-/// `ToolFailureExplanation` shape (`class` / `category` / `causePlain` /-/// `nextAction`) for the `ToolFailureLines` renderer.-#[derive(Debug, Clone, PartialEq, Serialize)]-#[serde(rename_all = "camelCase")]-pub struct ToolCallFailure {- /// Short, single-line reason for the failure, when the writer captured one.- #[serde(skip_serializing_if = "Option::is_none")]- pub detail: Option<String>,-}--/// One item in a projected transcript, in the frontend's display vocabulary.-///-/// `#[serde(tag = "kind")]` gives each variant a camelCase discriminator-/// (`userMessage`, `assistantMessage`, …) and every field is camelCase.-#[derive(Debug, Clone, PartialEq, Serialize)]-#[serde(- tag = "kind",- rename_all = "camelCase",- rename_all_fields = "camelCase"-)]-pub enum DisplayItem {- /// A user prompt. `content` is the raw persisted content (may carry the- /// injected `Current Date & Time:` scaffolding line); `displayContent` is- /// the sanitized version to show, present only when it differs from raw.- UserMessage {- content: String,- #[serde(skip_serializing_if = "Option::is_none")]- display_content: Option<String>,- #[serde(skip_serializing_if = "Option::is_none")]- request_id: Option<String>,- /// RFC3339 timestamp of the underlying `DisplayMessage`, when the- /// transcript record carried one. `None` for older records written- /// before timestamps were persisted — never backfilled.- #[serde(skip_serializing_if = "Option::is_none")]- ts: Option<String>,- },- /// An assistant answer. `interim: true` marks a non-terminal tool-calling- /// step within a multi-iteration turn (not the final answer bubble).- AssistantMessage {- content: String,- #[serde(default, skip_serializing_if = "is_false")]- interim: bool,- #[serde(skip_serializing_if = "Option::is_none")]- request_id: Option<String>,- #[serde(skip_serializing_if = "Option::is_none")]- model: Option<String>,- #[serde(skip_serializing_if = "Option::is_none")]- iteration: Option<u32>,- #[serde(skip_serializing_if = "Option::is_none")]- ts: Option<String>,- },- /// The model's reasoning/thinking that preceded an assistant message.- /// `iteration` is the model call it belongs to — the same value as the- /// message/tool calls that follow it — so a renderer groups it with the- /// step it explains rather than the step before.- Reasoning {- text: String,- #[serde(skip_serializing_if = "Option::is_none")]- iteration: Option<u32>,- },- /// A tool invocation with its paired result, when available.- ToolCall {- call_id: String,- name: String,- /// The model call (1-based, within the turn) that issued this call.- #[serde(skip_serializing_if = "Option::is_none")]- iteration: Option<u32>,- #[serde(skip_serializing_if = "Option::is_none")]- args: Option<serde_json::Value>,- #[serde(skip_serializing_if = "Option::is_none")]- result: Option<String>,- status: ToolCallStatus,- /// Present only when `status` is `Error` — the failure payload the- /// frontend expands for the `ToolFailureLines` renderer.- #[serde(skip_serializing_if = "Option::is_none")]- failure: Option<ToolCallFailure>,- #[serde(skip_serializing_if = "Option::is_none")]- ts: Option<String>,- },- /// A delegated sub-agent run, with its own nested projected items.- ///- /// Placed in the item list directly after the tool call that spawned it- /// when that call can be correlated (`call_id`), else at the end of the- /// turn it was spawned in. Sub-agent transcripts are sibling files with no- /// explicit back-link to the delegating tool call, so the turn is derived- /// by matching the sub-agent's spawn timestamp (encoded in its file stem)- /// against the parent turns' commit timestamps, and the call within that- /// turn by the delegation target (see `subagents::attach`).- ///- /// `id` is unique per run: the spawn `task_id` when recorded, else the- /// file-stem suffix — never the agent name, which repeats across runs.- Subagent {- id: String,- /// Sub-agent definition id (e.g. `code_executor`).- #[serde(skip_serializing_if = "Option::is_none")]- agent_id: Option<String>,- /// Spawn task id (`sub-…`), when the transcript recorded one.- #[serde(skip_serializing_if = "Option::is_none")]- task_id: Option<String>,- /// The parent tool call that spawned this run, when correlated.- #[serde(skip_serializing_if = "Option::is_none")]- call_id: Option<String>,- /// Terminal state of the run, derived from its own transcript and the- /// spawning call's result.- status: SubagentStatus,- #[serde(skip_serializing_if = "Option::is_none")]- request_id: Option<String>,- #[serde(skip_serializing_if = "Option::is_none")]- ts: Option<String>,- items: Vec<DisplayItem>,- },- /// A turn boundary — emitted when the `request_id` changes between lines.- TurnBoundary { request_id: String },- /// A partial assistant answer captured when a turn was interrupted.- InterruptedPartial {- text: String,- #[serde(skip_serializing_if = "Option::is_none")]- thinking: Option<String>,- },- /// A context-compaction marker: the reduced set replaced everything before- /// it. Counts describe what the record superseded/installed.- Compaction {- replaced_count: usize,- kept_count: usize,- #[serde(skip_serializing_if = "Option::is_none")]- ts: Option<String>,- #[serde(skip_serializing_if = "Option::is_none")]- request_id: Option<String>,- },-}--#[allow(clippy::trivially_copy_pass_by_ref)]-fn is_false(b: &bool) -> bool {- !*b-}--/// A projected transcript for one thread, before pagination. Chronological-/// (file) order; the RPC layer paginates newest-first.-#[derive(Debug, Clone)]-pub struct ProjectedTranscript {- pub thread_id: String,- /// All top-level display items in chronological order.- pub items: Vec<DisplayItem>,-}