mirror of
https://github.com/block/buzz.git
synced 2026-11-26 03:01:38 +00:00
The "Restart required" badge reports that an agent's running config has
drifted from its spawn-time config, but never says what changed. This
ships the full feature: a typed Rust diff engine and a TS/UI layer that
renders it at every badge site.
## Rust core (spawn-snapshot diff engine)
Replaces the lossy `u64` `spawn_config_hash` with a typed
`SpawnConfigSnapshot`. The snapshot is stamped from the already-resolved
command/env/config values immediately before `spawn()`, closing the race
window where a mid-spawn config edit would suppress the badge.
`SpawnConfigSnapshot::canonical()` is the single JSON projection shared
by the badge and the diff. Drift is `to_value(stamped) !=
to_value(current)`; the diff is a generic leaf walk over those same two
values, so badge-on and diff-non-empty are structurally guaranteed.
Adding a snapshot field reaches the UI with no code change to the diff
engine — `mutation_table_covers_every_serialized_field` fails CI if a
new field arrives without a mutation row.
`eligible_restart_diff(persona_orphaned, Option<TrackedSpawnState>)`
returns the final vector — snapshot walk entries plus a synthetic
`adapter_availability` entry. It returns empty for an orphaned instance
(spawning one would fail) and for agents with no tracked spawn state
(never stamped, can never have drifted). `needs_restart =
!restart_diff.is_empty()` derives from that vector and nothing else.
Redaction policy (`policy_for(path)`) is shared by the wire diff and the
snapshot's manual `Debug` via `is_safe_to_reveal()` from
`managed_agents::env_vars` as the single authority for env-key masking:
| Policy | Paths | Rendering |
|---|---|---|
| `Text` | `system_prompt`, `team_instructions` | character counts only
|
| `MaskedBare` | `args`, `relay_url` | `••••`, no suffix |
| `MaskedSuffix` | non-allowlisted `env.*` | `••••` + last 4 chars when
longer than 8 |
| `Plain` | allowlisted `env.*` (`BUZZ_AGENT_THINKING_EFFORT`,
`BUZZ_AGENT_PROVIDER`, `BUZZ_AGENT_MODEL`, `DATABRICKS_HOST/MODEL`) and
everything else | verbatim |
Default-deny: every env key not in the explicit allowlist stays masked.
`is_safe_to_reveal()` is the single allowlist authority for both the
baked-env display and the diff.
`restart_diff` is omitted from the wire when empty
(`skip_serializing_if`).
## TypeScript / UI layer
New `restartDiff.ts` module defines `RestartDiffEntry`, `RestartChange`,
`JsonValue`; `tauri.ts` and `types.ts` re-export and add `restart_diff`
/ `restartDiff` fields (Rust omission → `restartDiff: []`).
**`RestartDiffBadge`** — hover tooltip capped at 6 entries + "and N
more", `asChild` span trigger (never inside a `<button>`), auto-restart
blurb below the diff list (on/off variant from `autoRestartEnabled`
prop; same `AUTO_RESTART_ON_BLURB` / `AUTO_RESTART_OFF_BLURB` constants
shared with the Runtime-tab banner). **`RestartDiffList`** renders the
full uncapped list for the Runtime-tab banner with `tooltip`/`inline`
presentation variants for correct foreground in both surfaces.
**`ManagedAgentRow` B4 fix** — badge moved to a sibling `div` of the row
expansion button; tooltip trigger has no `button` ancestor.
**`UnifiedAgentsSection`** — both badge sites render
`<RestartDiffBadge>` instead of a raw `<Badge>`, with
`autoRestartEnabled` threaded from `agent.autoRestartOnConfigChange`.
**Side-panel fix** — `RestartDiffBadge` rendered tab-independently in
the `ProfileSummaryView` hero area (was Runtime-tab only — root cause of
the ~50% inconsistency Will reported). Hero badge is `self-center` in
the flex column. `ProfileRuntimeTabContent` early-return checks
`needsRestart` so the banner is never dropped when all other content is
empty. Auto-restart blurb in the Runtime-tab banner uses the shared
constants.
## Wire shape
```jsonc
"restart_diff": [
{ "field": "model", "change": { "kind": "value", "before": "gpt-5", "after": "claude-4" } },
{ "field": "system_prompt", "change": { "kind": "text", "before_chars": 1234, "after_chars": 1410 } },
{ "field": "env.OPENAI_API_KEY", "change": { "kind": "masked", "before": "••••bc12", "after": "••••xyz9" } },
{ "field": "env.BUZZ_AGENT_THINKING_EFFORT", "change": { "kind": "value", "before": "medium", "after": "high" } }
]
```
`added`/`removed` occur only for dynamic-map keys; nullable struct
fields always serialize as `null`; arrays are atomic leaves (`args`,
never `args.0`).
## Tests
**Rust** — 1902 passing: snapshot mutation coverage, diff entry
serialization, allowlist-aware env masking
(`allowlisted_env_key_shows_plain_value`,
`allowlisted_env_key_is_case_insensitive`,
`non_allowlisted_env_key_stays_masked`),
`unstamped_agent_yields_no_badge_and_no_entries` (both orphan values),
`summary_without_drift_omits_restart_diff_from_the_wire`,
`unstamped_availability_is_not_drift`. Clippy clean, fmt clean.
**TypeScript** — `needs-restart-screenshots.spec.ts`: 11 E2E cases
registered in the smoke project — all three badge sites, tooltip +
keyboard focus, DOM no-button-ancestor assertion, 6+1 truncation,
uncapped Runtime list, unknown field humanisation, side-panel badge on
default Info tab, inactive/friendly-error Runtime opening path.
Consolidates [#3652](https://github.com/block/buzz/pull/3652)
Signed-off-by: Will Pfleger <pfleger.will@gmail.com>
Co-authored-by: npub1mn7jgtj4w2pd0g0zeuhxsa6jy6p0rewxz4kujt98my82ahfmp72sxjexk7 <dcfd242e557282d7a1e2cf2e6877522682f1e5c6156dc92ca7d90eaedd3b0f95@buzz.block.builderlab.xyz>
141 lines
6.6 KiB
Rust
141 lines
6.6 KiB
Rust
//! B5 (unified agent model): one-time backfill of standalone agents into
|
|
//! definition-linked records. Every keyed record with `persona_id: None`
|
|
//! gets a key-less definition manufactured from its own settings, retiring
|
|
//! the standalone-create pattern (Wes's Option 2: backfill, not grandfather).
|
|
|
|
use std::path::Path;
|
|
|
|
use crate::managed_agents::{
|
|
persona_events::{persona_content_hash, persona_event_content},
|
|
ManagedAgentRecord,
|
|
};
|
|
|
|
/// Manufacture definitions for standalone agents (B5 backfill).
|
|
///
|
|
/// For each keyed record with `persona_id: None`, append a key-less
|
|
/// definition record snapshotting the agent's own config and link the agent
|
|
/// to it. Safety rails (pinned in the B5 review gates):
|
|
/// - **Idempotent**: linked records are skipped, so a second run is a no-op.
|
|
/// - **`.bak` create-if-absent**: the pre-migration backup is taken once and
|
|
/// never clobbered — a partial first run must not replace the pristine
|
|
/// backup with a half-migrated snapshot on re-run.
|
|
/// - **Fail loudly per record**: a record that cannot be backfilled (slug
|
|
/// collision) is logged and skipped; the rest proceed.
|
|
/// - **No behavior change**: the definition snapshots the record's own
|
|
/// values (prompt present-even-if-empty via `to_definition_view`'s
|
|
/// `unwrap_or_default`, env COPIED so later instances inherit a working
|
|
/// config, quad copied to the definition defaults) and the record gains
|
|
/// `persona_source_version` = the new definition's content hash, so
|
|
/// neither the spawn-config snapshot nor the drift badge moves.
|
|
///
|
|
/// The manufactured definition's slug is the agent's pubkey: 64-hex passes
|
|
/// the NIP-AP slug grammar on both relay and desktop ends, and agent pubkeys
|
|
/// are unique, so the coordinate is collision-free by construction.
|
|
pub fn backfill_standalone_agents(app: &tauri::AppHandle) {
|
|
let Ok(base_dir) = crate::managed_agents::managed_agents_base_dir(app) else {
|
|
return;
|
|
};
|
|
match backfill_standalone_agents_in_dir(&base_dir) {
|
|
Ok(0) => {}
|
|
Ok(backfilled) => {
|
|
eprintln!(
|
|
"buzz-desktop: standalone-backfill: {backfilled} agents linked to manufactured definitions"
|
|
);
|
|
}
|
|
Err(e) => eprintln!("buzz-desktop: standalone-backfill: {e}"),
|
|
}
|
|
}
|
|
|
|
/// Core backfill logic, decoupled from the Tauri `AppHandle` for testing.
|
|
/// Returns the number of records backfilled (0 = nothing to do).
|
|
fn backfill_standalone_agents_in_dir(base_dir: &Path) -> Result<usize, String> {
|
|
let agents_path = base_dir.join("managed-agents.json");
|
|
if !agents_path.exists() {
|
|
return Ok(0);
|
|
}
|
|
let content = std::fs::read_to_string(&agents_path)
|
|
.map_err(|e| format!("failed to read managed-agents.json: {e}"))?;
|
|
let mut all: Vec<ManagedAgentRecord> = serde_json::from_str(&content)
|
|
.map_err(|e| format!("failed to parse managed-agents.json: {e}"))?;
|
|
|
|
let needs_backfill =
|
|
|record: &ManagedAgentRecord| !record.pubkey.is_empty() && record.persona_id.is_none();
|
|
if !all.iter().any(needs_backfill) {
|
|
return Ok(0);
|
|
}
|
|
|
|
// Pre-migration backup, taken ONCE: a re-run after a partial failure must
|
|
// not overwrite the pristine backup with a half-migrated snapshot. Owner-only
|
|
// from the initial open, and sited next to the resolved store — see
|
|
// `create_restricted_backup_once` and `resolved_backup_path`.
|
|
let bak_path =
|
|
crate::util::resolved_backup_path(&agents_path, "managed-agents.json.pre-backfill.bak");
|
|
crate::util::create_restricted_backup_once(&bak_path, content.as_bytes())
|
|
.map_err(|e| format!("failed to write pre-backfill backup: {e}"))?;
|
|
|
|
let existing_slugs: std::collections::HashSet<String> =
|
|
all.iter().filter_map(|r| r.slug.clone()).collect();
|
|
|
|
let mut manufactured: Vec<ManagedAgentRecord> = Vec::new();
|
|
let mut backfilled = 0usize;
|
|
for record in all.iter_mut().filter(|r| needs_backfill(r)) {
|
|
// Pubkeys are unique so this cannot fire against another manufactured
|
|
// definition — only against a pre-existing definition improbably
|
|
// slugged as this agent's pubkey. Fail loudly, skip, continue: the
|
|
// agent keeps working persona-less (`persona_id: None`), and the
|
|
// backfill retries it on every boot. Recovery path: delete or re-slug
|
|
// the colliding definition, then relaunch.
|
|
if existing_slugs.contains(&record.pubkey) {
|
|
eprintln!(
|
|
"buzz-desktop: standalone-backfill: slug collision for agent {} — skipped; \
|
|
delete or re-slug the colliding definition to let the next launch backfill it",
|
|
record.pubkey
|
|
);
|
|
continue;
|
|
}
|
|
|
|
// Snapshot the record's own config as a definition. Via the same
|
|
// fold path every definition takes: a temporary persona view of the
|
|
// record (prompt unwrap_or_default = present-even-if-empty — the
|
|
// heal source old devices hard-require) folded into a key-less
|
|
// definition record. Quad + env come along so future instances
|
|
// minted from this definition inherit a working config.
|
|
let mut view_source = record.clone();
|
|
view_source.slug = Some(record.pubkey.clone());
|
|
// Standalone agents have no definition-level quad — the INSTANCE
|
|
// fields are the author's intent; copy them up.
|
|
view_source.definition_respond_to = Some(record.respond_to.as_str().to_string());
|
|
view_source.definition_respond_to_allowlist = record.respond_to_allowlist.clone();
|
|
view_source.definition_parallelism = Some(record.parallelism);
|
|
let Some(persona_view) = view_source.to_definition_view() else {
|
|
eprintln!(
|
|
"buzz-desktop: standalone-backfill: agent {} produced no persona view — skipped",
|
|
record.pubkey
|
|
);
|
|
continue;
|
|
};
|
|
|
|
// Link the record BEFORE computing the version so the hash covers the
|
|
// definition exactly as manufactured.
|
|
let source_version = persona_content_hash(&persona_event_content(&persona_view));
|
|
let definition = persona_view.into_agent_record();
|
|
record.persona_id = Some(record.pubkey.clone());
|
|
record.persona_source_version = Some(source_version);
|
|
manufactured.push(definition);
|
|
backfilled += 1;
|
|
}
|
|
|
|
if backfilled == 0 {
|
|
return Ok(0);
|
|
}
|
|
all.extend(manufactured);
|
|
let payload = serde_json::to_vec_pretty(&all)
|
|
.map_err(|e| format!("failed to serialize unified store: {e}"))?;
|
|
crate::managed_agents::atomic_write_json_restricted(&agents_path, &payload)?;
|
|
Ok(backfilled)
|
|
}
|
|
|
|
#[cfg(test)]
|
|
#[path = "backfill_tests.rs"]
|
|
mod tests;
|