Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
34 changes: 25 additions & 9 deletions bt-daemon/src/collections/legacy.rs
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,10 @@ const IMPORT_RECORDS: usize = 1024;
const IMPORT_BYTES: usize = 8 * 1024 * 1024;
const PI_MESSAGES_DELTA: &str = "_bt_messages_delta";

// Recovery and live capture can both discover a legacy journal. Serialize
// reading, committing and removing those files. Modern sessions bypass this.
static IMPORT_LOCK: tokio::sync::Mutex<()> = tokio::sync::Mutex::const_new(());

/// Import any legacy journals that hold records for this source session.
pub(super) async fn import_session(
data_dir: &Path,
Expand All @@ -30,14 +34,19 @@ pub(super) async fn import_session(
events: &SessionStorage,
) -> anyhow::Result<()> {
let unqualified = journal_path(data_dir, session_id);
if unqualified
let unqualified_supported = unqualified
.file_name()
.is_some_and(|name| name.len() <= crate::journal::MAX_FILE_NAME_BYTES)
&& tokio::fs::try_exists(&unqualified).await?
.is_some_and(|name| name.len() <= crate::journal::MAX_FILE_NAME_BYTES);
let qualified = source_journal_path(data_dir, source, session_id);
if !(unqualified_supported && tokio::fs::try_exists(&unqualified).await?)
&& !tokio::fs::try_exists(&qualified).await?
{
return Ok(());
}
let _guard = IMPORT_LOCK.lock().await;
if unqualified_supported && tokio::fs::try_exists(&unqualified).await? {
import_unqualified(data_dir, &unqualified).await?;
}
let qualified = source_journal_path(data_dir, source, session_id);
if tokio::fs::try_exists(&qualified).await? {
import_file(&qualified, source, events, None).await?;
tokio::fs::remove_file(&qualified).await?;
Expand All @@ -57,11 +66,18 @@ pub(crate) async fn import_all(data_dir: &Path) {
continue;
}
let result = async {
let owners = sessions(&path).await?;
if owners.is_empty() {
// Nothing was ever acknowledged from a file without events.
tokio::fs::remove_file(&path).await?;
}
let owners = {
let _guard = IMPORT_LOCK.lock().await;
if !tokio::fs::try_exists(&path).await? {
return Ok(());
}
let owners = sessions(&path).await?;
if owners.is_empty() {
// Nothing was ever acknowledged from a file without events.
tokio::fs::remove_file(&path).await?;
}
owners
};
for (source, session_id) in owners {
SessionStorage::open(data_dir, &source, &session_id).await?;
}
Expand Down
27 changes: 27 additions & 0 deletions bt-daemon/src/collections/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -434,3 +434,30 @@ async fn compaction_returns_deleted_space_to_the_file_system() {
assert_eq!(pragma("freelist_count"), 0);
assert!(size() < bloated / 4, "{} of {bloated} bytes remain", size());
}

#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
async fn simultaneous_legacy_open_preserves_capture() {
for qualified in [true, false] {
let temp = tempfile::tempdir().unwrap();
let path = if qualified {
source_journal_path(temp.path(), "debug", "session")
} else {
journal_path(temp.path(), "session")
};
let record = line(
&json!({"source":"debug","session_id":"session","event":"e","ts_ms":1,"payload":{}}),
);
write_legacy(&path, &record).await;
let outcomes = futures::future::join_all(
(0..16).map(|_| SessionStorage::open(temp.path(), "debug", "session")),
)
.await;
for storage in outcomes {
assert_eq!(
storage.unwrap().status().await.unwrap().event_tail,
record.len() as u64
);
}
assert!(!path.exists());
}
}
47 changes: 45 additions & 2 deletions bt-daemon/src/transcript_import/claude.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,10 @@ use super::{
string_at, timestamp_bounds, timestamp_ms, validate_session_id, IncrementalRecords,
TailSession, TranscriptImport, TranscriptLayout,
};
use crate::translate::{claude_task_notification_id, ClaudeSubagentHook, ClaudeUserPromptHook};
use crate::wire::Envelope;
use anyhow::bail;
use serde::Deserialize;
use serde_json::{json, Value};
use std::collections::{HashMap, HashSet};
use std::io::BufRead;
Expand All @@ -30,6 +32,7 @@ pub(super) struct Tail {
completed_turns: usize,
active_turn: Option<usize>,
last_len: u64,
pending_background_stops: HashSet<String>,
}

impl TailSession for Tail {
Expand All @@ -55,6 +58,9 @@ impl TailSession for Tail {
if events.len() < 2 {
bail!("Claude import did not produce session boundary events");
}
// A cold historical import already has the complete child transcript.
// During attach, async launch results are links, not completion events.
let attaching = !finalize || self.started;
let mut out = Vec::new();
if !self.started {
out.push(events[0].clone());
Expand All @@ -77,10 +83,37 @@ impl TailSession for Tail {
let start = turn_starts[turn];
let end = turn_starts.get(turn + 1).copied().unwrap_or(middle.len());
let skip = usize::from(self.active_turn == Some(turn));
out.extend(middle[start + skip..end].iter().cloned());
for event in &middle[start + skip..end] {
if attaching && event.event == "SubagentStop" {
if let Ok(hook) = ClaudeSubagentHook::deserialize(&event.payload) {
if hook.import_background {
self.pending_background_stops.insert(hook.agent_id);
continue;
}
}
}
out.push(event.clone());
}
self.completed_turns += 1;
self.active_turn = None;
}
let notifications = turn_starts
.iter()
.filter_map(|&index| {
let hook = ClaudeUserPromptHook::deserialize(&middle[index].payload).ok()?;
claude_task_notification_id(hook.text()?)
})
.collect::<HashSet<_>>();
for event in middle.iter().filter(|event| event.event == "SubagentStop") {
let Ok(hook) = ClaudeSubagentHook::deserialize(&event.payload) else {
continue;
};
let id = hook.agent_id.as_str();
if (finalize || notifications.contains(id)) && self.pending_background_stops.remove(id)
{
out.push(event.clone());
}
}
if !finalize && turn_count > 0 {
let active = turn_count - 1;
if self.active_turn != Some(active) {
Expand Down Expand Up @@ -290,7 +323,8 @@ pub(super) fn envelopes(
"agent_type": subagent.agent_type,
"agent_transcript_path": subagent.path,
"_bt_import_parent_agent_id": subagent.parent_agent_id,
"_bt_import_parent_tool_id": subagent.parent_tool_id
"_bt_import_parent_tool_id": subagent.parent_tool_id,
"_bt_import_background": subagent.background
});
if !is_start {
payload["last_assistant_message"] = json!(subagent
Expand Down Expand Up @@ -359,6 +393,7 @@ struct Subagent {
parent_agent_id: Option<String>,
parent_tool_id: Option<String>,
depth: usize,
background: bool,
}

fn subagents(path: &Path, records: &[Value]) -> anyhow::Result<Vec<Subagent>> {
Expand Down Expand Up @@ -527,6 +562,10 @@ fn subagents(path: &Path, records: &[Value]) -> anyhow::Result<Vec<Subagent>> {
parent_agent_id: None,
parent_tool_id: None,
depth: 0,
background: records[record_index]
.pointer("/toolUseResult/status")
.and_then(Value::as_str)
== Some("async_launched"),
})
})
.collect::<Vec<_>>();
Expand Down Expand Up @@ -643,6 +682,10 @@ fn subagents(path: &Path, records: &[Value]) -> anyhow::Result<Vec<Subagent>> {
parent_agent_id: parent_id,
parent_tool_id,
depth,
background: records[record_index]
.pointer("/toolUseResult/status")
.and_then(Value::as_str)
== Some("async_launched"),
});
linked.insert(agent_id.clone());
added = true;
Expand Down
48 changes: 48 additions & 0 deletions bt-daemon/src/transcript_import/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1592,6 +1592,54 @@ mod tests {
assert!(!tail.retry_envelopes);
}

#[test]
fn claude_attach_keeps_background_agent_open_until_its_final_records_arrive() {
let temp = tempfile::tempdir().unwrap();
let path = temp.path().join("session-a.jsonl");
let child = temp.path().join("session-a/subagents/agent-child-a.jsonl");
std::fs::create_dir_all(child.parent().unwrap()).unwrap();
let write = |path: &Path, records: &[Value]| {
std::fs::write(
path,
records
.iter()
.map(|record| format!("{record}\n"))
.collect::<String>(),
)
.unwrap();
};
write(
&path,
&[
json!({"type":"user","sessionId":"session-a","timestamp":"2026-01-01T00:00:01Z","message":{"content":"delegate"}}),
json!({"type":"assistant","timestamp":"2026-01-01T00:00:02Z","message":{"content":[{"type":"tool_use","id":"call-a","name":"Agent","input":{"subagent_type":"reviewer"}}]}}),
json!({"type":"user","timestamp":"2026-01-01T00:00:03Z","toolUseResult":{"agentId":"child-a","status":"async_launched"},"message":{"content":[{"type":"tool_result","tool_use_id":"call-a","content":"launched"}]}}),
json!({"type":"user","timestamp":"2026-01-01T00:00:04Z","message":{"content":"next prompt"}}),
],
);
let started = json!({"type":"user","timestamp":"2026-01-01T00:00:02Z","message":{"content":"review"}});
write(&child, std::slice::from_ref(&started));

let mut tail = TranscriptTail::new(path, ImportSource::Claude);
let initial = tail.poll(false).unwrap();
assert!(initial.iter().any(|event| event.event == "SubagentStart"));
assert!(!initial.iter().any(|event| event.event == "SubagentStop"));
write(
&child,
&[
started,
json!({"type":"assistant","timestamp":"2026-01-01T00:00:06Z","message":{"id":"late","content":[{"type":"text","text":"reviewed"}]}}),
],
);
let terminal = tail.poll(true).unwrap();
let stop = terminal
.iter()
.find(|event| event.event == "SubagentStop")
.unwrap();
assert_eq!(stop.payload["last_assistant_message"], "reviewed");
assert_eq!(stop.ts_ms, 1_767_225_606_000);
}

#[test]
fn claude_tail_closes_only_completed_turns() {
let temp = tempfile::tempdir().unwrap();
Expand Down
8 changes: 5 additions & 3 deletions bt-daemon/src/translate/claude.rs
Original file line number Diff line number Diff line change
Expand Up @@ -17,17 +17,19 @@ mod timestamp_envelope;
mod transcript_envelope;
mod transcript_tool;
mod transcript_tool_outcome;
mod user_prompt_hook;

use hook_context::HookContext;
use llm_call::LlmCall;
use message_history::MessageHistory;
use parsed_transcript::ParsedTranscript;
use subagent_hook::SubagentHook;
pub(crate) use subagent_hook::SubagentHook;
#[cfg(test)]
use timestamp_envelope::parse_rfc3339_timestamp;
use timestamp_envelope::parse_timestamp_ms;
use transcript_envelope::TranscriptEnvelope;
use transcript_tool::TranscriptTool;
pub(crate) use user_prompt_hook::UserPromptHook;

use super::git::GitMetadataCache;
use super::recent::{RecentMap, RecentSet, RECENT_ID_CAPACITY};
Expand Down Expand Up @@ -1644,7 +1646,7 @@ fn continuation_origin(payload: &Value) -> Option<(&'static str, &str)> {
return (!id.is_empty()).then_some(("agent_message", id));
}
}
let prompt = payload.get("prompt")?.as_str()?.trim();
let prompt = UserPromptHook::deserialize(payload).ok()?.text()?.trim();
if let Some(id) = task_notification_id(prompt) {
return Some(("task_notification", id));
}
Expand All @@ -1656,7 +1658,7 @@ fn continuation_origin(payload: &Value) -> Option<(&'static str, &str)> {
Some(("agent_message", id))
}

fn task_notification_id(prompt: &str) -> Option<&str> {
pub(crate) fn task_notification_id(prompt: &str) -> Option<&str> {
let body = prompt
.trim()
.strip_prefix("<task-notification>")?
Expand Down
6 changes: 4 additions & 2 deletions bt-daemon/src/translate/claude/subagent_hook.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,11 +2,13 @@ use super::native_field::{deserialize_nonempty_string, deserialize_optional_stri
use serde::{Deserialize, Serialize};

#[derive(Deserialize, Serialize)]
pub(super) struct SubagentHook {
pub(crate) struct SubagentHook {
#[serde(deserialize_with = "deserialize_nonempty_string")]
pub(super) agent_id: String,
pub(crate) agent_id: String,
#[serde(default, deserialize_with = "deserialize_optional_string")]
pub(super) agent_type: Option<String>,
#[serde(default, deserialize_with = "deserialize_optional_string")]
pub(super) agent_transcript_path: Option<String>,
#[serde(rename = "_bt_import_background", default)]
pub(crate) import_background: bool,
}
24 changes: 24 additions & 0 deletions bt-daemon/src/translate/claude/user_prompt_hook.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
use serde::Deserialize;

/// Text projection of a prompt hook. Imported prompts may also contain blocks.
#[derive(Deserialize)]
pub(crate) struct UserPromptHook<'a> {
#[serde(default, borrow)]
prompt: Option<PromptText<'a>>,
}

#[derive(Deserialize)]
#[serde(untagged)]
enum PromptText<'a> {
Text(&'a str),
Other(serde::de::IgnoredAny),
}

impl<'a> UserPromptHook<'a> {
pub(crate) fn text(&self) -> Option<&'a str> {
match self.prompt.as_ref()? {
PromptText::Text(text) => Some(text),
PromptText::Other(_) => None,
}
}
}
5 changes: 4 additions & 1 deletion bt-daemon/src/translate/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,10 @@ mod muse;
mod opencode;
mod opencode_v2;
mod pi;
pub(crate) use claude::successful_subagent_handback_message;
pub(crate) use claude::{
successful_subagent_handback_message, task_notification_id as claude_task_notification_id,
SubagentHook as ClaudeSubagentHook, UserPromptHook as ClaudeUserPromptHook,
};
pub(crate) use pi::request_config as pi_request_config;
mod origins;
pub(crate) mod recent;
Expand Down
7 changes: 7 additions & 0 deletions bt-daemon/tests/agent_integration.rs
Original file line number Diff line number Diff line change
Expand Up @@ -368,6 +368,13 @@ async fn pi_session_emits_traces() {
if request.has_function_output("call_pi_1") {
return MockReply::response(OpenAiTurn::text("PI_MOCK_OK"));
}
// Oh My Pi sends auxiliary requests without tools to the same
// provider before the actual prompt. Only drive the shell turn when
// tools are offered. The assertions below still require the tool
// call, its result, and their delivered trace.
if request.tool_names().is_empty() {
return MockReply::response(OpenAiTurn::text("Integration test"));
}
MockReply::response(shell_tool_call(
&request,
"call_pi_1",
Expand Down
18 changes: 6 additions & 12 deletions src/plugins/pi/content/src/daemon-adapter.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,18 +17,12 @@ const mockState = vi.hoisted(() => ({
permalink: "https://www.braintrust.dev/trace/1" as string | undefined,
}));

vi.mock("@earendil-works/pi-tui", async (importOriginal) => {
const original = await importOriginal<typeof import("@earendil-works/pi-tui")>();
return {
...original,
get getCapabilities() {
return mockState.ompTui ? undefined : () => ({ hyperlinks: mockState.hyperlinks });
},
get hyperlink() {
return mockState.ompTui ? undefined : original.hyperlink;
},
};
});
vi.mock("./pi-tui.ts", () => ({
loadPiHyperlinkHelpers: async () =>
mockState.ompTui
? {}
: { getCapabilities: () => ({ hyperlinks: mockState.hyperlinks }), hyperlink },
}));

vi.mock("./runtime/daemon-client.ts", () => ({
claimManagedTracingInstance: () => mockState.claim,
Expand Down
Loading
Loading