fix(desktop): address Wes review comments on #1307

FIX 1 — extract agent_env.rs to fix file-size guard:
runtime.rs was 2172 lines (gate limit 2150). Extracted
build_buzz_agent_provider_defaults + parse_agent_env_lines into a new
focused module managed_agents/agent_env.rs. Moved the 10 associated
tests (parse_agent_env_lines_*, buzz_agent_provider_defaults_*,
base64_round_trip, baked_defaults_ordering) into agent_env.rs's own
#[cfg(test)] mod. Re-exported build_buzz_agent_provider_defaults via
mod.rs pub(crate) use so agent_models.rs call site is unchanged.
runtime.rs is now 2120 lines (gate sees 2121); check-file-sizes.mjs
passes.

FIX 2 — rewrite stale E2E spec:
persona-env-vars.spec.ts 'persona model options follow the selected LLM
provider' asserted the deleted static roster (GPT-5.5, Claude Sonnet
4.6) and clicked 'Databricks (default)' (now just 'Default'). Rewrote
to assert provider-agnostic behavior: Default model present without
discovery, provider switch updates API-key field label/value, Default
provider resets model to 'Default model'. No hardcoded model IDs remain.
E2E harness requires a built app (webServer) — not runnable locally
without dist; CI validates.

FIX 3 — drop dead providers filter branch:
With the static roster gone, PersonaModelOption.providers was always
undefined. Removed the providers field from the type and simplified
getPersonaModelOptions to drop the dead option.providers?.includes()
branch. typecheck clean.

Co-authored-by: Will Pfleger <pfleger.will@gmail.com>
Signed-off-by: Will Pfleger <pfleger.will@gmail.com>
This commit is contained in:
npub1mn7jgtj4w2pd0g0zeuhxsa6jy6p0rewxz4kujt98my82ahfmp72sxjexk7
2026-06-29 19:49:16 -04:00
parent 8a4d12b437
commit fd9270e8fd
6 changed files with 207 additions and 235 deletions

View File

@@ -0,0 +1,191 @@
//! Build-time agent env passthrough.
//!
//! Internal builds (buzz-releases) bake arbitrary `KEY=VALUE` pairs into the
//! binary via `BUZZ_BUILD_AGENT_ENV` (base64-encoded, newline-delimited).
//! OSS builds leave the compile-time var unset — nothing is injected.
use base64::Engine as _;
/// Inject baked-in provider/model defaults and generic env pairs onto `cmd`.
///
/// Call this BEFORE writing record/persona metadata env vars so that the
/// record's explicit choices (written after) override the baked defaults.
/// User-supplied `record.env_vars` (written last) always win.
pub(crate) fn build_buzz_agent_provider_defaults(cmd: &mut std::process::Command) {
if let Some(provider) = option_env!("BUZZ_DESKTOP_BUILD_BUZZ_AGENT_PROVIDER") {
if !provider.is_empty() {
cmd.env("BUZZ_AGENT_PROVIDER", provider);
}
}
if let Some(model) = option_env!("BUZZ_DESKTOP_BUILD_BUZZ_AGENT_MODEL") {
if !model.is_empty() {
cmd.env("BUZZ_AGENT_MODEL", model);
}
}
if let Some(raw) = option_env!("BUZZ_DESKTOP_BUILD_AGENT_ENV") {
// The value was base64-encoded at build time so the single-line Cargo
// output carries all KEY=VALUE pairs without truncation.
if let Ok(decoded) = base64::engine::general_purpose::STANDARD.decode(raw.as_bytes()) {
if let Ok(text) = std::str::from_utf8(&decoded) {
for (key, value) in parse_agent_env_lines(text) {
cmd.env(key, value);
}
}
}
}
}
/// Parse newline-delimited `KEY=VALUE` lines from a baked env blob.
/// Blank lines are skipped. Each non-blank line must contain `=`; the key
/// is everything before the first `=`, the value is everything after (values
/// may themselves contain `=`). Lines with an empty key are skipped.
pub(crate) fn parse_agent_env_lines(raw: &str) -> Vec<(&str, &str)> {
raw.lines()
.filter_map(|line| {
let line = line.trim();
if line.is_empty() {
return None;
}
let eq = line.find('=')?;
let key = &line[..eq];
if key.is_empty() {
return None;
}
Some((key, &line[eq + 1..]))
})
.collect()
}
#[cfg(test)]
mod tests {
use super::{build_buzz_agent_provider_defaults, parse_agent_env_lines};
#[test]
fn buzz_agent_provider_defaults_empty_in_oss_build() {
// OSS (and normal test) builds set neither BUZZ_BUILD_BUZZ_AGENT_*,
// so nothing is baked in and no BUZZ_AGENT_* is injected on spawn.
let mut cmd = std::process::Command::new("env");
cmd.env_clear();
build_buzz_agent_provider_defaults(&mut cmd);
let output = cmd.output().expect("env should run");
let stdout = String::from_utf8_lossy(&output.stdout);
assert!(
!stdout.contains("BUZZ_AGENT_PROVIDER="),
"BUZZ_AGENT_PROVIDER should not be injected in OSS builds"
);
assert!(
!stdout.contains("BUZZ_AGENT_MODEL="),
"BUZZ_AGENT_MODEL should not be injected in OSS builds"
);
assert!(
!stdout.contains("DATABRICKS_HOST="),
"DATABRICKS_HOST should not be injected in OSS builds"
);
}
#[test]
fn parse_agent_env_lines_splits_on_first_equals() {
// Value may itself contain `=` — only the first `=` is the separator.
let pairs = parse_agent_env_lines("DATABRICKS_HOST=https://host.example.com/path?a=1");
assert_eq!(
pairs,
vec![("DATABRICKS_HOST", "https://host.example.com/path?a=1")]
);
}
#[test]
fn parse_agent_env_lines_multiple_pairs() {
let raw = "KEY_A=value_a\nKEY_B=value_b";
let pairs = parse_agent_env_lines(raw);
assert_eq!(pairs, vec![("KEY_A", "value_a"), ("KEY_B", "value_b")]);
}
#[test]
fn parse_agent_env_lines_skips_blank_lines() {
let raw = "KEY_A=val_a\n\n \nKEY_B=val_b";
let pairs = parse_agent_env_lines(raw);
assert_eq!(pairs, vec![("KEY_A", "val_a"), ("KEY_B", "val_b")]);
}
#[test]
fn parse_agent_env_lines_skips_line_without_equals() {
// A malformed line (no `=`) is silently skipped — build.rs validates at
// compile time; runtime parsing is defensive.
let raw = "NO_EQUALS_HERE\nGOOD=value";
let pairs = parse_agent_env_lines(raw);
assert_eq!(pairs, vec![("GOOD", "value")]);
}
#[test]
fn parse_agent_env_lines_skips_empty_key() {
// `=value` has an empty key — skip it.
let raw = "=orphan_value\nGOOD=value";
let pairs = parse_agent_env_lines(raw);
assert_eq!(pairs, vec![("GOOD", "value")]);
}
#[test]
fn parse_agent_env_lines_empty_value_is_allowed() {
// `KEY=` is valid — empty value is intentional (clears an env var).
let pairs = parse_agent_env_lines("EMPTY=");
assert_eq!(pairs, vec![("EMPTY", "")]);
}
#[test]
fn parse_agent_env_lines_empty_input_returns_empty() {
assert!(parse_agent_env_lines("").is_empty());
assert!(parse_agent_env_lines(" \n \n").is_empty());
}
// ── base64 round-trip regression ─────────────────────────────────────
//
// Cargo build-script output is line-oriented: a raw multiline value emitted
// via `cargo:rustc-env=KEY=...` would be truncated to the first line.
// build.rs base64-encodes the validated value; runtime.rs decodes it.
// This test verifies that a 2-pair value with a URL containing `=` survives
// the encode→decode→parse round-trip and both pairs land correctly.
#[test]
fn parse_agent_env_lines_base64_round_trip_preserves_all_pairs() {
use base64::Engine as _;
let raw =
"DATABRICKS_HOST=https://host.example.com/path?a=1&b=2\nDATABRICKS_MODEL=some-model";
let encoded = base64::engine::general_purpose::STANDARD.encode(raw.as_bytes());
let decoded_bytes = base64::engine::general_purpose::STANDARD
.decode(encoded.as_bytes())
.expect("decode should succeed");
let decoded = std::str::from_utf8(&decoded_bytes).expect("utf8 should be valid");
let pairs = parse_agent_env_lines(decoded);
assert_eq!(pairs.len(), 2, "both pairs must survive the round-trip");
assert_eq!(
pairs[0],
("DATABRICKS_HOST", "https://host.example.com/path?a=1&b=2")
);
assert_eq!(pairs[1], ("DATABRICKS_MODEL", "some-model"));
}
// ── baked defaults ordering regression ───────────────────────────────
//
// `build_buzz_agent_provider_defaults` must run BEFORE
// `runtime_metadata_env_vars` writes the record's provider/model so that
// record values win (last-write-wins). This test simulates the ordering by
// writing the baked default first, then overwriting with the record value.
#[test]
fn baked_defaults_do_not_override_record_provider_written_after() {
let mut cmd = std::process::Command::new("env");
cmd.env_clear();
// Simulate what an internal build's baked defaults would inject.
cmd.env("BUZZ_AGENT_PROVIDER", "databricks");
// Simulate what runtime_metadata_env_vars writes from the record (comes after).
cmd.env("BUZZ_AGENT_PROVIDER", "anthropic");
let output = cmd.output().expect("env should run");
let stdout = String::from_utf8_lossy(&output.stdout);
assert!(
stdout.contains("BUZZ_AGENT_PROVIDER=anthropic"),
"record provider must win over baked default (last-write-wins)"
);
assert!(
!stdout.contains("BUZZ_AGENT_PROVIDER=databricks"),
"baked default must not survive when record provider is written after"
);
}
}

View File

@@ -1,4 +1,6 @@
mod agent_env;
pub(crate) mod agent_events;
pub(crate) use agent_env::build_buzz_agent_provider_defaults;
mod backend;
pub(crate) mod config_bridge;
mod discovery;

View File

@@ -1,8 +1,9 @@
use std::collections::HashMap;
use base64::Engine as _;
use tauri::AppHandle;
use super::agent_env::build_buzz_agent_provider_defaults;
use crate::{
managed_agents::{
append_log_marker, known_acp_runtime, login_shell_path, managed_agent_log_path,
@@ -1951,58 +1952,6 @@ fn child_rust_log_filter() -> String {
}
}
/// Provider/model baked in at compile time for internal builds. Empty
/// in OSS builds, where the `BUZZ_BUILD_BUZZ_AGENT_*` env is unset.
///
/// Also injects any arbitrary `KEY=VALUE` pairs baked via `BUZZ_BUILD_AGENT_ENV`
/// (newline-delimited). This is how provider-specific vars like `DATABRICKS_HOST`
/// reach the agent in internal builds without naming them in OSS code.
/// User-supplied env vars (written after this call) always win.
pub(crate) fn build_buzz_agent_provider_defaults(cmd: &mut std::process::Command) {
if let Some(provider) = option_env!("BUZZ_DESKTOP_BUILD_BUZZ_AGENT_PROVIDER") {
if !provider.is_empty() {
cmd.env("BUZZ_AGENT_PROVIDER", provider);
}
}
if let Some(model) = option_env!("BUZZ_DESKTOP_BUILD_BUZZ_AGENT_MODEL") {
if !model.is_empty() {
cmd.env("BUZZ_AGENT_MODEL", model);
}
}
if let Some(raw) = option_env!("BUZZ_DESKTOP_BUILD_AGENT_ENV") {
// The value was base64-encoded at build time so the single-line Cargo
// output carries all KEY=VALUE pairs without truncation.
if let Ok(decoded) = base64::engine::general_purpose::STANDARD.decode(raw.as_bytes()) {
if let Ok(text) = std::str::from_utf8(&decoded) {
for (key, value) in parse_agent_env_lines(text) {
cmd.env(key, value);
}
}
}
}
}
/// Parse newline-delimited `KEY=VALUE` lines from a baked env blob.
/// Blank lines are skipped. Each non-blank line must contain `=`; the key
/// is everything before the first `=`, the value is everything after (values
/// may themselves contain `=`). Lines with an empty key are skipped.
pub(crate) fn parse_agent_env_lines(raw: &str) -> Vec<(&str, &str)> {
raw.lines()
.filter_map(|line| {
let line = line.trim();
if line.is_empty() {
return None;
}
let eq = line.find('=')?;
let key = &line[..eq];
if key.is_empty() {
return None;
}
Some((key, &line[eq + 1..]))
})
.collect()
}
pub fn start_managed_agent_process(
app: &AppHandle,
record: &mut ManagedAgentRecord,

View File

@@ -86,143 +86,6 @@ fn buzz_agent_has_mcp_hooks() {
assert_eq!(p.mcp_command, Some("buzz-dev-mcp"));
}
#[test]
fn buzz_agent_provider_defaults_empty_in_oss_build() {
// OSS (and normal test) builds set neither BUZZ_BUILD_BUZZ_AGENT_*,
// so nothing is baked in and no BUZZ_AGENT_* is injected on spawn.
let mut cmd = std::process::Command::new("env");
cmd.env_clear();
super::build_buzz_agent_provider_defaults(&mut cmd);
// Verify the function injects nothing when the compile-time vars are absent.
let output = cmd.output().expect("env should run");
let stdout = String::from_utf8_lossy(&output.stdout);
assert!(
!stdout.contains("BUZZ_AGENT_PROVIDER="),
"BUZZ_AGENT_PROVIDER should not be injected in OSS builds"
);
assert!(
!stdout.contains("BUZZ_AGENT_MODEL="),
"BUZZ_AGENT_MODEL should not be injected in OSS builds"
);
// BUZZ_DESKTOP_BUILD_AGENT_ENV is also absent in OSS builds — no
// arbitrary keys should appear from the generic passthrough either.
assert!(
!stdout.contains("DATABRICKS_HOST="),
"DATABRICKS_HOST should not be injected in OSS builds"
);
}
// ── parse_agent_env_lines tests ──────────────────────────────────────────
use super::parse_agent_env_lines;
#[test]
fn parse_agent_env_lines_splits_on_first_equals() {
// Value may itself contain `=` — only the first `=` is the separator.
let pairs = parse_agent_env_lines("DATABRICKS_HOST=https://host.example.com/path?a=1");
assert_eq!(
pairs,
vec![("DATABRICKS_HOST", "https://host.example.com/path?a=1")]
);
}
#[test]
fn parse_agent_env_lines_multiple_pairs() {
let raw = "KEY_A=value_a\nKEY_B=value_b";
let pairs = parse_agent_env_lines(raw);
assert_eq!(pairs, vec![("KEY_A", "value_a"), ("KEY_B", "value_b")]);
}
#[test]
fn parse_agent_env_lines_skips_blank_lines() {
let raw = "KEY_A=val_a\n\n \nKEY_B=val_b";
let pairs = parse_agent_env_lines(raw);
assert_eq!(pairs, vec![("KEY_A", "val_a"), ("KEY_B", "val_b")]);
}
#[test]
fn parse_agent_env_lines_skips_line_without_equals() {
// A malformed line (no `=`) is silently skipped — build.rs validates at
// compile time; runtime parsing is defensive.
let raw = "NO_EQUALS_HERE\nGOOD=value";
let pairs = parse_agent_env_lines(raw);
assert_eq!(pairs, vec![("GOOD", "value")]);
}
#[test]
fn parse_agent_env_lines_skips_empty_key() {
// `=value` has an empty key — skip it.
let raw = "=orphan_value\nGOOD=value";
let pairs = parse_agent_env_lines(raw);
assert_eq!(pairs, vec![("GOOD", "value")]);
}
#[test]
fn parse_agent_env_lines_empty_value_is_allowed() {
// `KEY=` is valid — empty value is intentional (clears an env var).
let pairs = parse_agent_env_lines("EMPTY=");
assert_eq!(pairs, vec![("EMPTY", "")]);
}
#[test]
fn parse_agent_env_lines_empty_input_returns_empty() {
assert!(parse_agent_env_lines("").is_empty());
assert!(parse_agent_env_lines(" \n \n").is_empty());
}
// ── base64 round-trip regression ─────────────────────────────────────────
//
// Cargo build-script output is line-oriented: a raw multiline value emitted
// via `cargo:rustc-env=KEY=...` would be truncated to the first line.
// build.rs base64-encodes the validated value; runtime.rs decodes it.
// This test verifies that a 2-pair value with a URL containing `=` survives
// the encode→decode→parse round-trip and both pairs land correctly.
#[test]
fn parse_agent_env_lines_base64_round_trip_preserves_all_pairs() {
use base64::Engine as _;
let raw = "DATABRICKS_HOST=https://host.example.com/path?a=1&b=2\nDATABRICKS_MODEL=some-model";
let encoded = base64::engine::general_purpose::STANDARD.encode(raw.as_bytes());
let decoded_bytes = base64::engine::general_purpose::STANDARD
.decode(encoded.as_bytes())
.expect("decode should succeed");
let decoded = std::str::from_utf8(&decoded_bytes).expect("utf8 should be valid");
let pairs = parse_agent_env_lines(decoded);
assert_eq!(pairs.len(), 2, "both pairs must survive the round-trip");
assert_eq!(
pairs[0],
("DATABRICKS_HOST", "https://host.example.com/path?a=1&b=2")
);
assert_eq!(pairs[1], ("DATABRICKS_MODEL", "some-model"));
}
// ── baked defaults ordering regression ───────────────────────────────────
//
// `build_buzz_agent_provider_defaults` must run BEFORE `runtime_metadata_env_vars`
// writes the record's provider/model so that record values win (last-write-wins).
// This test verifies the ordering by simulating what spawn does: call
// `build_buzz_agent_provider_defaults` first, then overwrite with the record value.
// In an OSS build the baked call is a no-op, so we simulate the baked write
// manually and confirm the subsequent record write wins.
#[test]
fn baked_defaults_do_not_override_record_provider_written_after() {
let mut cmd = std::process::Command::new("env");
cmd.env_clear();
// Simulate what an internal build's baked defaults would inject.
cmd.env("BUZZ_AGENT_PROVIDER", "databricks");
// Simulate what runtime_metadata_env_vars writes from the record (comes after).
cmd.env("BUZZ_AGENT_PROVIDER", "anthropic");
let output = cmd.output().expect("env should run");
let stdout = String::from_utf8_lossy(&output.stdout);
assert!(
stdout.contains("BUZZ_AGENT_PROVIDER=anthropic"),
"record provider must win over baked default (last-write-wins)"
);
assert!(
!stdout.contains("BUZZ_AGENT_PROVIDER=databricks"),
"baked default must not survive when record provider is written after"
);
}
#[test]
fn buzz_agent_resolved_via_path() {
assert!(known_acp_runtime("/usr/local/bin/buzz-agent").is_some_and(|p| p.mcp_hooks));

View File

@@ -26,7 +26,6 @@ type PersonaLlmProviderId = (typeof KNOWN_LLM_PROVIDER_IDS)[number];
export type PersonaModelOption = {
id: string;
label: string;
providers?: readonly PersonaLlmProviderId[];
};
export type PersonaDropdownOption = {
@@ -112,9 +111,7 @@ export function getPersonaModelOptions(
return options.filter(
(option) =>
(option.id.length === 0 &&
!providerRequiresExplicitModel(trimmedProvider)) ||
option.providers?.includes(trimmedProvider),
option.id.length === 0 && !providerRequiresExplicitModel(trimmedProvider),
);
}

View File

@@ -296,8 +296,10 @@ test("persona model options follow the selected LLM provider", async ({
await expect(provider).toContainText("Buzz Agent (default)");
await expect(llmProvider).toBeVisible();
await expect(model).toBeVisible();
// Without live discovery, the only static option is "Default model".
await expect(model).toContainText("Default model");
// Switch to OpenAI — the API-key field appears and is labelled correctly.
await llmProvider.click();
await page
.getByRole("menuitemradio", { name: "OpenAI", exact: true })
@@ -307,26 +309,19 @@ test("persona model options follow the selected LLM provider", async ({
await expect(providerApiKey).toBeVisible();
await expect(page.getByTestId("env-vars-editor")).toHaveCount(0);
await expect(model).toBeVisible();
await providerApiKey.fill("sk-openai-test");
// Model menu contains only the generic "Default model" — no static roster.
const openAiModelMenu = await openModelMenu(page, model);
await expect(
openAiModelMenu.getByRole("menuitemradio", {
name: "GPT-5.5",
name: "Default model",
exact: true,
}),
).toBeVisible();
await expect(
openAiModelMenu.getByRole("menuitemradio", { name: "GPT-5", exact: true }),
).toHaveCount(0);
await expect(
openAiModelMenu.getByRole("menuitemradio", { name: /Claude/ }),
).toHaveCount(0);
await openAiModelMenu
.getByRole("menuitemradio", { name: "GPT-5.5", exact: true })
.getByRole("menuitemradio", { name: "Custom model...", exact: true })
.click();
await expect(model).toContainText("GPT-5.5");
// Switch to Anthropic — API-key field label changes and value clears.
await llmProvider.click();
await page
.getByRole("menuitemradio", { name: "Anthropic", exact: true })
@@ -335,44 +330,19 @@ test("persona model options follow the selected LLM provider", async ({
await expect(providerApiKey).toHaveValue("");
await expect(model).toBeVisible();
// Fill in the Anthropic key and verify the model field is still present.
await providerApiKey.fill("sk-ant-test");
await expect(model).toBeVisible();
const anthropicModelMenu = await openModelMenu(page, model);
await expect(
anthropicModelMenu.getByRole("menuitemradio", {
name: "Claude Sonnet 4.6",
}),
).toBeVisible();
await expect(
anthropicModelMenu.getByRole("menuitemradio", {
name: "GPT-5.5",
exact: true,
}),
).toHaveCount(0);
await anthropicModelMenu
.getByRole("menuitemradio", { name: "Claude Sonnet 4.6" })
.click();
await expect(model).toContainText("Claude Sonnet 4.6");
// Switch to Default (no explicit provider) — model resets to "Default model".
await llmProvider.click();
const llmProviderMenu = page.getByRole("menu").filter({
has: page.getByRole("menuitemradio", { name: "OpenAI", exact: true }),
});
await llmProviderMenu
.last()
.getByRole("menuitemradio", { name: "Databricks (default)", exact: true })
.getByRole("menuitemradio", { name: "Default", exact: true })
.click();
await expect(model).toBeVisible();
await expect(model).toContainText("Claude Sonnet 4.6");
const defaultModelMenu = await openModelMenu(page, model);
await expect(
defaultModelMenu.getByRole("menuitemradio", { name: "Claude Sonnet 4.6" }),
).toBeVisible();
await expect(
defaultModelMenu.getByRole("menuitemradio", {
name: "GPT-5.5",
exact: true,
}),
).toBeVisible();
await expect(model).toContainText("Default model");
});