Skip to content

Commit cc528db

Browse files
wpfleger96Hayt
andauthored
feat(agents): request summarized Claude thinking and label empty rows (#8051)
Claude Code agents on Opus showed Thinking rows that opened to nothing. Opus returns no readable thinking unless Claude Code is asked for summaries, and Buzz never asked. Sonnet returns readable thinking either way. **Request summaries from Claude Code.** `session_new_full` now adds `_meta.claudeCode.options.extraArgs: {"thinking-display": "summarized"}` for the Claude adapter. claude-agent-acp spreads `extraArgs` into the CLI's arguments; 0.36.1, 0.60.0 and 0.66.0 all read the same shape. The value is merged into the existing `_meta`, so `systemPrompt` and `sessionTitle` are kept. `session_new_full` is the only place Buzz sends `session/new`, so agent sessions and model discovery both get it. **Only for a CLI that accepts the flag.** `--thinking-display` first shipped in Claude Code 2.1.94, and older CLIs exit on unknown flags, which would fail every session start. When the adapter is spawned, Buzz runs `$CLAUDE_CODE_EXECUTABLE --version` once with a 5-second limit, reading at most 256 bytes of output and killing its whole process group on timeout, and sends the flag only on 2.1.94 or newer. The flag is left off, and sessions start exactly as before, when: - the CLI is older than 2.1.94; - `CLAUDE_CODE_EXECUTABLE` is unset (the adapter then runs its own bundled CLI, which Buzz can't inspect) or empty; - the binary hangs, fails, or prints anything other than a clean `major.minor.patch` version; - `BUZZ_ACP_LAUNCH_PREFIX` is set, since the wrapper can change which CLI the adapter actually runs. The result is logged once at debug level. **Label rows that still have no text.** A Thinking row whose text is empty or only whitespace keeps its header and shows a muted "No readable reasoning tokens", with nothing to expand. This covers models or CLIs that still return no readable thinking. If text arrives later in the same row, it renders as an expandable section as before. `ThoughtActivity` is the only component that draws Thinking rows. --------- Signed-off-by: Will Pfleger <[email protected]> Co-authored-by: Hayt <211b96e6a2b7f45fd4047988976c7bbbeeda0c15f3ae7b32eec20834b5a55118@buzz.block.builderlab.xyz>
1 parent 133fb98 commit cc528db

5 files changed

Lines changed: 424 additions & 14 deletions

File tree

‎crates/buzz-acp/src/acp.rs‎

Lines changed: 245 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -221,6 +221,10 @@ pub struct AcpClient {
221221
standard_usage: StandardUsageTracker,
222222
/// Known adapter identity for prompt-response usage mapping.
223223
standard_adapter: Option<StandardAdapterKind>,
224+
/// Ask Claude Code for summarized thinking on `session/new`. Opus omits
225+
/// readable thinking unless asked; set only when the CLI the adapter runs
226+
/// is new enough to accept `--thinking-display`.
227+
claude_thinking_summaries: bool,
224228
}
225229

226230
/// Recursively merge `overlay` into `base`, with `overlay` winning on scalar/shape
@@ -478,6 +482,9 @@ impl AcpClient {
478482
) -> Result<Self, AcpError> {
479483
use std::process::Stdio;
480484

485+
// A launch prefix may change the CLI or environment the adapter sees,
486+
// so the version check below could inspect the wrong binary.
487+
let launch_prefixed = std::env::var_os(launch::PREFIX_ENV).is_some();
481488
let mut cmd = launch::command(command, args)?;
482489
if crate::config::normalize_agent_command_identity(command) == BUZZ_PI_ACP_NAME {
483490
if !args.iter().any(|arg| arg == "--") {
@@ -589,6 +596,9 @@ impl AcpClient {
589596
};
590597
cmd.envs(launch_env.iter().cloned());
591598
cmd.env_remove(launch::PREFIX_ENV);
599+
let claude_thinking_summaries = standard_adapter == Some(StandardAdapterKind::Claude)
600+
&& !launch_prefixed
601+
&& claude_cli_accepts_thinking_display(&cmd).await;
592602
let mut child = cmd.spawn().map_err(|error| {
593603
std::io::Error::new(
594604
error.kind(),
@@ -623,6 +633,7 @@ impl AcpClient {
623633
goose_usage: UsageTracker::default(),
624634
standard_usage: StandardUsageTracker::default(),
625635
standard_adapter,
636+
claude_thinking_summaries,
626637
})
627638
}
628639

@@ -703,10 +714,11 @@ impl AcpClient {
703714
/// - `Some(SystemPromptTransport::ClaudeMeta(text))` — `_meta.systemPrompt`
704715
/// as `{"append": text}`, keeping claude-agent-acp's native preset intact.
705716
///
706-
/// `session_title` rides in `_meta.sessionTitle` when `Some`; `_meta` is
707-
/// omitted entirely otherwise, since adapters may distinguish an absent
708-
/// member from a null one. Metadata prompt transports and the title are
709-
/// merged into a single object.
717+
/// `session_title` rides in `_meta.sessionTitle` when `Some`, and a Claude
718+
/// CLI that supports it gets `_meta.claudeCode.options.extraArgs` asking
719+
/// for summarized thinking. These and the metadata prompt transports merge
720+
/// into a single object; with none of them, `_meta` is omitted entirely,
721+
/// since adapters may distinguish an absent member from a null one.
710722
///
711723
/// Callers use [`extract_model_config_options`] and [`extract_model_state`]
712724
/// to pull model info from the raw result.
@@ -738,6 +750,11 @@ impl AcpClient {
738750
// Merge — _meta may already carry a system prompt from an adapter extension.
739751
params["_meta"]["sessionTitle"] = serde_json::Value::String(title.to_owned());
740752
}
753+
if self.claude_thinking_summaries {
754+
// Merge — claude-agent-acp spreads these into the CLI's argv.
755+
params["_meta"]["claudeCode"]["options"]["extraArgs"]["thinking-display"] =
756+
serde_json::Value::String("summarized".to_owned());
757+
}
741758
let result = self.send_request("session/new", params).await?;
742759
let session_id = result["sessionId"]
743760
.as_str()
@@ -2400,6 +2417,99 @@ fn kill_process_group(_pid: u32) -> bool {
24002417
false
24012418
}
24022419

2420+
/// First Claude Code release with `--thinking-display`. Older CLIs exit on
2421+
/// unknown flags, so sending it to them would fail every `session/new`.
2422+
const CLAUDE_THINKING_DISPLAY_MIN_VERSION: (u64, u64, u64) = (2, 1, 94);
2423+
2424+
/// Parse `claude --version` output such as `2.1.284 (Claude Code)`. The
2425+
/// first word must be exactly three dot-separated digit runs.
2426+
fn parse_claude_version(output: &str) -> Option<(u64, u64, u64)> {
2427+
let mut parts = output.split_whitespace().next()?.split('.');
2428+
let mut next = || {
2429+
let part = parts.next()?;
2430+
part.bytes()
2431+
.all(|b| b.is_ascii_digit())
2432+
.then(|| part.parse().ok())?
2433+
};
2434+
let version = (next()?, next()?, next()?);
2435+
parts.next().is_none().then_some(version)
2436+
}
2437+
2438+
/// Whether the CLI claude-agent-acp will run accepts `--thinking-display`.
2439+
///
2440+
/// The adapter runs `CLAUDE_CODE_EXECUTABLE` when set and its bundled CLI
2441+
/// otherwise; the bundled one cannot be inspected from here, so an unset
2442+
/// variable, a hung or failing binary, or unparseable output all answer
2443+
/// `false` and leave the session exactly as before.
2444+
async fn claude_cli_accepts_thinking_display(cmd: &tokio::process::Command) -> bool {
2445+
const KEY: &str = "CLAUDE_CODE_EXECUTABLE";
2446+
let executable = cmd
2447+
.as_std()
2448+
.get_envs()
2449+
.find(|(key, _)| *key == KEY)
2450+
.map(|(_, value)| value.map(std::ffi::OsStr::to_os_string))
2451+
.unwrap_or_else(|| std::env::var_os(KEY))
2452+
.filter(|path| !path.is_empty());
2453+
let Some(executable) = executable else {
2454+
tracing::debug!(target: "acp::spawn", "{KEY} unset; not requesting thinking summaries");
2455+
return false;
2456+
};
2457+
let mut version_cmd = tokio::process::Command::new(&executable);
2458+
version_cmd.arg("--version");
2459+
configure_version_probe(&mut version_cmd);
2460+
let version = match version_cmd.spawn() {
2461+
Ok(child) => claude_version_within(child, std::time::Duration::from_secs(5)).await,
2462+
Err(_) => None,
2463+
};
2464+
let accepts = version.is_some_and(|v| v >= CLAUDE_THINKING_DISPLAY_MIN_VERSION);
2465+
tracing::debug!(
2466+
target: "acp::spawn",
2467+
"{executable:?} --version = {version:?}; thinking summaries requested: {accepts}"
2468+
);
2469+
accepts
2470+
}
2471+
2472+
/// Pipe stdout only, and put the probe in its own process group (like the
2473+
/// adapter) so a timeout also kills a launcher's children.
2474+
fn configure_version_probe(cmd: &mut tokio::process::Command) {
2475+
cmd.stdin(std::process::Stdio::null())
2476+
.stdout(std::process::Stdio::piped())
2477+
.stderr(std::process::Stdio::null())
2478+
.kill_on_drop(true);
2479+
#[cfg(unix)]
2480+
cmd.process_group(0);
2481+
configure_no_window(cmd);
2482+
}
2483+
2484+
/// Read at most a version line from `child` and require a clean exit within
2485+
/// `limit`. On timeout the whole process group is killed.
2486+
async fn claude_version_within(
2487+
mut child: tokio::process::Child,
2488+
limit: std::time::Duration,
2489+
) -> Option<(u64, u64, u64)> {
2490+
use tokio::io::AsyncReadExt;
2491+
const MAX_VERSION_BYTES: u64 = 256;
2492+
let pid = child.id();
2493+
let probe = async {
2494+
let mut stdout = Vec::new();
2495+
let pipe = child.stdout.take()?;
2496+
pipe.take(MAX_VERSION_BYTES)
2497+
.read_to_end(&mut stdout)
2498+
.await
2499+
.ok()?;
2500+
child.wait().await.ok()?.success().then_some(stdout)
2501+
};
2502+
match tokio::time::timeout(limit, probe).await {
2503+
Ok(stdout) => parse_claude_version(&String::from_utf8_lossy(&stdout?)),
2504+
Err(_) => {
2505+
if !pid.is_some_and(kill_process_group) {
2506+
let _ = child.start_kill();
2507+
}
2508+
None
2509+
}
2510+
}
2511+
}
2512+
24032513
/// Suppress the console window that Windows otherwise allocates for every
24042514
/// console-subsystem child process spawned from a GUI (non-console) parent.
24052515
/// No-op on non-Windows platforms.
@@ -3694,6 +3804,137 @@ mod tests {
36943804
);
36953805
}
36963806

3807+
#[test]
3808+
fn claude_version_gate_admits_only_cli_with_thinking_display() {
3809+
let accepts = |out: &str| {
3810+
parse_claude_version(out).is_some_and(|v| v >= CLAUDE_THINKING_DISPLAY_MIN_VERSION)
3811+
};
3812+
assert!(!accepts("2.1.92 (Claude Code)"), "below the minimum");
3813+
assert!(!accepts("1.0.100 (Claude Code)"), "older major");
3814+
assert!(accepts("2.1.94 (Claude Code)"), "exactly the minimum");
3815+
assert!(accepts("2.1.284 (Claude Code)"), "newer");
3816+
assert!(accepts("3.0.0"), "newer major");
3817+
assert!(!accepts(""), "empty output");
3818+
assert!(!accepts("error: unknown"), "unparseable output");
3819+
assert!(!accepts("2.1.284.garbage"), "trailing junk");
3820+
assert!(!accepts("2.1.+284"), "sign in a component");
3821+
}
3822+
3823+
#[tokio::test]
3824+
async fn claude_thinking_display_check_fails_closed_without_readable_cli() {
3825+
let mut cmd = tokio::process::Command::new("true");
3826+
cmd.env("CLAUDE_CODE_EXECUTABLE", "/nonexistent/claude");
3827+
assert!(!claude_cli_accepts_thinking_display(&cmd).await);
3828+
cmd.env("CLAUDE_CODE_EXECUTABLE", "");
3829+
assert!(!claude_cli_accepts_thinking_display(&cmd).await);
3830+
}
3831+
3832+
#[cfg(unix)]
3833+
#[tokio::test]
3834+
async fn claude_version_timeout_kills_launcher_children() {
3835+
let dir = std::env::temp_dir().join(format!("buzz-acp-hang-{}", uuid::Uuid::new_v4()));
3836+
std::fs::create_dir_all(&dir).expect("create dir");
3837+
let pidfile = dir.join("child.pid");
3838+
// A launcher that starts a child holding stdout open, then hangs.
3839+
let mut cmd = tokio::process::Command::new("sh");
3840+
cmd.arg("-c")
3841+
.arg(format!("sleep 300 & echo $! > {}; wait", pidfile.display()));
3842+
configure_version_probe(&mut cmd);
3843+
let child = cmd.spawn().expect("spawn launcher");
3844+
let version = claude_version_within(child, std::time::Duration::from_millis(500)).await;
3845+
assert_eq!(version, None);
3846+
let grandchild = std::fs::read_to_string(&pidfile).expect("pidfile");
3847+
let grandchild = nix::unistd::Pid::from_raw(grandchild.trim().parse().expect("pid"));
3848+
let mut alive = true;
3849+
for _ in 0..50 {
3850+
alive = nix::sys::signal::kill(grandchild, None).is_ok();
3851+
if !alive {
3852+
break;
3853+
}
3854+
tokio::time::sleep(std::time::Duration::from_millis(20)).await;
3855+
}
3856+
std::fs::remove_dir_all(&dir).expect("remove dir");
3857+
assert!(!alive, "the launcher's child must not outlive the timeout");
3858+
}
3859+
3860+
/// Spawn a fake `claude-agent-acp` whose `CLAUDE_CODE_EXECUTABLE` is a
3861+
/// fake CLI running `cli_body`, then return the `_meta` its `session/new`
3862+
/// actually received.
3863+
#[cfg(unix)]
3864+
async fn claude_session_meta_with_cli(cli_body: &str) -> serde_json::Value {
3865+
use std::os::unix::fs::PermissionsExt;
3866+
3867+
let dir =
3868+
std::env::temp_dir().join(format!("buzz-acp-claude-cli-{}", uuid::Uuid::new_v4()));
3869+
std::fs::create_dir_all(&dir).expect("create fake dir");
3870+
let write = |name: &str, body: &str| {
3871+
let path = dir.join(name);
3872+
std::fs::write(&path, format!("#!/bin/sh\n{body}\n")).expect("write fake");
3873+
std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o755))
3874+
.expect("chmod fake");
3875+
path
3876+
};
3877+
let cli = write("claude", cli_body);
3878+
let adapter = write(
3879+
"claude-agent-acp",
3880+
r#"read -r _init
3881+
echo '{"jsonrpc":"2.0","id":0,"result":{"protocolVersion":1,"agentCapabilities":{}}}'
3882+
read -r REQ
3883+
echo '{"jsonrpc":"2.0","id":1,"result":{"sessionId":"ses_test","_receivedRequest":'"$REQ"'}}'
3884+
sleep 1"#,
3885+
);
3886+
let mut client = AcpClient::spawn_with_env(
3887+
adapter.to_str().expect("utf8 path"),
3888+
&[],
3889+
&[],
3890+
false,
3891+
&[(
3892+
"CLAUDE_CODE_EXECUTABLE".into(),
3893+
cli.to_str().expect("utf8 path").into(),
3894+
)],
3895+
)
3896+
.await
3897+
.expect("spawn fake claude adapter");
3898+
client.initialize().await.expect("initialize");
3899+
let resp = client
3900+
.session_new_full(
3901+
"/tmp",
3902+
vec![],
3903+
Some(SystemPromptTransport::ClaudeMeta("be brief")),
3904+
Some("Fizz"),
3905+
)
3906+
.await
3907+
.expect("session_new_full");
3908+
client.shutdown().await;
3909+
std::fs::remove_dir_all(&dir).expect("remove fake dir");
3910+
resp.raw["_receivedRequest"]["params"]["_meta"].clone()
3911+
}
3912+
3913+
#[cfg(unix)]
3914+
#[tokio::test]
3915+
async fn claude_spawn_requests_thinking_summaries_only_from_supporting_cli() {
3916+
let meta = claude_session_meta_with_cli("echo '2.1.284 (Claude Code)'").await;
3917+
assert_eq!(
3918+
meta["claudeCode"]["options"]["extraArgs"],
3919+
serde_json::json!({ "thinking-display": "summarized" })
3920+
);
3921+
assert_eq!(
3922+
meta["systemPrompt"],
3923+
serde_json::json!({ "append": "be brief" })
3924+
);
3925+
assert_eq!(meta["sessionTitle"], "Fizz");
3926+
3927+
for (case, cli) in [
3928+
("old CLI", "echo '2.1.93 (Claude Code)'"),
3929+
("failing CLI", "echo '2.1.284 (Claude Code)'; exit 1"),
3930+
("unclean version", "echo '2.1.284.garbage'"),
3931+
] {
3932+
let meta = claude_session_meta_with_cli(cli).await;
3933+
assert!(meta.get("claudeCode").is_none(), "{case}: {meta}");
3934+
assert_eq!(meta["sessionTitle"], "Fizz", "{case}");
3935+
}
3936+
}
3937+
36973938
// ── claude-agent-acp _meta.systemPrompt transport ─────────────────────
36983939

36993940
include!("acp/system_prompt_tests.rs");

‎crates/buzz-acp/src/acp/launch/tests.rs‎

Lines changed: 23 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -46,13 +46,19 @@ for line in sys.stdin:
4646
result = {'protocolVersion': 1, 'argv': sys.argv[1:],
4747
'hermes': os.environ.get('HERMES_ACP_SKIP_CONFIGURED_MCP'),
4848
'codex': os.environ.get('CODEX_CONFIG'),
49-
'prefix': os.environ.get('BUZZ_ACP_LAUNCH_PREFIX')}
49+
'prefix': os.environ.get('BUZZ_ACP_LAUNCH_PREFIX'),
50+
'sessionId': 'ses_test', 'meta': request.get('params', {}).get('_meta')}
5051
print(json.dumps({'jsonrpc': '2.0', 'id': request['id'], 'result': result}), flush=True)
5152
"#,
5253
)
5354
.unwrap();
5455
fs::set_permissions(path, fs::Permissions::from_mode(0o700)).unwrap();
5556
}
57+
// A CLI new enough for `--thinking-display`, so only the prefix can
58+
// keep summaries off.
59+
let claude = dir.join("claude");
60+
fs::write(&claude, "#!/bin/sh\necho '2.1.284 (Claude Code)'\n").unwrap();
61+
fs::set_permissions(&claude, fs::Permissions::from_mode(0o700)).unwrap();
5662
Self(dir)
5763
}
5864
fn prefix(&self) -> String {
@@ -75,6 +81,7 @@ for line in sys.stdin:
7581
.env(CHILD, mode)
7682
.env_remove("CODEX_CONFIG")
7783
.env_remove("HERMES_ACP_SKIP_CONFIGURED_MCP")
84+
.env("CLAUDE_CODE_EXECUTABLE", self.0.join("claude"))
7885
.current_dir(&self.0);
7986
if let Some(prefix) = prefix {
8087
cmd.env(PREFIX_ENV, prefix);
@@ -216,6 +223,21 @@ async fn spawn_child() {
216223
_ => None,
217224
};
218225
assert_eq!(client.standard_adapter, adapter);
226+
if name == "claude-agent-acp" {
227+
let meta = client
228+
.session_new_full("/tmp", vec![], None, None)
229+
.await
230+
.unwrap()
231+
.raw["meta"]
232+
.clone();
233+
let expected = match std::env::var_os(PREFIX_ENV) {
234+
Some(_) => Value::Null,
235+
None => json!({"claudeCode": {"options": {"extraArgs": {
236+
"thinking-display": "summarized"
237+
}}}}),
238+
};
239+
assert_eq!(meta, expected, "prefix leaves summaries off");
240+
}
219241
client.shutdown().await;
220242
}
221243
}

0 commit comments

Comments
 (0)