Skip to content

Commit 50a3dd7

Browse files
wpfleger96npub1mn7jgtj4w2pd0g0zeuhxsa6jy6p0rewxz4kujt98my82ahfmp72sxjexk7
andauthored
fix(desktop): make agent definition authoritative for model/provider/prompt (#1968)
## Summary Introduces a single effective-config resolver that makes agent definitions authoritative for model, provider, system prompt, and relay-mesh routing on linked instances. Stale materialized record bytes are never consulted at spawn, deploy, readiness, hash, card summary, or mesh preflight. **Resolution semantics (field-specific):** - **model/provider (linked):** definition → global. `None` = inherit global default. Record value never consulted. - **model/provider (definition-less):** instance → global. - **system_prompt (linked):** strictly from definition; blank = no prompt. No global tier for prompt. - **system_prompt (definition-less):** from the instance. - **relay-mesh preflight (both):** driven by the same `resolve_effective_config` resolution spawn's mesh env consults. For a linked instance the record's own `provider`/`model`/`relay_mesh` bytes are never consulted; for a definition-less instance with no provider of its own, the legacy marker and env preset are the last fallback (see below). - **Orphaned (linked record, definition missing):** spawn, deploy, and mesh preflight blocked with actionable user-facing error. **Changes:** - New `effective_config` resolver module with `ConfigSource` metadata (`definition`, `global`, `instance_legacy`) - All consumers routed through the single resolver: local spawn, deploy, readiness, spawn hash, card summary, relay-mesh preflight (interactive start and restore-on-launch) - `apply_persona_snapshot` no longer preserves stale record model/provider when definition is blank - Backend `update_managed_agent` blocks model/provider/prompt writes for linked records - Frontend omits model/provider/systemPrompt submission for linked instances; system prompt override hidden - `model_source` field added to `ManagedAgentSummary` so card labels distinguish inherited (`Default model (X)`) from explicit - Spawn hash now digests resolved model/provider (not raw record fields) so global default changes trip the restart badge even for runtimes without `model_env_var` - Orphan spawn/deploy/mesh-preflight blocked with jargon-free error ("This agent's configuration is missing — it may still be syncing or was deleted on another device") - `EffectiveAgentConfig::relay_mesh_model_id()` and `resolve_effective_relay_mesh_model_id()` added; both mesh preflights (`start_local_agent_with_preflight`, `restore_managed_agents_on_launch`) call this instead of the deleted `relay_mesh_config`/`relay_mesh_model_id` record-byte sniffs - Legacy relay-mesh records keep their mesh routing. Two shipped generations predate `provider: "relay-mesh"` and are never rewritten on load: the typed `relay_mesh` marker (added when `ManagedAgentRecord` had no `provider` field), and before it the mesh preset written directly into `env_vars`. `resolve_definition_less` falls back to the marker, then to the env preset, so these records still resolve to mesh instead of silently misrouting to an unrelated provider while their stale env bytes reach the child. The fallback is skipped when the record carries an explicit `provider` — that states current intent, including a switch away from mesh — and `resolve_linked` has no legacy fallback at all - The env discriminator accepts both spellings of the two sentinels renamed in the Jun-11 window without a record migration: the provider env key (`BUZZ_AGENT_PROVIDER`, previously `SPROUT_AGENT_PROVIDER`) and the api-key value (`buzz-mesh-local`, previously `sprout-mesh-local`). Each is independent, since a record can straddle the window; the current provider-key spelling wins when both are present - Dead `persona_field_with_record_fallback` and wrapper `persona_snapshot_with_agent_config_fallback` deleted; callers use `persona_snapshot` directly - New resolver/deploy/hash/write-guard/mesh-preflight tests, including switch-away and global-inheritance regressions for both mesh preflight call sites, per-class legacy-mesh resolution (typed marker and env preset, in every rename-window spelling combination), and the paired assertions that a linked instance's legacy mesh bytes stay inert --------- Signed-off-by: Will Pfleger <[email protected]> Co-authored-by: npub1mn7jgtj4w2pd0g0zeuhxsa6jy6p0rewxz4kujt98my82ahfmp72sxjexk7 <dcfd242e557282d7a1e2cf2e6877522682f1e5c6156dc92ca7d90eaedd3b0f95@buzz.block.builderlab.xyz>
1 parent 7575f8d commit 50a3dd7

34 files changed

Lines changed: 2549 additions & 830 deletions

‎desktop/scripts/check-file-sizes.mjs‎

Lines changed: 32 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -80,7 +80,15 @@ const overrides = new Map([
8080
// ratcheting 1443 -> 1295. Queued to split further in the A2 fold.
8181
// global-agent-config: resolve_deploy_model_provider + visibility exports
8282
// add ~40 lines on top of the 1A.1 ratchet. Queued to split.
83-
["src-tauri/src/commands/agents.rs", 1340],
83+
// +22 (1340 -> 1360): agent-config-resolver — start_local_agent_with_preflight
84+
// uses resolve_effective_relay_mesh_model_id at both preflight call sites;
85+
// preview_prospective_persona_snapshot helper extracted; orphan guard threaded
86+
// through restore path. Load-bearing feature changes; queued to split.
87+
// +9 (1360 -> 1369): start_local_agent_pairs_with_preflight — added
88+
// personas/global load + resolve_effective_relay_mesh_model_id call to
89+
// replace stale record-byte preflight. Same resolver pattern as
90+
// start_local_agent_with_preflight. Load-bearing; queued to split.
91+
["src-tauri/src/commands/agents.rs", 1369],
8492
// agent-lifecycle-fixes: cascade-delete in delete_persona restructured into
8593
// 3-phase (stage/stop/commit) + commit_cascade_agents injectable helper for
8694
// retry-safety. Load-bearing reviewer-required change; queued to split.
@@ -168,7 +176,9 @@ const overrides = new Map([
168176
// Windows PATH-correctness fix: 3 #[cfg(windows)] test functions covering
169177
// .cmd shim rejection, .bat shim rejection, and .exe acceptance for
170178
// configure_runtime_cli (fix #2397). Test-only growth; queued to split.
171-
["src-tauri/src/managed_agents/runtime/tests.rs", 1041],
179+
// +7 (1041 -> 1048): rebase onto main — this PR's resolver tests land on top
180+
// of main's #2397 Windows shim tests. Test-only; queued to split.
181+
["src-tauri/src/managed_agents/runtime/tests.rs", 1055],
172182
// applyWorkspace reposDir parameter plus the validateReposDir binding,
173183
// threaded through Tauri invokes for configurable repos_dir, plus the
174184
// harness-persona-sync `harnessOverride` create-input bit — load-bearing
@@ -203,7 +213,8 @@ const overrides = new Map([
203213
// mapper. This is the existing API boundary; split remains queued.
204214
// team-instructions-first-class: createManagedAgent Tauri bridge threads the
205215
// new teamId input through to the backend (+1 line).
206-
["src/shared/api/tauri.ts", 1305],
216+
// +2 for model_source field in RawManagedAgent + fromRawManagedAgent mapping.
217+
["src/shared/api/tauri.ts", 1307],
207218
// doctor-npm-eacces-preflight: hint field added to InstallStepResult (+1 line).
208219
// codex-acp-package-swap: "adapter_outdated" variant added to AcpAvailabilityStatus (+1 line).
209220
// doctor-install-reliability: AuthStatus tagged union + nodeRequired/authStatus/
@@ -438,7 +449,15 @@ const overrides = new Map([
438449
// (if let Some(provider_update) = input.provider { record.provider = provider_update; }).
439450
// +8: harness_override thread-through in update_managed_agent so a deliberate
440451
// Custom pin routes to update_time_agent_command_override (comment + call).
441-
["src-tauri/src/commands/agent_models.rs", 1079],
452+
// +22 (1079 -> 1101): Finding 2 — model discovery now resolves through
453+
// resolve_effective_model_provider instead of raw record bytes
454+
// (saved_agent_model_discovery_config takes personas/global and the
455+
// get_agent_models call site loads global config), plus
456+
// apply_model_provider_prompt_update's linked-instance write-guard
457+
// extraction and its regression tests.
458+
// +4 (1101 -> 1105): rebase onto agents-everywhere — agents.rs function
459+
// signatures updated for ManagedAgentRuntimeKey-keyed runtimes map.
460+
["src-tauri/src/commands/agent_models.rs", 1113],
442461
// global-agent-config: get_agent_config_surface / write_agent_config_field /
443462
// put_agent_session_config commands + GlobalAgentConfig serde types. New file
444463
// in this PR; queued to split with the command module refactor.
@@ -454,7 +473,12 @@ const overrides = new Map([
454473
// relay from the harness-attached payload relayUrl (with effective-relay
455474
// fallback for older harnesses) instead of a required arg the frontend
456475
// wrapper never passed, which silently broke the session-config cache.
457-
["src-tauri/src/commands/agent_config.rs", 1050],
476+
// +60 (1050 -> 1110): agent-config-resolver — resolve_config_surface now
477+
// clears a linked instance's own system_prompt/model/provider before
478+
// computing had_* so stale materialized snapshot bytes can never be tagged
479+
// BuzzExplicit and shadow the definition/global fallthrough; the dead
480+
// persona-model re-tag branch replaced; two new regression tests added.
481+
["src-tauri/src/commands/agent_config.rs", 1110],
458482
// codex-install-auto-restart review-fixes: should_restart_after_install
459483
// takes pid_alive:bool (pure predicate, no OS-dependent call); 3 racy
460484
// cache tests replaced with 6 pure availability_drift predicate tests;
@@ -532,7 +556,9 @@ const overrides = new Map([
532556
// for Databricks v1 gate; prospectiveRuntimeId default fallback for builtins.
533557
// PR-B moves default/API-key derivation into shared hooks; the explicit
534558
// hidden-key projection keeps the top-level secret out of Advanced rows.
535-
["src/features/agents/ui/AgentInstanceEditDialog.tsx", 1195],
559+
// +6 (1195 -> 1201): rebase onto main — this PR's model-source label wiring
560+
// lands on top of main's dialog growth. Queued to split.
561+
["src/features/agents/ui/AgentInstanceEditDialog.tsx", 1201],
536562
// AgentDefinitionDialog grew past 1000 with the following load-bearing fixes:
537563
// isRuntimeAutoSeededRef tracking for edit-mode seeding (Fizz shows models);
538564
// runtimeSupportsLlmProviderSelection guard on discovery provider (codex fix);

‎desktop/src-tauri/src/commands/agent_config.rs‎

Lines changed: 79 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -39,6 +39,13 @@ pub struct RuntimeFileConfigSubset {
3939

4040
/// Resolve the config surface with persona and global default values applied.
4141
///
42+
/// Linked instances are definition-authoritative: the record's own
43+
/// system_prompt/model/provider are cleared before applying, so a stale
44+
/// materialized snapshot can never shadow the persona's current values or a
45+
/// blank-definition fallthrough to global defaults (mirrors
46+
/// `effective_config::resolve_linked`). Definition-less instances keep their
47+
/// own explicit values.
48+
///
4249
/// The pipeline: resolve the linked persona's prompt/model/provider, inject
4350
/// each into the record only where the record lacks its own value, let
4451
/// `read_config_surface` tag those injected fields `BuzzExplicit`, then re-tag
@@ -59,6 +66,22 @@ fn resolve_config_surface(
5966
session_cache: Option<&SessionConfigCache>,
6067
global: &GlobalAgentConfig,
6168
) -> RuntimeConfigSurface {
69+
// Linked instances are definition-authoritative (mirrors
70+
// `effective_config::resolve_linked`): the record's own
71+
// system_prompt/model/provider fields are, at best, a stale materialized
72+
// snapshot from the last `apply_persona_snapshot` — never a legitimate
73+
// live override, since `update_managed_agent` blocks writing these three
74+
// fields for linked instances. Clear them before computing `had_*` below
75+
// so a stale byte can never masquerade as BuzzExplicit and suppress
76+
// definition/global injection. Env var overrides (set via the advanced
77+
// env-vars editor) are untouched — those remain a legitimate
78+
// per-instance override regardless of link status.
79+
if record.persona_id.is_some() {
80+
record.system_prompt = None;
81+
record.model = None;
82+
record.provider = None;
83+
}
84+
6285
let had_prompt =
6386
record.system_prompt.is_some() || record.env_vars.contains_key("BUZZ_ACP_SYSTEM_PROMPT");
6487
let had_model = record.model.is_some();
@@ -172,22 +195,6 @@ fn resolve_config_surface(
172195
retag_global_default(&mut surface.normalized.provider);
173196
}
174197

175-
// Re-tag persona-snapshotted model from BuzzExplicit to PersonaDefault.
176-
// Persona-created agents have record.model set at create time from the
177-
// persona snapshot — had_model is true, but the model came from the persona,
178-
// not an explicit user choice. Re-tag when the record model matches the
179-
// persona model and no live override is active. Only applies when a persona
180-
// is actually linked — non-persona agents with an explicit model keep BuzzExplicit.
181-
if had_model && !model_overridden && record.persona_id.is_some() {
182-
if let (Some(ref record_model), Some(ref persona_model_val)) =
183-
(&record.model, &persona_model)
184-
{
185-
if record_model == persona_model_val {
186-
retag_persona_default(&mut surface.normalized.model);
187-
}
188-
}
189-
}
190-
191198
surface
192199
}
193200

@@ -728,11 +735,64 @@ mod tests {
728735
}
729736
}
730737

731-
/// A model the user set explicitly in Buzz must never be re-tagged to
732-
/// `PersonaDefault`, even when the linked persona also has a model.
738+
/// Definition-authoritative: a stale materialized `record.model` on a
739+
/// linked instance must never outrank (or even be consulted against) the
740+
/// linked persona's model. `update_managed_agent` already blocks writing
741+
/// model/provider/prompt for linked instances, so a non-`None` value here
742+
/// can only be leftover snapshot bytes from before a persona edit — the
743+
/// panel must report the persona's current model, tagged `PersonaDefault`,
744+
/// not the stale byte as `BuzzExplicit`.
745+
#[test]
746+
fn linked_stale_record_model_never_outranks_persona_model() {
747+
let mut record = agent_record();
748+
record.model = Some("stale-explicit-model".to_string());
749+
let personas = vec![persona_with_model("persona-model")];
750+
751+
let surface = resolve_config_surface(
752+
record,
753+
&personas,
754+
Some(goose_runtime()),
755+
None,
756+
&Default::default(),
757+
);
758+
759+
let model = surface.normalized.model.as_ref().expect("model resolved");
760+
assert_eq!(model.value.as_deref(), Some("persona-model"));
761+
assert_eq!(model.origin, ConfigOrigin::PersonaDefault);
762+
}
763+
764+
/// Definition-authoritative, blank-definition case: a linked instance
765+
/// whose persona has no model of its own must fall through to the global
766+
/// default, tagged `GlobalDefault` — mirroring
767+
/// `effective_config::resolve_linked`'s `None => global` arm. A stale
768+
/// materialized record model must not shadow this fallthrough either.
733769
#[test]
734-
fn explicit_record_model_outranks_persona_and_keeps_buzz_explicit_origin() {
770+
fn linked_blank_definition_model_falls_through_to_global_default() {
735771
let mut record = agent_record();
772+
record.model = Some("stale-explicit-model".to_string());
773+
let mut persona = persona_with_model("unused");
774+
persona.model = None;
775+
let personas = vec![persona];
776+
let global = crate::managed_agents::GlobalAgentConfig {
777+
model: Some("global-model".to_string()),
778+
..Default::default()
779+
};
780+
781+
let surface =
782+
resolve_config_surface(record, &personas, Some(goose_runtime()), None, &global);
783+
784+
let model = surface.normalized.model.as_ref().expect("model resolved");
785+
assert_eq!(model.value.as_deref(), Some("global-model"));
786+
assert_eq!(model.origin, ConfigOrigin::GlobalDefault);
787+
}
788+
789+
/// A definition-less (no `persona_id`) instance's own explicit model IS
790+
/// authoritative — the stale-record clearing above is scoped to linked
791+
/// instances only.
792+
#[test]
793+
fn definition_less_explicit_record_model_keeps_buzz_explicit_origin() {
794+
let mut record = agent_record();
795+
record.persona_id = None;
736796
record.model = Some("explicit-model".to_string());
737797
let personas = vec![persona_with_model("persona-model")];
738798

‎desktop/src-tauri/src/commands/agent_models.rs‎

Lines changed: 57 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -87,9 +87,13 @@ pub async fn get_agent_models(
8787

8888
// ModelPicker can persist a selected model but not rewrite the saved
8989
// provider/env snapshot, and runtime spawn reads that same snapshot.
90-
// Discover models against the record snapshot so an out-of-date persona
91-
// cannot offer models for a provider this agent will not launch with.
92-
let discovery = saved_agent_model_discovery_config(record, &effective_command);
90+
// Discover models against the resolver's effective model/provider —
91+
// definition-authoritative for linked instances — so discovery can
92+
// never query a stale provider this agent will not actually launch
93+
// with.
94+
let global = crate::managed_agents::load_global_agent_config(&app).unwrap_or_default();
95+
let discovery =
96+
saved_agent_model_discovery_config(record, &effective_command, &personas, &global);
9397

9498
(
9599
resolved,
@@ -161,27 +165,38 @@ struct SavedAgentModelDiscoveryConfig {
161165
env: BTreeMap<String, String>,
162166
}
163167

168+
/// Resolve the model/provider discovery config from the same authoritative
169+
/// source spawn uses (`resolve_effective_model_provider`) — linked instances
170+
/// read their definition, never a stale materialized `record.model`/
171+
/// `record.provider`, so model discovery cannot query a provider this agent
172+
/// will not actually launch with. Definition-less instances keep their own
173+
/// record values, matching spawn's `resolve_definition_less` arm.
164174
fn saved_agent_model_discovery_config(
165175
record: &crate::managed_agents::ManagedAgentRecord,
166176
agent_command: &str,
177+
personas: &[crate::managed_agents::AgentDefinition],
178+
global: &crate::managed_agents::GlobalAgentConfig,
167179
) -> SavedAgentModelDiscoveryConfig {
168180
let runtime_meta = known_acp_runtime(agent_command);
181+
let (effective_model, effective_provider) =
182+
crate::managed_agents::resolve_effective_model_provider(record, personas, global);
183+
169184
let mut derived_env = BTreeMap::new();
170185
if let Some(meta) = runtime_meta {
171186
for (key, value) in crate::managed_agents::runtime_metadata_env_vars(
172187
meta.model_env_var,
173188
meta.provider_env_var,
174189
meta.provider_locked,
175-
record.model.as_deref(),
176-
record.provider.as_deref(),
190+
effective_model.as_deref(),
191+
effective_provider.as_deref(),
177192
) {
178193
derived_env.insert(key.to_string(), value.to_string());
179194
}
180195
}
181196

182197
SavedAgentModelDiscoveryConfig {
183-
model: record.model.clone(),
184-
provider: record.provider.clone(),
198+
model: effective_model,
199+
provider: effective_provider,
185200
provider_env_var: runtime_meta.and_then(|meta| meta.provider_env_var),
186201
env: crate::managed_agents::merged_user_env(&derived_env, &record.env_vars),
187202
}
@@ -775,6 +790,35 @@ async fn discover_databricks_models(
775790
}))
776791
}
777792

793+
/// Apply an `UpdateManagedAgentRequest`'s model/provider/system_prompt patch
794+
/// to `record`, enforcing the linked-instance write guard: a definition-linked
795+
/// record's model/provider/prompt are definition-authoritative (see
796+
/// `effective_config::resolve_linked`), so writes to these three fields are
797+
/// silently dropped for a linked instance rather than persisting a byte the
798+
/// resolver will never read. Definition-less instances accept the patch
799+
/// as-is. Extracted so the guard is exercised by both `update_managed_agent`
800+
/// and its regression tests — a test that reimplements this check instead of
801+
/// calling it can go green after the real guard is deleted.
802+
fn apply_model_provider_prompt_update(
803+
record: &mut crate::managed_agents::ManagedAgentRecord,
804+
model: Option<Option<String>>,
805+
provider: Option<Option<String>>,
806+
system_prompt: Option<Option<String>>,
807+
) {
808+
if record.persona_id.is_some() {
809+
return;
810+
}
811+
if let Some(model_update) = model {
812+
record.model = model_update;
813+
}
814+
if let Some(provider_update) = provider {
815+
record.provider = provider_update;
816+
}
817+
if let Some(prompt_update) = system_prompt {
818+
record.system_prompt = prompt_update;
819+
}
820+
}
821+
778822
/// Update mutable fields on an existing managed agent record.
779823
///
780824
/// Does NOT auto-restart the agent. Runtime config changes (system prompt,
@@ -814,15 +858,12 @@ pub async fn update_managed_agent(
814858
name_changed = true;
815859
}
816860
}
817-
if let Some(model_update) = input.model {
818-
record.model = model_update;
819-
}
820-
if let Some(provider_update) = input.provider {
821-
record.provider = provider_update;
822-
}
823-
if let Some(prompt_update) = input.system_prompt {
824-
record.system_prompt = prompt_update;
825-
}
861+
apply_model_provider_prompt_update(
862+
record,
863+
input.model,
864+
input.provider,
865+
input.system_prompt,
866+
);
826867
if let Some(parallelism) = input.parallelism {
827868
record.parallelism = parallelism;
828869
}

0 commit comments

Comments
 (0)