diff --git a/bt-daemon/src/collections/legacy.rs b/bt-daemon/src/collections/legacy.rs index 60853be3..43564bfd 100644 --- a/bt-daemon/src/collections/legacy.rs +++ b/bt-daemon/src/collections/legacy.rs @@ -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, @@ -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?; @@ -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?; } diff --git a/bt-daemon/src/collections/tests.rs b/bt-daemon/src/collections/tests.rs index e3de1129..1974cc99 100644 --- a/bt-daemon/src/collections/tests.rs +++ b/bt-daemon/src/collections/tests.rs @@ -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()); + } +} diff --git a/bt-daemon/src/translate/claude.rs b/bt-daemon/src/translate/claude.rs index 66db8853..9098992a 100644 --- a/bt-daemon/src/translate/claude.rs +++ b/bt-daemon/src/translate/claude.rs @@ -14,9 +14,11 @@ mod native_field; mod parsed_transcript; mod subagent_hook; mod timestamp_envelope; +mod transcript_content; mod transcript_envelope; mod transcript_tool; mod transcript_tool_outcome; +mod user_prompt_hook; use hook_context::HookContext; use llm_call::LlmCall; @@ -26,8 +28,10 @@ use subagent_hook::SubagentHook; #[cfg(test)] use timestamp_envelope::parse_rfc3339_timestamp; use timestamp_envelope::parse_timestamp_ms; +use transcript_content::TranscriptContent; use transcript_envelope::TranscriptEnvelope; use transcript_tool::TranscriptTool; +use user_prompt_hook::UserPromptHook; use super::git::GitMetadataCache; use super::recent::{RecentMap, RecentSet, RECENT_ID_CAPACITY}; @@ -72,7 +76,7 @@ struct Turn { #[derive(Serialize, Deserialize)] struct PendingPrompt { turn_id: Arc, - content: Value, + content: TranscriptContent, } #[derive(Default, Serialize, Deserialize)] @@ -350,7 +354,7 @@ impl ClaudeTranslator { ) } - fn open_turn(&mut self, event: &Envelope, ops: &mut Vec) { + fn open_turn(&mut self, event: &Envelope, prompt: UserPromptHook, ops: &mut Vec) { self.session_status = Some("running".into()); if let Some(old) = self.turn.take() { self.close_pending_tools( @@ -369,7 +373,8 @@ impl ClaudeTranslator { ..Default::default() })); } - let continuation = continuation_origin(&event.payload); + let text = prompt.prompt.as_ref().and_then(TranscriptContent::as_text); + let continuation = continuation_origin(&event.payload, text); let (id, parent_id, user_turn_id, name) = if let Some((_, task_id)) = continuation { self.continuation_count += 1; let owner = self @@ -402,7 +407,7 @@ impl ClaudeTranslator { // as directly as a `/x` slash command. Continuations are runtime // notifications, not user requests. if continuation.is_none() { - if let Some(prompt) = event.payload.get("prompt").and_then(Value::as_str) { + if let Some(prompt) = text { for name in prompt_skill_names(prompt) { push_unique(&mut self.requested_skills, name); } @@ -433,7 +438,7 @@ impl ClaudeTranslator { span_type: SpanType::Task, is_turn: true, start_ms: Some(event.ts_ms), - input: event.payload.get("prompt").cloned(), + input: (!prompt.prompt.is_missing()).then(|| json!(prompt.prompt)), metadata: (!metadata.is_empty()).then_some(Value::Object(metadata)), turn_span_id: Some(owner.clone()), ..Default::default() @@ -446,14 +451,12 @@ impl ClaudeTranslator { self.prompt_turns .insert(prompt_id.to_owned(), turn_id.clone()); } - if let Some(content) = event.payload.get("prompt").filter(|value| !value.is_null()) { + if let crate::json::Field::Value(content) = prompt.prompt { if self.pending_prompts.len() == RECENT_ID_CAPACITY { self.pending_prompts.pop_front(); } - self.pending_prompts.push_back(PendingPrompt { - turn_id, - content: content.clone(), - }); + self.pending_prompts + .push_back(PendingPrompt { turn_id, content }); } self.turn = Some(Turn { id, @@ -992,7 +995,11 @@ impl ClaudeTranslator { // Hooks carry prompt_id only after the first user input, and older Claude // versions omit it. Without it, match prompts in submission order, then // retain transcript identities so repeats cannot consume another turn. - fn user_record_turn(&mut self, record: &Value) -> Option> { + fn user_record_turn( + &mut self, + record: &Value, + row: &TranscriptEnvelope, + ) -> Option> { let prompt_id = record.get("promptId").and_then(Value::as_str); let mut owner = prompt_id .and_then(|id| self.prompt_turns.get(id)) @@ -1007,9 +1014,8 @@ impl ClaudeTranslator { if let Some(owner) = &owner { &pending.turn_id == owner } else { - record - .pointer("/message/content") - .is_some_and(|content| prompt_matches(&pending.content, content)) + row.content() + .is_some_and(|content| content.matches_prompt(&pending.content)) } }) { owner = self @@ -1028,12 +1034,13 @@ impl ClaudeTranslator { // each user record before propagating its owner through record ancestry. fn observe_record_turns(&mut self, records: &[Value], ops: &mut Vec) { for record in records { - let user_prompt = is_real_user_record(record) - && record.get("queueTranscriptOnly").and_then(Value::as_bool) != Some(true); - if user_prompt { - self.main_record_turn = self.user_record_turn(record); + let user_prompt = TranscriptEnvelope::deserialize(record) + .ok() + .filter(|row| row.is_user_prompt() && !row.queue_transcript_only); + if let Some(row) = &user_prompt { + self.main_record_turn = self.user_record_turn(record, row); } - let owner = if user_prompt { + let owner = if user_prompt.is_some() { self.main_record_turn.clone() } else { record @@ -1044,10 +1051,11 @@ impl ClaudeTranslator { .or_else(|| self.main_record_turn.clone()) }; let Some(owner) = owner else { continue }; - if user_prompt { - if let Some(content) = record - .pointer("/message/content") - .filter(|content| crate::attachments::contains(content)) + if let Some(row) = user_prompt { + if let Some(content) = row + .content() + .map(|content| json!(content)) + .filter(crate::attachments::contains) { let identity = self.turn_identities @@ -1064,7 +1072,7 @@ impl ClaudeTranslator { span_id: owner.to_string(), root_span_id, parent_span_ids: vec![parent_id], - input: Some(content.clone()), + input: Some(content), turn_span_id: self.owner_of(owner.as_str()), ..Default::default() })); @@ -1155,19 +1163,39 @@ impl ClaudeTranslator { } } - fn flush_previous_turn_rows(&mut self, ops: &mut Vec) { - let (Some(path), Some(parent)) = (self.main_transcript.clone(), self.last_turn_id.clone()) - else { + fn flush_previous_turn_rows(&mut self, prompt: &UserPromptHook, ops: &mut Vec) { + let previous = self.turn.as_ref().map_or_else( + || { + self.last_turn_id + .clone() + .map(|id| (id, self.last_turn_cwd.clone())) + }, + |turn| Some((turn.id.clone(), turn.cwd.clone())), + ); + let (Some(path), Some((parent, cwd))) = (self.main_transcript.clone(), previous) else { return; }; let Some(cursor) = self.transcripts.get_mut(&path) else { return; }; - let split = cursor - .buffered - .iter() - .rposition(is_real_user_record) - .unwrap_or(cursor.buffered.len()); + let split = if self.turn.is_some() { + // The replacement hook can run before its prompt is written. In + // that case all bytes observed by this hook belong to the old turn. + prompt.prompt.as_ref().and_then(|prompt| { + cursor.buffered.iter().rposition(|record| { + TranscriptEnvelope::deserialize(record).is_ok_and(|row| { + row.is_user_prompt() + && !row.queue_transcript_only + && row + .content() + .is_some_and(|content| content.matches_prompt(prompt)) + }) + }) + }) + } else { + cursor.buffered.iter().rposition(is_real_user_record) + } + .unwrap_or(cursor.buffered.len()); let current_turn_rows = cursor.buffered.split_off(split); let previous_rows = std::mem::replace(&mut cursor.buffered, current_turn_rows); self.queue_transcript( @@ -1175,7 +1203,7 @@ impl ClaudeTranslator { PendingHistory::Main, "main".into(), parent, - self.last_turn_cwd.clone(), + cwd, ops, ); } @@ -1411,9 +1439,10 @@ impl AgentTranslator for ClaudeTranslator { } } "UserPromptSubmit" => { - self.flush_previous_turn_rows(&mut ops); + let prompt = UserPromptHook::deserialize(&event.payload).unwrap_or_default(); + self.flush_previous_turn_rows(&prompt, &mut ops); event_op_start = ops.len(); - self.open_turn(event, &mut ops); + self.open_turn(event, prompt, &mut ops); } "UserPromptExpansion" => self.record_skill(event, &mut ops), "PreToolUse" => self.pre_tool(event, &mut ops), @@ -1632,7 +1661,10 @@ pub(crate) fn successful_subagent_handback_message(records: &[Value]) -> Option< .and_then(|tool| tool.handback_message()) } -fn continuation_origin(payload: &Value) -> Option<(&'static str, &str)> { +fn continuation_origin<'a>( + payload: &'a Value, + prompt: Option<&'a str>, +) -> Option<(&'static str, &'a str)> { if let Some(origin) = payload.get("origin") { if origin.get("kind").and_then(Value::as_str) == Some("peer") && origin.get("handback").and_then(Value::as_bool) == Some(true) @@ -1644,7 +1676,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 = prompt?.trim(); if let Some(id) = task_notification_id(prompt) { return Some(("task_notification", id)); } @@ -1667,49 +1699,10 @@ fn task_notification_id(prompt: &str) -> Option<&str> { (!id.is_empty()).then_some(id) } -fn prompt_matches(prompt: &Value, content: &Value) -> bool { - if prompt == content { - return true; - } - let (Some(mut remaining), Some(blocks)) = (prompt.as_str(), content.as_array()) else { - return false; - }; - // Native hooks use a string, while transcripts may wrap the same prompt - // in text blocks alongside images. Compare without allocating a joined copy. - let mut has_text = false; - for text in blocks.iter().filter_map(|block| { - (block.get("type").and_then(Value::as_str) == Some("text")) - .then(|| block.get("text").and_then(Value::as_str)) - .flatten() - }) { - has_text = true; - let Some(rest) = remaining.strip_prefix(text) else { - return false; - }; - remaining = rest; - } - remaining.is_empty() && (has_text || crate::attachments::contains(content)) -} - fn is_real_user_record(record: &Value) -> bool { - let Some(envelope) = decode::(record) else { - return false; - }; - if envelope.kind.as_deref() != Some("user") { - return false; - } - if envelope.is_compact_summary { - return false; - } - !record - .pointer("/message/content") - .and_then(Value::as_array) - .is_some_and(|blocks| { - blocks - .iter() - .any(|block| block.get("type").and_then(Value::as_str) == Some("tool_result")) - }) + TranscriptEnvelope::deserialize(record).is_ok_and(|row| row.is_user_prompt()) } + /// Read newline-delimited records forward from `offset`, advancing it past /// everything consumed. /// diff --git a/bt-daemon/src/translate/claude/transcript_content.rs b/bt-daemon/src/translate/claude/transcript_content.rs new file mode 100644 index 00000000..eaf4aa15 --- /dev/null +++ b/bt-daemon/src/translate/claude/transcript_content.rs @@ -0,0 +1,60 @@ +use crate::json::Field; +use serde::{Deserialize, Serialize}; +use serde_json::Value; +use std::collections::BTreeMap; + +/// Content shared by the prompt hook and native transcript messages. +#[derive(Clone, PartialEq, Deserialize, Serialize)] +#[serde(untagged)] +pub(super) enum TranscriptContent { + Text(String), + Blocks(Vec), + // Keep unfamiliar content shapes readable in checkpoints and span input. + Unknown(Value), +} + +#[derive(Clone, PartialEq, Deserialize, Serialize)] +pub(super) struct TranscriptBlock { + #[serde(rename = "type", default, skip_serializing_if = "Field::is_missing")] + pub(super) kind: Field, + #[serde(default, skip_serializing_if = "Field::is_missing")] + pub(super) text: Field, + // Preserve tool data and future native block fields when emitting content. + #[serde(flatten)] + extensions: BTreeMap, +} + +impl TranscriptContent { + pub(super) fn as_text(&self) -> Option<&str> { + match self { + Self::Text(text) => Some(text), + Self::Blocks(_) | Self::Unknown(_) => None, + } + } + + pub(super) fn has_tool_result(&self) -> bool { + matches!(self, Self::Blocks(blocks) if blocks.iter().any(|block| block.kind.as_deref() == Some("tool_result"))) + } + + pub(super) fn matches_prompt(&self, prompt: &Self) -> bool { + if self == prompt { + return true; + } + let (Some(mut remaining), Self::Blocks(blocks)) = (prompt.as_text(), self) else { + return false; + }; + let mut has_text = false; + for text in blocks.iter().filter_map(|block| { + (block.kind.as_deref() == Some("text")) + .then(|| block.text.as_deref()) + .flatten() + }) { + has_text = true; + let Some(rest) = remaining.strip_prefix(text) else { + return false; + }; + remaining = rest; + } + remaining.is_empty() && (has_text || crate::attachments::contains(&serde_json::json!(self))) + } +} diff --git a/bt-daemon/src/translate/claude/transcript_envelope.rs b/bt-daemon/src/translate/claude/transcript_envelope.rs index 1bbfa928..7079098e 100644 --- a/bt-daemon/src/translate/claude/transcript_envelope.rs +++ b/bt-daemon/src/translate/claude/transcript_envelope.rs @@ -1,7 +1,7 @@ +use super::transcript_content::TranscriptContent; use serde::{Deserialize, Serialize}; -/// Stable routing fields from one Claude transcript row. Message and tool -/// blocks intentionally remain raw because they are preserved in span I/O. +/// Stable routing fields from one Claude transcript row. #[derive(Deserialize, Serialize)] pub(super) struct TranscriptEnvelope { #[serde(rename = "type", default)] @@ -10,4 +10,26 @@ pub(super) struct TranscriptEnvelope { pub(super) subtype: Option, #[serde(rename = "isCompactSummary", default)] pub(super) is_compact_summary: bool, + #[serde(rename = "queueTranscriptOnly", default)] + pub(super) queue_transcript_only: bool, + message: Option, +} + +#[derive(Deserialize, Serialize)] +struct TranscriptMessage { + content: Option, +} + +impl TranscriptEnvelope { + pub(super) fn content(&self) -> Option<&TranscriptContent> { + self.message.as_ref()?.content.as_ref() + } + + pub(super) fn is_user_prompt(&self) -> bool { + self.kind.as_deref() == Some("user") + && !self.is_compact_summary + && !self + .content() + .is_some_and(TranscriptContent::has_tool_result) + } } diff --git a/bt-daemon/src/translate/claude/user_prompt_hook.rs b/bt-daemon/src/translate/claude/user_prompt_hook.rs new file mode 100644 index 00000000..49cba557 --- /dev/null +++ b/bt-daemon/src/translate/claude/user_prompt_hook.rs @@ -0,0 +1,9 @@ +use super::transcript_content::TranscriptContent; +use crate::json::Field; +use serde::Deserialize; + +#[derive(Default, Deserialize)] +pub(super) struct UserPromptHook { + #[serde(default)] + pub(super) prompt: Field, +} diff --git a/bt-daemon/tests/agent_integration.rs b/bt-daemon/tests/agent_integration.rs index df5a5787..b26d3309 100644 --- a/bt-daemon/tests/agent_integration.rs +++ b/bt-daemon/tests/agent_integration.rs @@ -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", diff --git a/bt-daemon/tests/claude_translator.rs b/bt-daemon/tests/claude_translator.rs index 39df0b2f..8cbdca1e 100644 --- a/bt-daemon/tests/claude_translator.rs +++ b/bt-daemon/tests/claude_translator.rs @@ -3108,3 +3108,59 @@ fn claude_expansion_before_submit_reaches_the_incoming_turn_while_another_is_ope let skill = tool_span(&rows, "review").metadata.as_ref().unwrap(); assert_eq!(skill["skill_load_trigger"], json!("explicit")); } + +#[test] +fn claude_mid_turn_notification_keeps_buffered_calls_under_their_turn() { + let prompt = "workercompleted"; + let launched = json!({"type":"assistant","message":{"id":"launch","content":[{"type":"text","text":"started"}]}}); + let notification = json!({"type":"user","message":{"content":prompt}}); + let reply = json!({"type":"assistant","message":{"id":"reply","content":[{"type":"text","text":"done"}]}}); + let rows = replay_continuation_events( + vec![ + ("UserPromptSubmit", 10, json!({"prompt":"delegate"})), + ( + "SubagentStart", + 15, + json!({"agent_id":"worker","agent_type":"Explore"}), + ), + ( + "UserPromptSubmit", + 20, + json!({ + "prompt":prompt, + "transcript_path":"main.jsonl", + "_bt_transcript_snapshot":{"path":"main.jsonl","contents":format!("{launched}\n{notification}\n")} + }), + ), + ( + "Stop", + 30, + json!({ + "transcript_path":"main.jsonl", + "_bt_transcript_snapshot":{"path":"main.jsonl","contents":format!("{launched}\n{notification}\n{reply}\n")} + }), + ), + ], + false, + ); + for (request, name) in [ + ("launch", "Turn 1"), + ("reply", "Continuation: subagent result"), + ] { + let turn = rows.values().find(|row| row.name == name).unwrap(); + let call = rows + .values() + .find(|row| { + row.metadata + .as_ref() + .and_then(|metadata| metadata.get("request_id")) + == Some(&json!(request)) + }) + .unwrap(); + assert_eq!( + call.parent_span_ids, + vec![turn.span_id.clone()], + "{request}" + ); + } +} diff --git a/src/plugins/pi/content/src/daemon-adapter.test.ts b/src/plugins/pi/content/src/daemon-adapter.test.ts index fc081359..6a189f93 100644 --- a/src/plugins/pi/content/src/daemon-adapter.test.ts +++ b/src/plugins/pi/content/src/daemon-adapter.test.ts @@ -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(); - 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, diff --git a/src/plugins/pi/content/src/index.ts b/src/plugins/pi/content/src/index.ts index 96525040..21d82e68 100644 --- a/src/plugins/pi/content/src/index.ts +++ b/src/plugins/pi/content/src/index.ts @@ -1,10 +1,10 @@ import { createHash, randomUUID } from "node:crypto"; import { resolve } from "node:path"; import type { ExtensionAPI, ExtensionContext } from "@earendil-works/pi-coding-agent"; -import * as piTui from "@earendil-works/pi-tui"; import { loadConfig } from "./config.ts"; import { legacyContinuationFor, type LegacyContinuation } from "./legacy-session.ts"; import { runningPiPackage } from "./pi-package.ts"; +import { loadPiHyperlinkHelpers } from "./pi-tui.ts"; import { claimManagedTracingInstance, DaemonClient } from "./runtime/daemon-client.ts"; import { EXTENSION_VERSION } from "./version.ts"; @@ -18,13 +18,8 @@ const TRACE_LINK_POLL_TIMEOUT_MS = 40_000; const PI_VERSION = runningPiPackage().version; const PI_HOST_NAME = runningPiPackage().name; -/** - * Oh My Pi resolves this package to its own pi-tui, which exports neither - * helper. A named import would fail to link and OMP would silently drop the - * extension, so read them from the namespace and fall back to plain text. - */ -function terminalHyperlink(text: string, url: string): string | undefined { - const { getCapabilities, hyperlink } = piTui as Partial; +async function terminalHyperlink(text: string, url: string): Promise { + const { getCapabilities, hyperlink } = await loadPiHyperlinkHelpers(PI_HOST_NAME); if (typeof getCapabilities !== "function" || typeof hyperlink !== "function") return undefined; return getCapabilities().hyperlinks ? hyperlink(text, url) : undefined; } @@ -149,10 +144,9 @@ export default function braintrustPiExtension(pi: ExtensionAPI): void { if (daemonSession?.last_error) { ctx.ui.setStatus(STATUS_KEY, `Braintrust: ${daemonSession.last_error}`); } else { - ctx.ui.setStatus( - STATUS_KEY, - (permalink && terminalHyperlink(traceLabel, permalink)) || "Braintrust: connected", - ); + const label = permalink ? await terminalHyperlink(traceLabel, permalink) : undefined; + if (uiGeneration !== refreshGeneration || sessionId !== refreshSessionId) return; + ctx.ui.setStatus(STATUS_KEY, label ?? "Braintrust: connected"); } traceLinkShown = Boolean(permalink); }; diff --git a/src/plugins/pi/content/src/pi-tui.ts b/src/plugins/pi/content/src/pi-tui.ts new file mode 100644 index 00000000..6f9ecb53 --- /dev/null +++ b/src/plugins/pi/content/src/pi-tui.ts @@ -0,0 +1,18 @@ +type PiTui = typeof import("@earendil-works/pi-tui"); +type HyperlinkHelpers = Pick; + +/** Pi's UI helpers are optional for a tracing extension and unavailable in Oh My Pi. */ +export async function loadPiHyperlinkHelpers( + host: string | undefined, +): Promise> { + if (host === "@oh-my-pi/pi-coding-agent") return {}; + try { + // Resolve only in the Pi UI path. Oh My Pi rejects package imports of + // the old TUI at extension load time, including literal dynamic imports. + const url = import.meta.resolve("@earendil-works/pi-tui"); + return (await import(url)) as PiTui; + } catch { + // Some hosts supply the extension API without Pi's optional UI helpers. + return {}; + } +}