From 86d7748ebd93027754bfd2326958c4324aa817d6 Mon Sep 17 00:00:00 2001 From: Will Pfleger Date: Wed, 24 Jun 2026 11:58:48 -0400 Subject: [PATCH 01/60] fix(desktop): resolve repos_dir symlink at boot before agent restore (#1231) Signed-off-by: Will Pfleger Co-authored-by: npub1mn7jgtj4w2pd0g0zeuhxsa6jy6p0rewxz4kujt98my82ahfmp72sxjexk7 --- crates/buzz-relay/src/handlers/event.rs | 1 + desktop/scripts/check-file-sizes.mjs | 9 +- desktop/src-tauri/src/commands/workspace.rs | 90 ++-- desktop/src-tauri/src/lib.rs | 38 +- desktop/src-tauri/src/managed_agents/mod.rs | 5 +- desktop/src-tauri/src/managed_agents/repos.rs | 389 ++++++++++++++++++ .../workspaces/ui/AddWorkspaceDialog.tsx | 21 +- .../workspaces/ui/EditWorkspaceDialog.tsx | 23 +- .../features/workspaces/useWorkspaceInit.ts | 15 +- desktop/src/shared/api/tauri.ts | 6 + 10 files changed, 544 insertions(+), 53 deletions(-) diff --git a/crates/buzz-relay/src/handlers/event.rs b/crates/buzz-relay/src/handlers/event.rs index 0190b36ee..4cdcf8b2a 100644 --- a/crates/buzz-relay/src/handlers/event.rs +++ b/crates/buzz-relay/src/handlers/event.rs @@ -1065,6 +1065,7 @@ mod tests { CancellationToken::new(), Arc::new(AtomicU8::new(0)), Arc::new(Mutex::new(HashMap::new())), + 3, ); state.sub_registry.register( conn_id, diff --git a/desktop/scripts/check-file-sizes.mjs b/desktop/scripts/check-file-sizes.mjs index cc6050e87..556046b1e 100644 --- a/desktop/scripts/check-file-sizes.mjs +++ b/desktop/scripts/check-file-sizes.mjs @@ -41,10 +41,11 @@ const overrides = new Map([ ["src-tauri/src/managed_agents/runtime.rs", 1953], ["src-tauri/src/managed_agents/personas.rs", 1080], ["src-tauri/src/managed_agents/persona_card.rs", 1050], - // applyWorkspace reposDir parameter threaded through the Tauri invoke for - // configurable repos_dir — a 3-line overage from load-bearing parameter - // plumbing, not generic debt growth. Approved override; still queued to split. - ["src/shared/api/tauri.ts", 1198], + // applyWorkspace reposDir parameter plus the validateReposDir binding, + // threaded through Tauri invokes for configurable repos_dir — a 4-line + // overage from load-bearing parameter plumbing, not generic debt growth. + // Approved override; still queued to split. + ["src/shared/api/tauri.ts", 1199], ["src-tauri/src/nostr_convert.rs", 1126], ["src/shared/api/relayClientSession.ts", 1022], ["src-tauri/src/migration.rs", 1295], diff --git a/desktop/src-tauri/src/commands/workspace.rs b/desktop/src-tauri/src/commands/workspace.rs index 7c3529fc1..7c0e4b832 100644 --- a/desktop/src-tauri/src/commands/workspace.rs +++ b/desktop/src-tauri/src/commands/workspace.rs @@ -3,7 +3,10 @@ use serde::Serialize; use tauri::{AppHandle, Emitter, State}; use crate::app_state::AppState; -use crate::managed_agents::{ensure_repos_symlink, nest_dir, try_regenerate_nest}; +use crate::managed_agents::{ + effective_repos_dir, ensure_repos_symlink, nest_dir, try_regenerate_nest, + write_persisted_repos_dir, +}; use crate::relay; #[derive(Serialize)] @@ -23,18 +26,36 @@ pub fn get_active_workspace(state: State<'_, AppState>) -> Result Result<(), String> { + let trimmed = dir.trim(); + if trimmed.is_empty() { + return Ok(()); + } + let nest = nest_dir().ok_or("cannot resolve home directory for nest")?; + crate::managed_agents::validate_repos_dir(&nest, trimmed).map(|_| ()) +} + /// Apply a workspace's configuration to the backend session. /// /// Called by the frontend on app init (after reload) to configure the /// Tauri backend with the selected workspace's relay URL, keys, and repos /// directory. /// -/// Validation runs before any state mutation: an invalid `repos_dir` (bad -/// path) rejects cleanly with nothing applied. The `REPOS` symlink itself is -/// a filesystem *side-effect* — its failure (e.g. a non-empty real `REPOS` -/// refusing a downgrade, or a renamed external target on a later launch) is -/// non-fatal: relay/keys still apply, the command returns `Ok`, and a -/// `repos-dir-error` event surfaces the failure to the frontend. +/// A bad `repos_dir` is non-fatal: relay/keys always apply (the relay is the +/// active workspace's own choice — orthogonal to the filesystem repos dir), +/// the bad value is NOT persisted (so the next boot starts clean), the +/// `REPOS` symlink is skipped (REPOS stays a real dir), a `repos-dir-error` +/// event surfaces the reason, and the command returns `Ok`. The dialogs +/// already block a bad path at Save (`validate_repos_dir`); this fallback only +/// catches a value that went bad after save (deleted dir, unmounted volume). #[tauri::command] pub fn apply_workspace( relay_url: String, @@ -51,23 +72,25 @@ pub fn apply_workspace( None => None, }; - // Normalize repos_dir to a trimmed non-empty value. `None`/empty clears - // the override (REPOS falls back to a real dir). A bad path is rejected - // here — before any mutation — so the dialog sees a clean Err. - let repos_dir = repos_dir - .map(|s| s.trim().to_string()) - .filter(|s| !s.is_empty()); - if let Some(dir) = repos_dir.as_deref() { - let nest = nest_dir().ok_or("cannot resolve home directory for nest")?; - // Validate without mutating the filesystem. Keeps the command's - // "validate-first, nothing below can fail" contract honest. Also emit - // the error so it surfaces even at the init call site (which swallows - // the returned Err to console for the relay/keys path). - if let Err(error) = crate::managed_agents::validate_repos_dir(&nest, dir) { - let _ = app.emit("repos-dir-error", error.clone()); - return Err(error); - } - } + // Decide the effective repos_dir from the candidate. A bad path does NOT + // reject — it is treated as if no override were set: relay/keys still + // apply, the bad value is not persisted, and a `repos-dir-error` surfaces + // the reason. Persisting a bad path would make every later boot read it, + // fail to resolve the symlink, and silently skip agent restore. One + // validate (inside `effective_repos_dir`) drives both the emit and the + // persisted value. `nest` is resolved softly: when absent there is nothing + // to persist or symlink, and relay/keys must still apply unconditionally. + let nest = nest_dir(); + let effective_repos_dir = match nest.as_deref() { + Some(nest) => match effective_repos_dir(nest, repos_dir.as_deref()) { + Ok(value) => value, + Err(error) => { + let _ = app.emit("repos-dir-error", error); + None + } + }, + None => None, + }; // ── Apply all state changes (nothing below can fail) ────────────────── { @@ -81,11 +104,20 @@ pub fn apply_workspace( } // ── Filesystem side-effect (non-fatal) ──────────────────────────────── - // Re-point REPOS to match repos_dir. Failure here (downgrade refused, - // external target gone) must NOT fail the command — relay/keys are already - // applied. Surface it via a `repos-dir-error` event the frontend toasts. - if let Some(nest) = nest_dir() { - if let Err(error) = ensure_repos_symlink(&nest, repos_dir.as_deref()) { + // Persist the *effective* repos_dir (None when the candidate failed + // validation) for the backend to read at boot, then re-point REPOS to + // match. Persisting first makes the dotfile authoritative even if the + // symlink apply fails here (e.g. a non-empty real REPOS): the next boot + // reads the persisted value and resolves the symlink before any agent can + // clone into REPOS. A bad candidate persists `None`, so the next boot is + // clean and agent restore proceeds. Failure of either must NOT fail the + // command — relay/keys are already applied. Surface symlink errors via + // `repos-dir-error`. + if let Some(nest) = nest.as_deref() { + if let Err(error) = write_persisted_repos_dir(nest, effective_repos_dir.as_deref()) { + eprintln!("buzz-desktop: persist repos dir failed: {error}"); + } + if let Err(error) = ensure_repos_symlink(nest, effective_repos_dir.as_deref()) { eprintln!("buzz-desktop: repos dir setup failed: {error}"); let _ = app.emit("repos-dir-error", error); } diff --git a/desktop/src-tauri/src/lib.rs b/desktop/src-tauri/src/lib.rs index d9b26841f..8cf55b13e 100644 --- a/desktop/src-tauri/src/lib.rs +++ b/desktop/src-tauri/src/lib.rs @@ -586,6 +586,21 @@ pub fn run() { eprintln!("buzz-desktop: failed to create nest: {error}"); } + // Resolve the REPOS symlink from the persisted repos_dir BEFORE + // agents are restored below, and decide whether restore is safe. + // The frontend's apply_workspace runs only after React mounts — + // later than the async agent restore — so without this an agent + // could clone into the empty real REPOS dir, and once REPOS is + // non-empty ensure_repos_symlink refuses forever. resolve_repos_at_boot + // fails closed: if a repos_dir was configured but its symlink could + // not be resolved (transiently unavailable external volume), it + // returns false so we skip restore this launch rather than let an + // agent clone into the wrong REPOS. See managed_agents::repos. + let restore_agents = match managed_agents::nest_dir() { + Some(nest) => managed_agents::resolve_repos_at_boot(&nest), + None => true, + }; + // Carry the agent's knowledge from the legacy nest (~/.sprout) into // the live nest (~/.buzz) after it exists. Must run after // ensure_nest() so the destination is present. Non-fatal. @@ -637,14 +652,20 @@ pub fn run() { } // Keep launch-time agent restoration off the synchronous setup path - // so the frontend can mount and reveal the window promptly. - tauri::async_runtime::spawn(async move { - if let Err(error) = - restore_managed_agents_on_launch(&app_handle, shutdown_started.as_ref()).await - { - eprintln!("buzz-desktop: failed to restore managed agents: {error}"); - } - }); + // so the frontend can mount and reveal the window promptly. Gated on + // the boot-time repos symlink result (see restore_agents above): + // skip when a configured repos_dir could not be resolved, so no + // agent clones into a REPOS that isn't the user's target. + if restore_agents { + tauri::async_runtime::spawn(async move { + if let Err(error) = + restore_managed_agents_on_launch(&app_handle, shutdown_started.as_ref()) + .await + { + eprintln!("buzz-desktop: failed to restore managed agents: {error}"); + } + }); + } // Periodic sweep: reap orphaned agents from dead instances every 60s. // Catches agents that escaped both the Justfile trap and boot-time @@ -844,6 +865,7 @@ pub fn run() { confirm_pairing_sas, cancel_pairing, apply_workspace, + validate_repos_dir, get_active_workspace, set_prevent_sleep_active, get_agent_memory, diff --git a/desktop/src-tauri/src/managed_agents/mod.rs b/desktop/src-tauri/src/managed_agents/mod.rs index 18d6af277..ca996c96a 100644 --- a/desktop/src-tauri/src/managed_agents/mod.rs +++ b/desktop/src-tauri/src/managed_agents/mod.rs @@ -27,7 +27,10 @@ pub use personas::*; pub use process_lifecycle::*; #[cfg(feature = "mesh-llm")] pub use relay_mesh::*; -pub use repos::{ensure_repos_symlink, validate_repos_dir}; +pub use repos::{ + effective_repos_dir, ensure_repos_symlink, resolve_repos_at_boot, validate_repos_dir, + write_persisted_repos_dir, +}; pub use restore::*; pub use runtime::*; pub use storage::*; diff --git a/desktop/src-tauri/src/managed_agents/repos.rs b/desktop/src-tauri/src/managed_agents/repos.rs index dd81950c4..1228ad74c 100644 --- a/desktop/src-tauri/src/managed_agents/repos.rs +++ b/desktop/src-tauri/src/managed_agents/repos.rs @@ -164,6 +164,117 @@ pub fn ensure_repos_setup_default(nest_root: &Path) -> Result<(), String> { ensure_repos_symlink(nest_root, None) } +/// Decide what `repos_dir` `apply_workspace` should persist and symlink for a +/// candidate value, running the single source-of-truth [`validate_repos_dir`]. +/// +/// - **`None`/empty candidate** → `Ok(None)`: no override; `REPOS` reverts to a +/// real in-nest directory. +/// - **valid candidate** → `Ok(Some(raw_trimmed))`: persist the *raw* trimmed +/// string (not the canonical path — persisting canonical would drift the +/// symlink target on `..`/symlinked-ancestor paths). +/// - **invalid candidate** → `Err(reason)`: the caller must persist `None` +/// (clearing the override so the next boot resolves clean and agent restore +/// proceeds) and surface `reason` to the user. Returning `Err` rather than +/// silently `Ok(None)` lets the caller emit the human-readable cause. +/// +/// One validate call drives both the persisted value and the error: a bad path +/// is never persisted, so it can never silently skip agent restore on a later +/// boot. Pure (no FS mutation, no emit) so the persist decision is unit-tested. +pub fn effective_repos_dir( + nest_root: &Path, + candidate: Option<&str>, +) -> Result, String> { + let Some(trimmed) = candidate.map(str::trim).filter(|s| !s.is_empty()) else { + return Ok(None); + }; + validate_repos_dir(nest_root, trimmed).map(|_| Some(trimmed.to_string())) +} + +/// Filename of the dotfile persisting the active workspace's `repos_dir`. +const REPOS_DIR_FILE: &str = ".repos-dir"; + +/// Read the persisted `repos_dir` from `nest_root/.repos-dir`. +/// +/// Returns the trimmed value, or `None` when the file is absent, unreadable, +/// or empty. This is the backend's sole knowledge of `repos_dir` at boot — +/// the frontend persists it via [`write_persisted_repos_dir`] on every +/// `apply_workspace`, so [`resolve_repos_at_boot`] can resolve the `REPOS` +/// symlink before any agent is restored. +fn read_persisted_repos_dir(nest_root: &Path) -> Option { + fs::read_to_string(nest_root.join(REPOS_DIR_FILE)) + .ok() + .map(|s| s.trim().to_string()) + .filter(|s| !s.is_empty()) +} + +/// Persist the active workspace's `repos_dir` to `nest_root/.repos-dir`. +/// +/// Writes the trimmed value (one line). A `None`/empty value clears the +/// override by removing the file, so a later boot reverts `REPOS` to a real +/// in-nest directory. Removing an absent file is not an error. Mirrors the +/// `.nest-agents-version` dotfile pattern. +pub fn write_persisted_repos_dir(nest_root: &Path, repos_dir: Option<&str>) -> Result<(), String> { + let path = nest_root.join(REPOS_DIR_FILE); + match repos_dir.map(str::trim).filter(|s| !s.is_empty()) { + Some(value) => fs::write(&path, format!("{value}\n")) + .map_err(|e| format!("write {}: {e}", path.display())), + None => match fs::remove_file(&path) { + Ok(()) => Ok(()), + Err(e) if e.kind() == io::ErrorKind::NotFound => Ok(()), + Err(e) => Err(format!("remove {}: {e}", path.display())), + }, + } +} + +/// Decide whether launch-time agent restore is safe given the boot symlink +/// outcome. Fails CLOSED: when a `repos_dir` was configured but its symlink +/// could not be resolved, restoring agents would let one clone into the empty +/// real `REPOS` that `ensure_nest` provisioned — the wrong location — and once +/// it is non-empty [`ensure_repos_symlink`] refuses forever, permanently +/// re-triggering the race. Skipping restore is recoverable on the next boot +/// once the external target is reachable; a misplaced clone is not. +/// +/// The no-`repos_dir` case (`persisted_present == false`) is always safe: the +/// real in-nest `REPOS` default is exactly where clones belong. +fn should_restore_agents(persisted_present: bool, symlink_result: &Result<(), String>) -> bool { + !(persisted_present && symlink_result.is_err()) +} + +/// Resolve the `REPOS` symlink at boot from the persisted `repos_dir` and +/// report whether agent restore is safe to proceed. +/// +/// Runs in the synchronous setup hook, after `ensure_nest` and before the +/// async agent restore is spawned, so `REPOS` is the user's configured symlink +/// before any agent can clone. Logs on failure (no toast path exists +/// pre-mount) and returns the fail-closed [`should_restore_agents`] decision. +pub fn resolve_repos_at_boot(nest_root: &Path) -> bool { + let persisted = read_persisted_repos_dir(nest_root); + let symlink_result = ensure_repos_symlink(nest_root, persisted.as_deref()); + if let Err(error) = &symlink_result { + eprintln!("buzz-desktop: repos dir setup failed at boot: {error}"); + } + let restore = should_restore_agents(persisted.is_some(), &symlink_result); + // Log the resolved outcome on success so a healthy boot is observable (the + // Err/skip branches already log; previously success was silent). + if symlink_result.is_ok() { + match persisted.as_deref() { + Some(dir) => eprintln!( + "buzz-desktop: repos dir resolved at boot — REPOS symlinked to configured `{dir}`" + ), + None => eprintln!( + "buzz-desktop: repos dir resolved at boot — no configured override, REPOS is the default real dir" + ), + } + } + if !restore { + eprintln!( + "buzz-desktop: skipping agent restore — configured repos_dir `{}` could not be resolved at boot; will retry on next launch", + persisted.as_deref().unwrap_or_default() + ); + } + restore +} + #[cfg(test)] mod tests { use super::*; @@ -383,6 +494,284 @@ mod tests { ); } + // ── persisted repos_dir dotfile ─────────────────────────────────────── + + #[test] + fn persisted_repos_dir_roundtrips_write_read_clear() { + let tmp = tempfile::tempdir().unwrap(); + let root = tmp.path().join(".buzz"); + fs::create_dir_all(&root).unwrap(); + + assert_eq!(read_persisted_repos_dir(&root), None, "absent → None"); + + write_persisted_repos_dir(&root, Some(" /Users/me/Development ")).unwrap(); + assert_eq!( + read_persisted_repos_dir(&root).as_deref(), + Some("/Users/me/Development"), + "value is trimmed on write/read" + ); + + write_persisted_repos_dir(&root, None).unwrap(); + assert_eq!(read_persisted_repos_dir(&root), None, "cleared → None"); + assert!( + !root.join(".repos-dir").exists(), + "clearing removes the dotfile" + ); + } + + #[test] + fn persisted_repos_dir_empty_value_clears() { + let tmp = tempfile::tempdir().unwrap(); + let root = tmp.path().join(".buzz"); + fs::create_dir_all(&root).unwrap(); + write_persisted_repos_dir(&root, Some("/Users/me/Development")).unwrap(); + + write_persisted_repos_dir(&root, Some(" ")).unwrap(); + assert_eq!( + read_persisted_repos_dir(&root), + None, + "a whitespace-only value clears the override" + ); + } + + #[test] + fn persisted_repos_dir_clear_when_absent_is_ok() { + let tmp = tempfile::tempdir().unwrap(); + let root = tmp.path().join(".buzz"); + fs::create_dir_all(&root).unwrap(); + + write_persisted_repos_dir(&root, None).expect("clearing an absent dotfile is not an error"); + } + + #[cfg(unix)] + #[test] + fn boot_resolves_symlink_from_persisted_value_into_empty_repos() { + // Mirrors the boot sequence: ensure_nest leaves REPOS an empty real + // dir, then the setup hook reads the persisted value and symlinks. + let tmp = tempfile::tempdir().unwrap(); + let root = tmp.path().join(".buzz"); + fs::create_dir_all(root.join("REPOS")).unwrap(); + let external = tmp.path().join("Development"); + fs::create_dir_all(&external).unwrap(); + + write_persisted_repos_dir(&root, Some(external.to_str().unwrap())).unwrap(); + let persisted = read_persisted_repos_dir(&root); + ensure_repos_symlink(&root, persisted.as_deref()).unwrap(); + + let repos = root.join("REPOS"); + assert!( + repos.symlink_metadata().unwrap().file_type().is_symlink(), + "boot must convert the empty real REPOS into a symlink" + ); + assert_eq!(repos.read_link().unwrap(), external.canonicalize().unwrap()); + } + + #[cfg(unix)] + #[test] + fn boot_leaves_already_correct_symlink_untouched() { + let tmp = tempfile::tempdir().unwrap(); + let root = tmp.path().join(".buzz"); + fs::create_dir_all(&root).unwrap(); + let external = tmp.path().join("Development"); + fs::create_dir_all(&external).unwrap(); + + write_persisted_repos_dir(&root, Some(external.to_str().unwrap())).unwrap(); + // First boot converts; second boot must be a noop. + let persisted = read_persisted_repos_dir(&root); + ensure_repos_symlink(&root, persisted.as_deref()).unwrap(); + ensure_repos_symlink(&root, persisted.as_deref()).unwrap(); + + let repos = root.join("REPOS"); + assert!(repos.symlink_metadata().unwrap().file_type().is_symlink()); + assert_eq!(repos.read_link().unwrap(), external.canonicalize().unwrap()); + } + + #[cfg(unix)] + #[test] + fn boot_with_cleared_value_reverts_symlink_to_real_dir() { + let tmp = tempfile::tempdir().unwrap(); + let root = tmp.path().join(".buzz"); + fs::create_dir_all(&root).unwrap(); + let external = tmp.path().join("Development"); + fs::create_dir_all(&external).unwrap(); + fs::write(external.join("KEEP.md"), "data").unwrap(); + + // Configure, then clear the field. + write_persisted_repos_dir(&root, Some(external.to_str().unwrap())).unwrap(); + ensure_repos_symlink(&root, read_persisted_repos_dir(&root).as_deref()).unwrap(); + write_persisted_repos_dir(&root, None).unwrap(); + + // Next boot reads None and reverts REPOS to a real in-nest dir. + ensure_repos_symlink(&root, read_persisted_repos_dir(&root).as_deref()).unwrap(); + + let repos = root.join("REPOS"); + assert!( + !repos.symlink_metadata().unwrap().file_type().is_symlink(), + "clearing the persisted value reverts REPOS to a real dir" + ); + assert!( + external.join("KEEP.md").exists(), + "reverting must not touch the external target's contents" + ); + } + + #[cfg(unix)] + #[test] + fn effective_repos_dir_drives_persisted_dotfile_for_all_three_cases() { + // Pins the CRITICAL persist decision on `.repos-dir` CONTENTS, not just + // a return value: a bad path must clear the dotfile so the next boot's + // `should_restore_agents(false, _)` restores agents (the regression + // this hardening fixes). Drives each case through the same + // effective→persist path `apply_workspace` uses. + let tmp = tempfile::tempdir().unwrap(); + let root = tmp.path().join(".buzz"); + fs::create_dir_all(&root).unwrap(); + let good = tmp.path().join("Development"); + fs::create_dir_all(&good).unwrap(); + let good_str = good.to_str().unwrap(); + + // Pre-seed a value so each case proves it overwrites/clears, not just + // that an absent dotfile stays absent. + let seed = |root: &Path| write_persisted_repos_dir(root, Some(good_str)).unwrap(); + let persist = |root: &Path, candidate: Option<&str>| { + let effective = effective_repos_dir(root, candidate); + // Mirror apply_workspace: Err clears the override (persist None). + let to_persist = effective.unwrap_or(None); + write_persisted_repos_dir(root, to_persist.as_deref()).unwrap(); + }; + + // Bad path → Err → dotfile cleared (the CRITICAL). + seed(&root); + persist(&root, Some("/no/such/dir/here")); + assert_eq!( + read_persisted_repos_dir(&root), + None, + "a bad repos_dir must clear `.repos-dir` so the next boot restores agents" + ); + + // Good path → Ok(Some(raw)) → dotfile holds the raw trimmed value. + persist(&root, Some(&format!(" {good_str} "))); + assert_eq!( + read_persisted_repos_dir(&root).as_deref(), + Some(good_str), + "a valid repos_dir must persist the raw trimmed path (not the canonical path)" + ); + + // Empty/whitespace → Ok(None) → dotfile cleared. + seed(&root); + persist(&root, Some(" ")); + assert_eq!( + read_persisted_repos_dir(&root), + None, + "an empty repos_dir clears the override" + ); + + // None candidate → Ok(None) → dotfile cleared. + seed(&root); + persist(&root, None); + assert_eq!( + read_persisted_repos_dir(&root), + None, + "no repos_dir clears the override" + ); + } + + // ── resolve_repos_at_boot (boot sequence + fail-closed gate) ────────── + + #[cfg(unix)] + #[test] + fn resolve_repos_at_boot_converts_empty_real_repos_and_allows_restore() { + // Drives the real boot sequence: ensure_repos_setup_default (called by + // ensure_nest) provisions REPOS as an empty real dir, then the setup + // hook calls resolve_repos_at_boot. Asserts the convert happens at that + // position and restore is allowed. + let tmp = tempfile::tempdir().unwrap(); + let root = tmp.path().join(".buzz"); + fs::create_dir_all(&root).unwrap(); + let external = tmp.path().join("Development"); + fs::create_dir_all(&external).unwrap(); + write_persisted_repos_dir(&root, Some(external.to_str().unwrap())).unwrap(); + + ensure_repos_setup_default(&root).unwrap(); + let repos = root.join("REPOS"); + assert!( + repos.is_dir() && !repos.symlink_metadata().unwrap().file_type().is_symlink(), + "ensure_nest provisions REPOS as an empty real dir before the boot resolve" + ); + + let restore = resolve_repos_at_boot(&root); + + assert!(restore, "restore proceeds when the symlink resolves"); + assert!( + repos.symlink_metadata().unwrap().file_type().is_symlink(), + "boot resolve converts the empty real REPOS into the configured symlink" + ); + assert_eq!(repos.read_link().unwrap(), external.canonicalize().unwrap()); + } + + #[cfg(unix)] + #[test] + fn resolve_repos_at_boot_fails_closed_when_target_unresolvable() { + // Persisted repos_dir whose target does not exist at boot (transiently + // unavailable external volume) → ensure_repos_symlink Errs. Restore must + // be skipped and REPOS left as the empty real dir, never the symlink, so + // no agent clones into the wrong place. + let tmp = tempfile::tempdir().unwrap(); + let root = tmp.path().join(".buzz"); + fs::create_dir_all(&root).unwrap(); + let missing = tmp.path().join("not-mounted-yet"); + write_persisted_repos_dir(&root, Some(missing.to_str().unwrap())).unwrap(); + ensure_repos_setup_default(&root).unwrap(); + + let restore = resolve_repos_at_boot(&root); + + assert!( + !restore, + "restore must be skipped when a configured repos_dir cannot resolve at boot" + ); + let repos = root.join("REPOS"); + assert!( + !repos.symlink_metadata().unwrap().file_type().is_symlink(), + "REPOS must not become a symlink to an unresolved target" + ); + } + + #[cfg(unix)] + #[test] + fn resolve_repos_at_boot_allows_restore_with_no_repos_dir() { + // No configured repos_dir → the real in-nest REPOS default is correct, + // restore proceeds normally (the fail-closed gate must not fire here). + let tmp = tempfile::tempdir().unwrap(); + let root = tmp.path().join(".buzz"); + fs::create_dir_all(&root).unwrap(); + ensure_repos_setup_default(&root).unwrap(); + + assert!( + resolve_repos_at_boot(&root), + "restore proceeds when no repos_dir is configured" + ); + } + + #[test] + fn should_restore_agents_only_blocks_configured_unresolved_boot() { + assert!( + should_restore_agents(false, &Ok(())), + "no repos_dir, symlink ok → restore" + ); + assert!( + should_restore_agents(false, &Err("boom".into())), + "no repos_dir → real-dir default is correct even on Err → restore" + ); + assert!( + should_restore_agents(true, &Ok(())), + "configured repos_dir resolved → restore" + ); + assert!( + !should_restore_agents(true, &Err("boom".into())), + "configured repos_dir unresolved → fail closed, skip restore" + ); + } + /// Test helper: canonicalize a path, creating it as a directory first. #[cfg(unix)] trait CanonicalizeOrMake { diff --git a/desktop/src/features/workspaces/ui/AddWorkspaceDialog.tsx b/desktop/src/features/workspaces/ui/AddWorkspaceDialog.tsx index 2c402664d..421c4c900 100644 --- a/desktop/src/features/workspaces/ui/AddWorkspaceDialog.tsx +++ b/desktop/src/features/workspaces/ui/AddWorkspaceDialog.tsx @@ -6,6 +6,7 @@ import { expandTilde, normalizeRelayUrl, } from "@/features/workspaces/workspaceStorage"; +import { validateReposDir } from "@/shared/api/tauri"; import { Button } from "@/shared/ui/button"; import { Dialog, @@ -31,6 +32,7 @@ export function AddWorkspaceDialog({ const [relayUrl, setRelayUrl] = React.useState(""); const [token, setToken] = React.useState(""); const [reposDir, setReposDir] = React.useState(""); + const [reposDirError, setReposDirError] = React.useState(null); const handleClose = React.useCallback(() => { onOpenChange(false); @@ -38,6 +40,7 @@ export function AddWorkspaceDialog({ setRelayUrl(""); setToken(""); setReposDir(""); + setReposDirError(null); }, [onOpenChange]); const handleSubmit = React.useCallback( @@ -48,8 +51,16 @@ export function AddWorkspaceDialog({ } // Expand `~` before save — the backend rejects tilde paths. Empty input - // resolves to `undefined` so REPOS keeps its default location. + // resolves to `undefined` so REPOS keeps its default location. Validate + // the expanded value (the bytes the backend canonicalizes) before save + // so a bad path is caught here instead of bricking a later boot. const expandedReposDir = await expandTilde(reposDir); + try { + await validateReposDir(expandedReposDir ?? ""); + } catch (error) { + setReposDirError(String(error)); + return; + } const workspace: Workspace = { id: crypto.randomUUID(), @@ -144,11 +155,17 @@ export function AddWorkspaceDialog({ setReposDir(e.target.value)} + onChange={(e) => { + setReposDir(e.target.value); + setReposDirError(null); + }} placeholder="~/Development" type="text" value={reposDir} /> + {reposDirError ? ( +

{reposDirError}

+ ) : null}

Point the agent's REPOS directory at an existing folder so agents work in your local checkouts. Leave blank to use diff --git a/desktop/src/features/workspaces/ui/EditWorkspaceDialog.tsx b/desktop/src/features/workspaces/ui/EditWorkspaceDialog.tsx index 8dacc030c..88fe4017e 100644 --- a/desktop/src/features/workspaces/ui/EditWorkspaceDialog.tsx +++ b/desktop/src/features/workspaces/ui/EditWorkspaceDialog.tsx @@ -5,6 +5,7 @@ import { expandTilde, normalizeRelayUrl, } from "@/features/workspaces/workspaceStorage"; +import { validateReposDir } from "@/shared/api/tauri"; import { Button } from "@/shared/ui/button"; import { Dialog, @@ -41,6 +42,7 @@ export function EditWorkspaceDialog({ const [relayUrl, setRelayUrl] = React.useState(""); const [token, setToken] = React.useState(""); const [reposDir, setReposDir] = React.useState(""); + const [reposDirError, setReposDirError] = React.useState(null); // Sync form state when the dialog opens with a workspace React.useEffect(() => { @@ -49,6 +51,7 @@ export function EditWorkspaceDialog({ setRelayUrl(workspace.relayUrl); setToken(workspace.token ?? ""); setReposDir(workspace.reposDir ?? ""); + setReposDirError(null); } }, [workspace, open]); @@ -84,10 +87,18 @@ export function EditWorkspaceDialog({ // Expand `~` to an absolute path before save — the backend rejects // tilde paths. An empty field clears the override (REPOS reverts to a - // real dir). Only emit when the resolved value actually changed so a - // no-op edit doesn't trigger a backend re-apply. + // real dir). Validate the expanded value (the bytes the backend + // canonicalizes) before save so a bad path is caught here instead of + // bricking a later boot. Only emit when the resolved value actually + // changed so a no-op edit doesn't trigger a backend re-apply. const expandedReposDir = await expandTilde(reposDir); if (expandedReposDir !== workspace.reposDir) { + try { + await validateReposDir(expandedReposDir ?? ""); + } catch (error) { + setReposDirError(String(error)); + return; + } updates.reposDir = expandedReposDir; } @@ -185,11 +196,17 @@ export function EditWorkspaceDialog({ setReposDir(e.target.value)} + onChange={(e) => { + setReposDir(e.target.value); + setReposDirError(null); + }} placeholder="~/Development" type="text" value={reposDir} /> + {reposDirError ? ( +

{reposDirError}

+ ) : null}

Point the agent's REPOS directory at an existing folder so agents work in your local checkouts. Leave blank to use diff --git a/desktop/src/features/workspaces/useWorkspaceInit.ts b/desktop/src/features/workspaces/useWorkspaceInit.ts index c0d20f108..fe01c30ce 100644 --- a/desktop/src/features/workspaces/useWorkspaceInit.ts +++ b/desktop/src/features/workspaces/useWorkspaceInit.ts @@ -139,12 +139,15 @@ export function useWorkspaceInit( activeWorkspace.reposDir, ); } catch (error) { - // apply_workspace validates repos_dir before touching relay/keys, so a - // hard reject (bad path) leaves the backend on the previous/default - // relay with nothing applied. Marking the workspace ready here would - // render workspace-scoped UI against the wrong relay — a silent - // split-brain. Park on the loading gate (isReady:false, no appliedKey) - // instead; the backend already toasts a `repos-dir-error`. + // A bad `repos_dir` no longer reaches here — `apply_workspace` treats + // it as non-fatal (relay/keys apply, bad value not persisted, REPOS + // falls back to a real dir, a `repos-dir-error` toast surfaces it) and + // returns Ok, so the app boots into a working state where the user can + // fix the value in workspace settings. This catch now only fires on a + // genuine relay/key apply failure (e.g. an invalid nsec or a poisoned + // lock). For those, marking the workspace ready would render + // workspace-scoped UI against a backend that never applied — park on + // the loading gate (isReady:false, no appliedKey) instead. console.error("Failed to apply workspace to backend:", error); if (!cancelled) { setResult({ isReady: false, needsSetup: false, appliedKey: null }); diff --git a/desktop/src/shared/api/tauri.ts b/desktop/src/shared/api/tauri.ts index 519f3fd85..1975e016e 100644 --- a/desktop/src/shared/api/tauri.ts +++ b/desktop/src/shared/api/tauri.ts @@ -1188,5 +1188,11 @@ export async function applyWorkspace( }); } +// Validate a candidate repos dir without mutating the filesystem. Rejects +// with a human-readable reason; resolves for a valid or empty path. +export async function validateReposDir(dir: string): Promise { + await invokeTauri("validate_repos_dir", { dir }); +} + export const setPreventSleepActive = (active: boolean) => invokeTauri("set_prevent_sleep_active", { active }); From 733c766eba90733a00dc397dd2ab9706935e5183 Mon Sep 17 00:00:00 2001 From: Wes Date: Wed, 24 Jun 2026 09:39:16 -0700 Subject: [PATCH 02/60] fix(desktop): clear unread projections from message read markers (#1242) Signed-off-by: Wes Co-authored-by: Pinky <44b8e82baa6e0e254e0208d68f335c283c94e7b78dd1fa10d5a49d3f13dd0435@sprout-oss.stage.blox.sqprod.co> --- desktop/src/app/AppShell.tsx | 1 + .../readState/readStateFormat.test.mjs | 39 ++++- .../channels/readState/readStateFormat.ts | 23 ++- .../channels/readState/readStateManager.ts | 20 +-- .../features/channels/unreadChannelCounts.ts | 14 +- .../channels/unreadReadMarker.test.mjs | 57 ++++++- .../features/channels/useUnreadChannels.ts | 7 +- desktop/src/features/home/ui/HomeView.tsx | 2 + .../home/useHomeInboxReadState.test.mjs | 65 ++++++++ .../features/home/useHomeInboxReadState.ts | 46 ++++-- .../src/features/notifications/hooks.test.mjs | 46 ++++++ desktop/src/features/notifications/hooks.ts | 39 ++--- .../features/notifications/lib/homeBadge.ts | 59 +++++++ docs/nips/NIP-RS.md | 150 +++++++++++------- 14 files changed, 446 insertions(+), 122 deletions(-) diff --git a/desktop/src/app/AppShell.tsx b/desktop/src/app/AppShell.tsx index b4b2ef77b..afa5f3ea8 100644 --- a/desktop/src/app/AppShell.tsx +++ b/desktop/src/app/AppShell.tsx @@ -405,6 +405,7 @@ export function AppShell() { feedItemState.unreadSet, threadActivityFeedItems, getThreadReadAt, + getMessageReadAt, ); const dueReminderBadge = useDueReminderBadgeCount( diff --git a/desktop/src/features/channels/readState/readStateFormat.test.mjs b/desktop/src/features/channels/readState/readStateFormat.test.mjs index 248692a91..417e40b02 100644 --- a/desktop/src/features/channels/readState/readStateFormat.test.mjs +++ b/desktop/src/features/channels/readState/readStateFormat.test.mjs @@ -1,18 +1,37 @@ import assert from "node:assert/strict"; import test from "node:test"; -import { isMsgContextKey, msgContextKey } from "./readStateFormat.ts"; +import { + isMsgContextKey, + isThreadContextKey, + maxReadAt, + msgContextKey, +} from "./readStateFormat.ts"; + +const EVENT_ID = "a".repeat(64); + +test("maxReadAt_usesNewestNonNullMarker", () => { + assert.equal(maxReadAt(null, 10, 5, null, 30), 30); +}); + +test("maxReadAt_allNull_returnsNull", () => { + assert.equal(maxReadAt(null, null), null); +}); test("msgContextKey_prefixesId_returnsMsgKey", () => { - assert.equal(msgContextKey("abc123"), "msg:abc123"); + assert.equal(msgContextKey(EVENT_ID), `msg:${EVENT_ID}`); }); test("isMsgContextKey_wellFormedKey_returnsTrue", () => { - assert.equal(isMsgContextKey("msg:abc123"), true); + assert.equal(isMsgContextKey(`msg:${EVENT_ID}`), true); +}); + +test("isThreadContextKey_wellFormedKey_returnsTrue", () => { + assert.equal(isThreadContextKey(`thread:${EVENT_ID}`), true); }); test("isMsgContextKey_threadKey_returnsFalse", () => { - assert.equal(isMsgContextKey(`thread:${"a".repeat(64)}`), false); + assert.equal(isMsgContextKey(`thread:${EVENT_ID}`), false); }); test("isMsgContextKey_channelKey_returnsFalse", () => { @@ -23,11 +42,19 @@ test("isMsgContextKey_emptyId_returnsFalse", () => { assert.equal(isMsgContextKey("msg:"), false); }); +test("isMsgContextKey_shortId_returnsFalse", () => { + assert.equal(isMsgContextKey("msg:abc123"), false); +}); + test("isMsgContextKey_msgPrefixWrappingThreadKey_returnsFalse", () => { // A thread key accidentally re-prefixed must not pass as a message key. - assert.equal(isMsgContextKey(`msg:thread:${"a".repeat(64)}`), false); + assert.equal(isMsgContextKey(`msg:thread:${EVENT_ID}`), false); +}); + +test("isThreadContextKey_shortId_returnsFalse", () => { + assert.equal(isThreadContextKey("thread:abc123"), false); }); test("msgContextKey_output_roundTripsThroughValidator", () => { - assert.equal(isMsgContextKey(msgContextKey("event-id")), true); + assert.equal(isMsgContextKey(msgContextKey(EVENT_ID)), true); }); diff --git a/desktop/src/features/channels/readState/readStateFormat.ts b/desktop/src/features/channels/readState/readStateFormat.ts index 4a37d1833..74ba002c9 100644 --- a/desktop/src/features/channels/readState/readStateFormat.ts +++ b/desktop/src/features/channels/readState/readStateFormat.ts @@ -18,17 +18,30 @@ export const MAX_CONTEXTS = 10_000; export const MSG_PREFIX = "msg:"; export const THREAD_PREFIX = "thread:"; +const EVENT_ID_PATTERN = /^[0-9a-f]{64}$/; + +export function maxReadAt(...markers: Array): number | null { + return markers.reduce((latest, marker) => { + if (marker === null) return latest; + if (latest === null || marker > latest) return marker; + return latest; + }, null); +} + export function msgContextKey(messageId: string): string { return `${MSG_PREFIX}${messageId}`; } -// A well-formed per-message context key: the msg: prefix with a non-empty id -// that does NOT itself start with thread: (guards against a thread key being -// mistaken for, or double-prefixed into, a message key). +// Spec-conformance helpers for well-known interoperable context keys. Runtime +// folding/eviction remains prefix-based so opaque client-local keys still work. +export function isThreadContextKey(value: string): value is `thread:${string}` { + if (!value.startsWith(THREAD_PREFIX)) return false; + return EVENT_ID_PATTERN.test(value.slice(THREAD_PREFIX.length)); +} + export function isMsgContextKey(value: string): value is `msg:${string}` { if (!value.startsWith(MSG_PREFIX)) return false; - const id = value.slice(MSG_PREFIX.length); - return id.length > 0 && !id.startsWith(THREAD_PREFIX); + return EVENT_ID_PATTERN.test(value.slice(MSG_PREFIX.length)); } export function localReadStateKey(pubkey: string): string { diff --git a/desktop/src/features/channels/readState/readStateManager.ts b/desktop/src/features/channels/readState/readStateManager.ts index ce93b0b3d..aa613c82a 100644 --- a/desktop/src/features/channels/readState/readStateManager.ts +++ b/desktop/src/features/channels/readState/readStateManager.ts @@ -10,6 +10,8 @@ import { READ_STATE_D_TAG_PREFIX, READ_STATE_FETCH_LIMIT, READ_STATE_HORIZON_SECONDS, + MSG_PREFIX, + THREAD_PREFIX, isValidBlob, isValidReadStateDTag, sanitizeContexts, @@ -593,23 +595,23 @@ export class ReadStateManager { contexts[ctx] = ts; } - // Evict oldest thread:* entries when approaching the MAX_CONTEXTS cap - // (10,000). Channel keys are never evicted — only thread read-state keys - // are eligible. This prevents silent blob rejection by isValidBlob(). + // Evict oldest per-thread/per-message entries when approaching the + // MAX_CONTEXTS cap (10,000). Channel keys are never evicted. This prevents + // silent blob rejection by isValidBlob(). const EVICTION_THRESHOLD = 8_000; const contextCount = Object.keys(contexts).length; if (contextCount > EVICTION_THRESHOLD) { - const threadEntries: [string, number][] = []; + const detailEntries: [string, number][] = []; for (const [key, ts] of Object.entries(contexts)) { - if (key.startsWith("thread:")) { - threadEntries.push([key, ts]); + if (key.startsWith(THREAD_PREFIX) || key.startsWith(MSG_PREFIX)) { + detailEntries.push([key, ts]); } } // Sort oldest-first (lowest timestamp = oldest) - threadEntries.sort((a, b) => a[1] - b[1]); + detailEntries.sort((a, b) => a[1] - b[1]); const toEvict = contextCount - EVICTION_THRESHOLD; - for (let i = 0; i < Math.min(toEvict, threadEntries.length); i++) { - delete contexts[threadEntries[i][0]]; + for (let i = 0; i < Math.min(toEvict, detailEntries.length); i++) { + delete contexts[detailEntries[i][0]]; } } diff --git a/desktop/src/features/channels/unreadChannelCounts.ts b/desktop/src/features/channels/unreadChannelCounts.ts index 2a4239cfe..cb33c6297 100644 --- a/desktop/src/features/channels/unreadChannelCounts.ts +++ b/desktop/src/features/channels/unreadChannelCounts.ts @@ -1,3 +1,5 @@ +import { maxReadAt } from "@/features/channels/readState/readStateFormat"; + export type ObservedUnreadEvent = { id: string; createdAt: number; @@ -122,13 +124,13 @@ export function observedUnreadEventReadAt( event: ObservedUnreadEvent, channelReadAt: number | null, getThreadOwnMarker: (rootId: string) => number | null, + getMessageOwnMarker: (messageId: string) => number | null = () => null, ): number | null { - if (event.rootId === null) return channelReadAt; + const markers = [channelReadAt, getMessageOwnMarker(event.id)]; - const threadReadAt = getThreadOwnMarker(event.rootId); - if (threadReadAt === null) return channelReadAt; - if (channelReadAt === null || threadReadAt > channelReadAt) { - return threadReadAt; + if (event.rootId !== null) { + markers.push(getThreadOwnMarker(event.rootId)); } - return channelReadAt; + + return maxReadAt(...markers); } diff --git a/desktop/src/features/channels/unreadReadMarker.test.mjs b/desktop/src/features/channels/unreadReadMarker.test.mjs index 521414e8a..266bca2df 100644 --- a/desktop/src/features/channels/unreadReadMarker.test.mjs +++ b/desktop/src/features/channels/unreadReadMarker.test.mjs @@ -118,6 +118,34 @@ test("observedUnreadEventReadAt_openedThreadReplyUsesThreadMarker", () => { assert.equal(event.createdAt > readAt, false); }); +test("observedUnreadEventReadAt_openedMessageReplyUsesMessageMarker", () => { + const event = observed("reply", 500, "root-1"); + + const readAt = observedUnreadEventReadAt( + event, + 300, + () => null, + (messageId) => (messageId === "reply" ? 500 : null), + ); + + assert.equal(readAt, 500); + assert.equal(event.createdAt > readAt, false); +}); + +test("observedUnreadEventReadAt_usesNewestAvailableMarker", () => { + const event = observed("reply", 500, "root-1"); + + assert.equal( + observedUnreadEventReadAt( + event, + 300, + () => 450, + () => 400, + ), + 450, + ); +}); + test("observedUnreadEventReadAt_topLevelUsesChannelMarker", () => { assert.equal( observedUnreadEventReadAt(observed("top", 500), 300, () => 900), @@ -156,12 +184,13 @@ function observed( }; } -function readAtFor(channelMarker, threadMarkers) { +function readAtFor(channelMarker, threadMarkers, messageMarkers = new Map()) { return (event) => observedUnreadEventReadAt( event, channelMarker, (rootId) => threadMarkers.get(rootId) ?? null, + (messageId) => messageMarkers.get(messageId) ?? null, ); } @@ -211,6 +240,32 @@ test("sidebarPipeline_openThreadClearsOnlyUnreadThreadContribution", () => { ); }); +test("sidebarPipeline_openedReplyMessageMarkerClearsDelayedReplay", () => { + const channelId = "chan"; + const rootId = "root-1"; + const reply = observed("reply", 500, rootId); + const observedByChannel = new Map(); + recordObservedUnreadEvent(observedByChannel, channelId, reply, 20); + + const beforeOpenReadAt = readAtFor(300, new Map(), new Map()); + assert.equal( + countUnreadObservedEvents( + observedByChannel.get(channelId), + beforeOpenReadAt, + ), + 1, + ); + + const afterOpenReadAt = readAtFor(300, new Map(), new Map([["reply", 500]])); + assert.equal( + countUnreadObservedEvents( + observedByChannel.get(channelId), + afterOpenReadAt, + ), + 0, + ); +}); + test("latestObservedEvent_latestThreadReadDoesNotImplyChannelClear", () => { const events = new Map([ ["older", observed("older", 400, "root-older")], diff --git a/desktop/src/features/channels/useUnreadChannels.ts b/desktop/src/features/channels/useUnreadChannels.ts index 8cf6808d9..f65f4bd82 100644 --- a/desktop/src/features/channels/useUnreadChannels.ts +++ b/desktop/src/features/channels/useUnreadChannels.ts @@ -826,8 +826,11 @@ export function useUnreadChannels( ); const channelReadAt = getEffectiveTimestamp(channel.id); const readAtForObservedEvent = (event: ObservedUnreadEvent) => - observedUnreadEventReadAt(event, channelReadAt, (rootId) => - getOwnTimestamp(`thread:${rootId}`), + observedUnreadEventReadAt( + event, + channelReadAt, + (rootId) => getOwnTimestamp(`thread:${rootId}`), + (messageId) => getOwnTimestamp(`msg:${messageId}`), ); const unreadCount = countUnreadObservedEvents( diff --git a/desktop/src/features/home/ui/HomeView.tsx b/desktop/src/features/home/ui/HomeView.tsx index d9a735be9..7d8c53395 100644 --- a/desktop/src/features/home/ui/HomeView.tsx +++ b/desktop/src/features/home/ui/HomeView.tsx @@ -125,6 +125,7 @@ export function HomeView({ const { getChannelReadAt, getThreadReadAt, + getMessageReadAt, feedItemState, markChannelRead, markThreadRead, @@ -202,6 +203,7 @@ export function HomeView({ items: inboxItems, getChannelReadAt, getThreadReadAt, + getMessageReadAt, readStateVersion, localDoneSet: doneSet, localUnreadSet: unreadSet, diff --git a/desktop/src/features/home/useHomeInboxReadState.test.mjs b/desktop/src/features/home/useHomeInboxReadState.test.mjs index 426188c0a..a6f4c90bc 100644 --- a/desktop/src/features/home/useHomeInboxReadState.test.mjs +++ b/desktop/src/features/home/useHomeInboxReadState.test.mjs @@ -5,6 +5,7 @@ import { getGroupedChannelReadTimestamp, getGroupedInboxItemIds, hasGroupedUnreadOverride, + resolveInboxItemReadAt, } from "./useHomeInboxReadState.ts"; const CHANNEL_ID = "9a1657ac-f7aa-5db0-b632-d8bbeb6dfb50"; @@ -123,3 +124,67 @@ test("grouped unread override matches any item represented by the row", () => { false, ); }); + +test("thread inbox row without a marker ignores local done fallback", () => { + const replyItem = feedItem({ + id: "reply-event", + createdAt: 200, + tags: [ + ["h", CHANNEL_ID], + ["e", "root-event", "", "root"], + ["e", "parent-event", "", "reply"], + ], + }); + + assert.equal( + resolveInboxItemReadAt(inboxItem([replyItem]), { + getChannelReadAt: () => 100, + getThreadReadAt: () => null, + getMessageReadAt: () => null, + }), + null, + ); +}); + +test("thread inbox row read state includes per-message marker", () => { + const replyItem = feedItem({ + id: "reply-event", + createdAt: 200, + tags: [ + ["h", CHANNEL_ID], + ["e", "root-event", "", "root"], + ["e", "parent-event", "", "reply"], + ], + }); + + assert.equal( + resolveInboxItemReadAt(inboxItem([replyItem]), { + getChannelReadAt: () => 100, + getThreadReadAt: () => null, + getMessageReadAt: (messageId) => + messageId === "reply-event" ? 200 : null, + }), + 200, + ); +}); + +test("thread inbox row read state uses newest thread or message marker", () => { + const replyItem = feedItem({ + id: "reply-event", + createdAt: 200, + tags: [ + ["h", CHANNEL_ID], + ["e", "root-event", "", "root"], + ["e", "parent-event", "", "reply"], + ], + }); + + assert.equal( + resolveInboxItemReadAt(inboxItem([replyItem]), { + getChannelReadAt: () => 100, + getThreadReadAt: () => 250, + getMessageReadAt: () => 200, + }), + 250, + ); +}); diff --git a/desktop/src/features/home/useHomeInboxReadState.ts b/desktop/src/features/home/useHomeInboxReadState.ts index b37cc3138..167c87337 100644 --- a/desktop/src/features/home/useHomeInboxReadState.ts +++ b/desktop/src/features/home/useHomeInboxReadState.ts @@ -1,6 +1,7 @@ import * as React from "react"; import type { InboxItem } from "@/features/home/lib/inbox"; +import { maxReadAt } from "@/features/channels/readState/readStateFormat"; import { getThreadReference, isThreadReply, @@ -13,6 +14,8 @@ type UseHomeInboxReadStateOptions = { getChannelReadAt: (channelId: string) => number | null; /** NIP-RS read marker resolver for thread-backed items (unix seconds, or null when unknown). */ getThreadReadAt: (rootId: string, channelId?: string | null) => number | null; + /** NIP-RS read marker resolver for per-message items (unix seconds, or null when unknown). */ + getMessageReadAt?: (messageId: string) => number | null; /** Invalidation signal for the channel-marker projection. */ readStateVersion: number; /** Local fallback "done" set (used only for items with no channelId). */ @@ -78,6 +81,29 @@ export function hasGroupedUnreadOverride( return getGroupedInboxItemIds(item).some((id) => localUnreadSet.has(id)); } +export function resolveInboxItemReadAt( + item: InboxItem, + options: { + getChannelReadAt: (channelId: string) => number | null; + getMessageReadAt?: (messageId: string) => number | null; + getThreadReadAt: ( + rootId: string, + channelId?: string | null, + ) => number | null; + }, +): number | null { + const channelId = item.item.channelId; + const threadRootId = getInboxThreadRootId(item); + if (threadRootId) { + return maxReadAt( + options.getThreadReadAt(threadRootId, channelId), + options.getMessageReadAt?.(item.item.id) ?? null, + ); + } + + return channelId ? options.getChannelReadAt(channelId) : null; +} + /** * Projects Home inbox read-state from the shared NIP-RS read marker, with * the local `useFeedItemState` done-set as a fallback for items that don't @@ -92,6 +118,7 @@ export function useHomeInboxReadState({ items, getChannelReadAt, getThreadReadAt, + getMessageReadAt, readStateVersion, localDoneSet, localUnreadSet = EMPTY_ITEM_SET, @@ -115,23 +142,23 @@ export function useHomeInboxReadState({ continue; } - const channelId = item.item.channelId; const threadRootId = getInboxThreadRootId(item); - if (threadRootId) { - const readAt = getThreadReadAt(threadRootId, channelId); - if (readAt !== null && item.latestActivityAt <= readAt) { + const readAt = resolveInboxItemReadAt(item, { + getChannelReadAt, + getMessageReadAt, + getThreadReadAt, + }); + if (readAt !== null) { + if (item.latestActivityAt <= readAt) { result.add(item.id); } continue; } - if (channelId) { - const readAt = getChannelReadAt(channelId); - if (readAt !== null && item.latestActivityAt <= readAt) { - result.add(item.id); - } + if (threadRootId !== null || item.item.channelId) { continue; } + if (localDoneSet.has(item.id)) { result.add(item.id); } @@ -140,6 +167,7 @@ export function useHomeInboxReadState({ }, [ getChannelReadAt, getThreadReadAt, + getMessageReadAt, items, localDoneSet, localUnreadSet, diff --git a/desktop/src/features/notifications/hooks.test.mjs b/desktop/src/features/notifications/hooks.test.mjs index 2fa571122..e5b90f3ac 100644 --- a/desktop/src/features/notifications/hooks.test.mjs +++ b/desktop/src/features/notifications/hooks.test.mjs @@ -3,6 +3,8 @@ import test from "node:test"; import { buildHomeBadgeFeedItems, + isHomeBadgeFeedItemUnread, + resolveHomeBadgeFeedItemReadAt, shouldCountTowardHomeBadgeSubtotal, } from "./lib/homeBadge.ts"; @@ -110,6 +112,50 @@ test("home badge subtotal still counts non-DM thread-only rows", () => { ); }); +test("home badge thread reply read state includes per-message markers", () => { + const item = { + ...feedItem("reply-1"), + channelId: "stream-channel", + createdAt: 500, + tags: ROOT_TAGS, + }; + + const readAt = resolveHomeBadgeFeedItemReadAt(item, { + getChannelReadAt: () => 300, + getThreadReadAt: () => null, + getMessageReadAt: (messageId) => (messageId === "reply-1" ? 500 : null), + }); + + assert.equal(readAt, 500); + assert.equal( + isHomeBadgeFeedItemUnread(item, { + getChannelReadAt: () => 300, + getThreadReadAt: () => null, + getMessageReadAt: () => 500, + seenFeedIdSet: new Set(), + }), + false, + ); +}); + +test("home badge thread reply read state uses newest channel thread or message marker", () => { + const item = { + ...feedItem("reply-1"), + channelId: "stream-channel", + createdAt: 500, + tags: ROOT_TAGS, + }; + + assert.equal( + resolveHomeBadgeFeedItemReadAt(item, { + getChannelReadAt: () => 300, + getThreadReadAt: () => 550, + getMessageReadAt: () => 400, + }), + 550, + ); +}); + test("home badge subtotal counts locally unread rows before channel exclusion", () => { const highPriorityChannelIds = new Set(["stream-channel"]); diff --git a/desktop/src/features/notifications/hooks.ts b/desktop/src/features/notifications/hooks.ts index 17a958c2b..e039d0eae 100644 --- a/desktop/src/features/notifications/hooks.ts +++ b/desktop/src/features/notifications/hooks.ts @@ -1,10 +1,6 @@ import * as React from "react"; import { useHomeFeedQuery } from "@/features/home/hooks"; -import { - getThreadReference, - isThreadReply, -} from "@/features/messages/lib/threading"; import { useUsersBatchQuery } from "@/features/profile/hooks"; import type { UserProfileLookup } from "@/features/profile/lib/identity"; import type { FeedItem, HomeFeedResponse } from "@/shared/api/types"; @@ -30,6 +26,7 @@ import { } from "./use-feed-desktop-notifications"; import { buildHomeBadgeFeedItems, + isHomeBadgeFeedItemUnread, shouldCountTowardHomeBadgeSubtotal, } from "./lib/homeBadge"; @@ -374,6 +371,11 @@ export function useHomeFeedNotificationState( rootId: string, channelId?: string | null, ) => number | null = () => null, + // Per-message read marker lookup, shared with channel thread badges. When + // provided, a thread activity row is treated as read if the specific reply + // has been revealed in-channel, even if the aggregate `thread:` marker + // has not been advanced by opening Home. + getMessageReadAt: (messageId: string) => number | null = () => null, ) { useFeedDesktopNotifications( feed, @@ -442,27 +444,13 @@ export function useHomeFeedNotificationState( ) { continue; } - const threadRootId = isThreadReply(item.tags) - ? getThreadReference(item.tags).rootId - : null; - let isUnread: boolean; - if (isLocallyUnread) { - isUnread = true; - } else if (threadRootId) { - const readAt = getThreadReadAt(threadRootId, item.channelId); - isUnread = - readAt !== null - ? item.createdAt > readAt - : !seenFeedIdSet.has(item.id); - } else if (item.channelId) { - const readAt = getChannelReadAt(item.channelId); - isUnread = - readAt !== null - ? item.createdAt > readAt - : !seenFeedIdSet.has(item.id); - } else { - isUnread = !seenFeedIdSet.has(item.id); - } + const isUnread = isHomeBadgeFeedItemUnread(item, { + getChannelReadAt, + getMessageReadAt, + getThreadReadAt, + isLocallyUnread, + seenFeedIdSet, + }); if (!isUnread) continue; total++; if ( @@ -482,6 +470,7 @@ export function useHomeFeedNotificationState( }, [ currentFeedItems, getChannelReadAt, + getMessageReadAt, getThreadReadAt, highPriorityChannelIds, isHomeActive, diff --git a/desktop/src/features/notifications/lib/homeBadge.ts b/desktop/src/features/notifications/lib/homeBadge.ts index 3355ec749..deac9b73a 100644 --- a/desktop/src/features/notifications/lib/homeBadge.ts +++ b/desktop/src/features/notifications/lib/homeBadge.ts @@ -1,7 +1,9 @@ import type { FeedItem, HomeFeedResponse } from "@/shared/api/types"; +import { maxReadAt } from "@/features/channels/readState/readStateFormat"; import { getThreadReference, isBroadcastReply, + isThreadReply, } from "@/features/messages/lib/threading"; function dedupeFeedItemsById(items: readonly FeedItem[]): FeedItem[] { @@ -56,3 +58,60 @@ export function shouldCountTowardHomeBadgeSubtotal( threadRef.parentId !== null && !isBroadcastReply(item.tags); return isThreadedReply && item.channelType !== "dm"; } + +type FeedItemReadState = Pick< + FeedItem, + "channelId" | "createdAt" | "id" | "tags" +>; + +export function feedItemThreadRootId(item: Pick) { + return isThreadReply(item.tags) ? getThreadReference(item.tags).rootId : null; +} + +export function isHomeBadgeFeedItemUnread( + item: FeedItemReadState, + options: { + getChannelReadAt: (channelId: string) => number | null; + getMessageReadAt?: (messageId: string) => number | null; + getThreadReadAt: ( + rootId: string, + channelId?: string | null, + ) => number | null; + isLocallyUnread?: boolean; + seenFeedIdSet: ReadonlySet; + }, +): boolean { + if (options.isLocallyUnread) { + return true; + } + + const readAt = resolveHomeBadgeFeedItemReadAt(item, options); + return readAt !== null + ? item.createdAt > readAt + : !options.seenFeedIdSet.has(item.id); +} + +export function resolveHomeBadgeFeedItemReadAt( + item: FeedItemReadState, + options: { + getChannelReadAt: (channelId: string) => number | null; + getMessageReadAt?: (messageId: string) => number | null; + getThreadReadAt: ( + rootId: string, + channelId?: string | null, + ) => number | null; + }, +): number | null { + const threadRootId = feedItemThreadRootId(item); + const markers: Array = []; + + if (item.channelId && !threadRootId) { + markers.push(options.getChannelReadAt(item.channelId)); + } + if (threadRootId) { + markers.push(options.getThreadReadAt(threadRootId, item.channelId)); + markers.push(options.getMessageReadAt?.(item.id) ?? null); + } + + return maxReadAt(...markers); +} diff --git a/docs/nips/NIP-RS.md b/docs/nips/NIP-RS.md index 9dbf714eb..1ca30ea08 100644 --- a/docs/nips/NIP-RS.md +++ b/docs/nips/NIP-RS.md @@ -25,7 +25,7 @@ This NIP defines a minimal, privacy-preserving protocol for propagating read sta ## Non-Goals This NIP does not define a durable log of all read messages — blobs are best-effort recent activity hints bounded by a time horizon. -This NIP does not define cross-client interoperability on context ID format — context identifiers are opaque by default and meaningful only within a single client family, except for OPTIONAL well-known schemes defined in this NIP (currently only `thread:`, defined under Thread Read Contexts), which are provided for cross-client thread-read interoperability. +This NIP does not define cross-client interoperability on context ID format — context identifiers are opaque by default and meaningful only within a single client family, except for OPTIONAL well-known schemes defined in this NIP (`thread:` and `msg:`, defined under Read Context Schemes), which are provided for cross-client thread/message-read interoperability. This NIP does not define mark-as-unread — the merge rule is monotonic by design. This NIP does not guarantee ordering of read events across devices. This NIP does not require relay-side logic. @@ -112,31 +112,42 @@ After decryption, clients MUST apply the following validation rules: Context identifier format is not prescribed by this NIP. Clients choose identifiers appropriate to their context type (e.g., a NIP-28 channel event ID, a NIP-29 group address, a pubkey for DMs). Interoperability between different client implementations on context ID conventions is outside the scope of this NIP. -#### Thread Read Contexts (Optional) +#### Read Context Schemes (Optional) -This subsection defines an OPTIONAL well-known context scheme for tracking read -state of threads (reply chains) independently from the channel they belong to. -It is a pure interpretation layer over the flat `contexts` map — it introduces -no new fields, no nesting, and no change to the merge rule, event structure, -validation, or fetching. The schema version `v` remains `1`. Clients that do -not implement this subsection remain fully interoperable (see Backwards -Compatibility below). +This subsection defines OPTIONAL well-known context schemes for tracking read +state below a channel: thread-level read state for reply chains and per-message +read state for individual events. These schemes are pure interpretation layers +over the flat `contexts` map — they introduce no new fields, no nesting, and no +change to the merge rule, event structure, validation, or fetching. The schema +version `v` remains `1`. Clients that do not implement this subsection remain +fully interoperable (see Backwards Compatibility below). -A client implementing this scheme MUST use the context key `thread:` -for a thread, where `` is the 64-character lowercase hex event ID -of the thread's root event. A bare channel identifier (e.g., the NIP-28 channel -event ID) remains the channel context, exactly as before — this is grandfathered -existing behavior and is unchanged. +A client implementing thread read contexts MUST use the context key +`thread:` for a thread, where `` is the +64-character lowercase hex event ID of the thread's root event. + +A client implementing per-message read contexts MUST use the context key +`msg:` for a message, where `` is the 64-character lowercase +hex event ID of that message. Per-message contexts are useful for clients that +reveal only part of a thread (for example, a thread panel with collapsed nested +branches): a client can mark the revealed reply events read without marking the +whole thread read. + +A bare channel identifier (e.g., the NIP-28 channel event ID) remains the channel +context, exactly as before — this is grandfathered existing behavior and is +unchanged. Keys beginning with `thread:` whose remainder does not match `^[0-9a-f]{64}$` -MUST be treated as ordinary opaque contexts, not as thread contexts. This -protects an existing client family that may already use a `thread:`-prefixed -convention from being misinterpreted under this scheme. +MUST be treated as ordinary opaque contexts, not as thread contexts. Keys +beginning with `msg:` whose remainder does not match `^[0-9a-f]{64}$` MUST be +treated as ordinary opaque contexts, not as per-message contexts. This protects +an existing client family that may already use one of these prefixes from being +misinterpreted under this scheme. -The relationship between a thread and its parent channel is DERIVED from the -Nostr event graph at evaluation time (the root event's channel reference, e.g. -its `h` tag) and MUST NOT be serialized into the blob. The blob remains a flat -`{: }` map. +The relationship between a thread or message and its parent channel is DERIVED +from the Nostr event graph at evaluation time (the root/message event's channel +reference, e.g. its `h` tag) and MUST NOT be serialized into the blob. The blob +remains a flat `{: }` map. ##### Hierarchical Frontier Rule @@ -154,46 +165,65 @@ value. For a thread, the parent is its channel: effective(thread:) = max(merged[thread:], merged[]) ``` -A thread is unread iff `latestReplyAt > effective(thread:)`, where -`latestReplyAt` is the `created_at` of the thread's most recent reply. Because -this rule is a `max()` over the same grow-only registers defined in the Merge -Rule, it remains a monotone state-based CvRDT — no change to the merge rule is -required. Marking a channel read clears unread state on any thread whose most -recent reply predates the channel frontier, since each thread's effective -frontier inherits the channel term; threads with replies newer than the channel -frontier remain unread until the thread itself is read. +For a per-message context, the parent is also its channel (not its thread or +parent message): -If the thread root event (and therefore its parent channel) cannot be resolved -from the event graph, `effective(thread:)` degrades to -`merged[thread:]` alone. +``` +effective(msg:) = max(merged[msg:], merged[]) +``` + +When a surface evaluates a reply inside a known thread, it MAY additionally fold +in the thread frontier: + +``` +effective(reply) = max(effective(msg:), effective(thread:)) +``` + +A thread is unread iff at least one reply is unread. A reply is unread iff +`reply.created_at > effective(reply)` for clients that implement per-message +contexts; clients that only implement thread contexts MAY instead use +`latestReplyAt > effective(thread:)`. Because both rules are `max()` over +the same grow-only registers defined in the Merge Rule, they remain monotone +state-based CvRDT interpretations — no change to the merge rule is required. +Marking a channel read clears unread state on any thread/message whose relevant +event predates the channel frontier, since each child context inherits the +channel term; replies newer than the channel frontier remain unread until their +own message marker or thread marker is advanced. + +If the thread root or message event (and therefore its parent channel) cannot be +resolved from the event graph, `effective(thread:)` or +`effective(msg:)` degrades to its own merged value alone. ##### Write Discipline -Marking a thread read MUST advance only its own `thread:` context. It MUST -NOT advance the parent channel context. Otherwise, reading a single thread would -silently mark later top-level channel messages as read. Marking a channel read -advances only the channel context (which the hierarchical rule then propagates -to threads at read time). The channel context SHOULD advance to the maximum -`created_at` across the channel's top-level messages only, NOT including thread -replies. This keeps a thread unread when its `latestReplyAt` exceeds the newest -top-level message: opening a channel clears the channel timeline but leaves its -threads' unread state intact until each thread is read. +Marking a thread read MUST advance only its own `thread:` context. +Marking an individual message read MUST advance only its own `msg:` +context. Neither operation may advance the parent channel context. Otherwise, +reading a single thread or reply would silently mark later top-level channel +messages as read. Marking a channel read advances only the channel context +(which the hierarchical rule then propagates to child contexts at read time). +The channel context SHOULD advance to the maximum `created_at` across the +channel's top-level messages only, NOT including thread replies. This keeps a +thread unread when its replies exceed the newest top-level message: opening a +channel clears the channel timeline but leaves its threads/replies unread until +each thread or message is read. ##### Eviction -A `thread:` entry whose value is `<= effective(parent)` is semantically -inert: the parent (channel) frontier already covers it, so its presence or -absence does not change the result of `effective(thread:)`. Clients MAY -drop such dominated entries before publishing to bound blob size, consistent -with the Debounce and Pruning section. +A `thread:` or `msg:` entry whose value is +`<= effective(parent)` is semantically inert: the parent (channel) frontier +already covers it, so its presence or absence does not change the result of the +child context's effective frontier. Clients MAY drop such dominated entries +before publishing to bound blob size, consistent with the Debounce and Pruning +section. This eviction is bounded best-effort, NOT a guaranteed garbage-collection or per-key tombstone mechanism. Because the merge rule re-merges any context present in another instance's blob (see Merge Rule and Live Subscription and -Convergence), a dropped `thread:` key MAY be re-added by a peer instance -that still carries it. A dropped key stays gone only once it is dominated on -every instance or has aged past the time horizon everywhere. Clients SHOULD -treat thread-context eviction as a companion to the existing time-horizon +Convergence), a dropped `thread:` or `msg:` key MAY be +re-added by a peer instance that still carries it. A dropped key stays gone only +once it is dominated on every instance or has aged past the time horizon +everywhere. Clients SHOULD treat child-context eviction as a companion to the existing time-horizon pruning, not as a standalone guarantee that the context count or blob size will shrink immediately. @@ -208,17 +238,18 @@ effect. ##### Backwards Compatibility -A client that does not implement this scheme treats a `thread:` key as an -ordinary opaque context. It carries the key through the merge unchanged (already -required by the Merge Rule) and simply computes no thread-level unread state. -There is no validation change and no interop break: an unaware client and an -aware client can share a blob and both produce correct results for the contexts -they understand. +A client that does not implement this scheme treats `thread:` and +`msg:` keys as ordinary opaque contexts. It carries the keys through +the merge unchanged (already required by the Merge Rule) and simply computes no +thread/message-level unread state. There is no validation change and no interop +break: an unaware client and an aware client can share a blob and both produce +correct results for the contexts they understand. ##### Example -Two blobs merge to the following effective state for a thread `X` and its parent -channel: +Two blobs merge to the following effective state for a symbolically named thread +`X` and its parent channel (real `thread:` keys use 64-character lowercase hex +event IDs): ```json { @@ -238,7 +269,8 @@ A thread reply with `created_at = 140` is `<= 150`, so it reads as **read** (the channel frontier already covers it). A reply with `created_at = 160` is `> 150`, so the thread reads as **unread**. The thread's own entry (`100`) is dominated by the channel frontier (`150`) and is therefore inert — a client MAY evict it -before publishing. +before publishing. The same rule applies to `msg:` entries for +individual replies. #### Timestamp Accuracy From 45067ec13507c406ee41d3f184fc96c988b1348b Mon Sep 17 00:00:00 2001 From: Wes Date: Wed, 24 Jun 2026 09:47:12 -0700 Subject: [PATCH 03/60] fix(desktop): render autolinked message links as chips (#1241) Signed-off-by: Wes Co-authored-by: Pinky <44b8e82baa6e0e254e0208d68f335c283c94e7b78dd1fa10d5a49d3f13dd0435@sprout-oss.stage.blox.sqprod.co> --- .../messages/lib/messageLink.test.mjs | 29 +++++ .../src/features/messages/lib/messageLink.ts | 31 +++++ desktop/src/shared/ui/markdown.test.mjs | 5 + desktop/src/shared/ui/markdown.tsx | 109 ++++++++++++------ 4 files changed, 140 insertions(+), 34 deletions(-) diff --git a/desktop/src/features/messages/lib/messageLink.test.mjs b/desktop/src/features/messages/lib/messageLink.test.mjs index 410cafb44..68ccd385e 100644 --- a/desktop/src/features/messages/lib/messageLink.test.mjs +++ b/desktop/src/features/messages/lib/messageLink.test.mjs @@ -5,6 +5,7 @@ import { buildMessageLink, isMessageLink, parseMessageLink, + resolveMessageLinkRenderTarget, } from "./messageLink.ts"; const CHANNEL = "f570339f-8f8a-4e08-a779-8d954aa44109"; @@ -118,3 +119,31 @@ test("isMessageLink matches buzz://message and legacy buzz://message", () => { assert.equal(isMessageLink(undefined), false); assert.equal(isMessageLink(""), false); }); + +test("resolveMessageLinkRenderTarget distinguishes autolinks from labeled links", () => { + const href = `buzz://message?channel=${CHANNEL}&id=${MESSAGE}`; + + assert.deepEqual(resolveMessageLinkRenderTarget({ href, label: href }), { + kind: "pill", + link: { + channelId: CHANNEL, + messageId: MESSAGE, + threadRootId: null, + }, + }); + assert.deepEqual(resolveMessageLinkRenderTarget({ href, label: "message" }), { + kind: "label", + link: { + channelId: CHANNEL, + messageId: MESSAGE, + threadRootId: null, + }, + }); + assert.deepEqual( + resolveMessageLinkRenderTarget({ + href: "https://example.com", + label: href, + }), + { kind: "none" }, + ); +}); diff --git a/desktop/src/features/messages/lib/messageLink.ts b/desktop/src/features/messages/lib/messageLink.ts index b8fa89999..56f67b23a 100644 --- a/desktop/src/features/messages/lib/messageLink.ts +++ b/desktop/src/features/messages/lib/messageLink.ts @@ -102,3 +102,34 @@ export function isMessageLink(href: string | undefined | null): boolean { if (!href) return false; return href.startsWith("buzz://message?") || href === "buzz://message"; } + +type MessageLinkRenderInput = { + href: string; + label: string; +}; + +export type MessageLinkRenderTarget = + | { kind: "pill"; link: ParsedMessageLink } + | { kind: "label"; link: ParsedMessageLink } + | { kind: "none" }; + +/** + * Centralizes how markdown-rendered anchors map to message-link UI. Both + * CommonMark autolinks (``) and explicitly labeled links + * arrive as anchors; autolinks have label === href and should render as pills, + * while intentionally labeled links keep their label. + */ +export function resolveMessageLinkRenderTarget({ + href, + label, +}: MessageLinkRenderInput): MessageLinkRenderTarget { + if (!isMessageLink(href)) return { kind: "none" }; + + const parsed = parseMessageLink(href); + if (!parsed.ok) return { kind: "none" }; + + return { + kind: label === href ? "pill" : "label", + link: parsed.value, + }; +} diff --git a/desktop/src/shared/ui/markdown.test.mjs b/desktop/src/shared/ui/markdown.test.mjs index 952d10101..dfedc3360 100644 --- a/desktop/src/shared/ui/markdown.test.mjs +++ b/desktop/src/shared/ui/markdown.test.mjs @@ -471,6 +471,11 @@ test("messageLinkUrlTransform: preserves buzz://message href", () => { assert.match(html, /href="buzz:\/\/message\?channel=abc&(?:amp;)?id=xyz"/); }); +test("messageLinkUrlTransform: preserves buzz://message autolink href", () => { + const html = renderMarkdown(""); + assert.match(html, /href="buzz:\/\/message\?channel=abc&(?:amp;)?id=xyz"/); +}); + test("messageLinkUrlTransform: preserves buzz://message href with thread", () => { const html = renderMarkdown( "[link](buzz://message?channel=c1&id=m1&thread=t1)", diff --git a/desktop/src/shared/ui/markdown.tsx b/desktop/src/shared/ui/markdown.tsx index 5fea77687..df7249206 100644 --- a/desktop/src/shared/ui/markdown.tsx +++ b/desktop/src/shared/ui/markdown.tsx @@ -23,6 +23,7 @@ import { useAppNavigation } from "@/app/navigation/useAppNavigation"; import { isMessageLink, parseMessageLink, + resolveMessageLinkRenderTarget, type ParsedMessageLink, } from "@/features/messages/lib/messageLink"; import { UserProfilePopover } from "@/features/profile/ui/UserProfilePopover"; @@ -79,6 +80,14 @@ type ImetaEntry = { type ImetaLookup = Map; +type MessageLinkPillProps = { + channels: Channel[]; + href: string; + interactive: boolean; + link: ParsedMessageLink; + onOpenMessageLink: (link: ParsedMessageLink) => void; +}; + let shikiHighlighter: HighlighterGeneric | null = null; let shikiInitPromise: Promise | null = null; @@ -1252,6 +1261,46 @@ function getCodeBlockText(children: React.ReactNode) { return getReactNodeText(children).replace(/\n$/, ""); } +function MessageLinkPill({ + channels, + href, + interactive, + link, + onOpenMessageLink, +}: MessageLinkPillProps) { + const channel = channels.find((c) => c.id === link.channelId); + const channelLabel = channel?.name ?? "channel"; + const shortId = link.messageId.slice(0, 6); + const label = ( + <> + #{channelLabel} · {shortId} + + ); + + if (!interactive) { + return {label}; + } + + return ( + + ); +} + function InlineEmojiPopover({ alt, resolvedSrc, @@ -1788,10 +1837,24 @@ function createMarkdownComponents( // Intercept `buzz://message?channel=…&id=…` links so a click navigates // in-app instead of opening the URL in the OS browser. http(s) links // continue to use the existing target="_blank" behavior. - if (isMessageLink(href)) { - const parsed = parseMessageLink(href ?? ""); - if (parsed.ok) { - const target = parsed.value; + if (href) { + const messageLinkTarget = resolveMessageLinkRenderTarget({ + href, + label: getReactNodeText(children), + }); + if (messageLinkTarget.kind !== "none") { + if (messageLinkTarget.kind === "pill") { + return ( + + ); + } + return ( { event.preventDefault(); - onOpenMessageLink(target); + onOpenMessageLink(messageLinkTarget.link); }} > {children} @@ -2095,36 +2158,14 @@ function createMarkdownComponents( return {href}; } - const { channelId, messageId } = parsed.value; - const channel = channels.find((c) => c.id === channelId); - const channelLabel = channel?.name ?? "channel"; - const shortId = messageId.slice(0, 6); - - if (!interactive) { - return ( - - #{channelLabel} · {shortId} - - ); - } - return ( - + ); }, } as Components; From 2e426b2fddbbec1f1261125c81d83cd57e838fd1 Mon Sep 17 00:00:00 2001 From: Will Pfleger Date: Wed, 24 Jun 2026 13:41:19 -0400 Subject: [PATCH 04/60] fix: propagate persona harness edits to live agent instances (#1244) Signed-off-by: Will Pfleger Co-authored-by: npub1mn7jgtj4w2pd0g0zeuhxsa6jy6p0rewxz4kujt98my82ahfmp72sxjexk7 --- desktop/scripts/check-file-sizes.mjs | 24 +- .../src-tauri/src/commands/agent_models.rs | 40 ++- desktop/src-tauri/src/commands/agents.rs | 72 +++-- .../src-tauri/src/managed_agents/discovery.rs | 285 +++++++++++++++++- desktop/src-tauri/src/managed_agents/nest.rs | 1 + .../src/managed_agents/relay_mesh.rs | 1 + .../src-tauri/src/managed_agents/restore.rs | 11 +- .../src-tauri/src/managed_agents/runtime.rs | 51 +++- .../src/managed_agents/runtime/tests.rs | 1 + .../src/managed_agents/team_repair.rs | 1 + desktop/src-tauri/src/managed_agents/types.rs | 21 ++ desktop/src-tauri/src/migration.rs | 50 ++- desktop/src-tauri/src/migration_tests.rs | 49 +++ desktop/src/features/agents/channelAgents.ts | 8 + .../features/agents/ui/EditAgentDialog.tsx | 74 ++++- .../channels/ui/AddChannelBotDialog.tsx | 4 + desktop/src/shared/api/tauri.ts | 3 + desktop/src/shared/api/types.ts | 14 + 18 files changed, 652 insertions(+), 58 deletions(-) diff --git a/desktop/scripts/check-file-sizes.mjs b/desktop/scripts/check-file-sizes.mjs index 556046b1e..b6f9d30bb 100644 --- a/desktop/scripts/check-file-sizes.mjs +++ b/desktop/scripts/check-file-sizes.mjs @@ -37,15 +37,27 @@ const overrides = new Map([ // self-contained repos_dir functions and their unit tests live in repos.rs; // this is the seam that must stay in nest.rs. Approved override; still queued // to split with the rest of this list. - ["src-tauri/src/managed_agents/nest.rs", 1447], - ["src-tauri/src/managed_agents/runtime.rs", 1953], + ["src-tauri/src/managed_agents/nest.rs", 1448], + // harness-persona-sync: persona-runtime resolution threaded into the spawn + // path here. Load-bearing feature growth; queued to split in the resolver + // unify refactor followup. + ["src-tauri/src/managed_agents/runtime.rs", 1966], ["src-tauri/src/managed_agents/personas.rs", 1080], ["src-tauri/src/managed_agents/persona_card.rs", 1050], // applyWorkspace reposDir parameter plus the validateReposDir binding, - // threaded through Tauri invokes for configurable repos_dir — a 4-line - // overage from load-bearing parameter plumbing, not generic debt growth. - // Approved override; still queued to split. - ["src/shared/api/tauri.ts", 1199], + // threaded through Tauri invokes for configurable repos_dir, plus the + // harness-persona-sync `harnessOverride` create-input bit — load-bearing + // parameter plumbing, not generic debt growth. Approved override; still + // queued to split. + ["src/shared/api/tauri.ts", 1202], + // harness-persona-sync feature growth, queued to split in the resolver-unify + // refactor followup. discovery.rs is dominated by the new test module + // (the effective_agent_command / divergent / create-time override matrix); + // types.rs adds the persona/instance harness fields; migration_tests.rs adds + // the harness-sync migration coverage. Load-bearing, not generic debt. + ["src-tauri/src/managed_agents/discovery.rs", 1043], + ["src-tauri/src/managed_agents/types.rs", 1010], + ["src-tauri/src/migration_tests.rs", 1033], ["src-tauri/src/nostr_convert.rs", 1126], ["src/shared/api/relayClientSession.ts", 1022], ["src-tauri/src/migration.rs", 1295], diff --git a/desktop/src-tauri/src/commands/agent_models.rs b/desktop/src-tauri/src/commands/agent_models.rs index 8a4e8401b..395826e56 100644 --- a/desktop/src-tauri/src/commands/agent_models.rs +++ b/desktop/src-tauri/src/commands/agent_models.rs @@ -49,11 +49,21 @@ pub async fn get_agent_models( let resolved = resolve_command(&record.acp_command) .ok_or_else(|| missing_command_message(&record.acp_command, "ACP harness command"))?; - let args = normalize_agent_args(&record.agent_command, record.agent_args.clone()); + // Resolve the effective harness from the linked persona (mirrors spawn), + // so model discovery runs against the persona's current harness, not the + // frozen record snapshot. An explicit per-agent override wins. + let personas = load_personas(&app).unwrap_or_default(); + let effective_command = crate::managed_agents::effective_agent_command( + record.persona_id.as_deref(), + &personas, + record.agent_command_override.as_deref(), + ); - let resolved_agent = resolve_command(&record.agent_command) + let args = normalize_agent_args(&effective_command, record.agent_args.clone()); + + let resolved_agent = resolve_command(&effective_command) .map(|p| p.display().to_string()) - .unwrap_or_else(|| record.agent_command.clone()); + .unwrap_or_else(|| effective_command.clone()); // Same env layering as runtime spawn: persona env < agent env. // Model discovery needs the user's credentials. Fail closed on @@ -65,7 +75,6 @@ pub async fn get_agent_models( // Resolve the effective model from the linked persona so the ModelPicker // dropdown shows the current persona model as selected. - let personas = load_personas(&app).unwrap_or_default(); let (_prompt, effective_model, _provider) = resolve_effective_prompt_model_provider( record.persona_id.as_deref(), &personas, @@ -197,8 +206,18 @@ pub async fn update_managed_agent( if let Some(acp_command) = input.acp_command { record.acp_command = acp_command; } + // Harness edit: the persona's runtime is authoritative, so we persist an + // explicit `agent_command_override` ONLY when the user picks a command + // that diverges from the persona. An empty/whitespace value (the + // "Inherit from persona" sentinel) clears the pin back to `None`. A + // name-only edit (`agent_command == None`) leaves the pin intact. if let Some(agent_command) = input.agent_command { - record.agent_command = agent_command; + let personas = load_personas(&app).unwrap_or_default(); + record.agent_command_override = crate::managed_agents::divergent_agent_command_override( + record.persona_id.as_deref(), + &personas, + Some(&agent_command), + ); } if let Some(agent_args) = input.agent_args { record.agent_args = agent_args; @@ -253,10 +272,19 @@ pub async fn update_managed_agent( &relay_ws_url_with_override(&state), ); let display_name = record.name.clone(); + // Avatar fallback derives from the EFFECTIVE harness (persona-wins), + // not the frozen snapshot, so an inherited harness picks the right + // default avatar. + let personas = load_personas(&app).unwrap_or_default(); + let effective_command = crate::managed_agents::effective_agent_command( + record.persona_id.as_deref(), + &personas, + record.agent_command_override.as_deref(), + ); let avatar_url = record .avatar_url .clone() - .or_else(|| managed_agent_avatar_url(&record.agent_command)); + .or_else(|| managed_agent_avatar_url(&effective_command)); let auth_tag = record.auth_tag.clone(); Some((agent_keys, relay_url, display_name, avatar_url, auth_tag)) } else { diff --git a/desktop/src-tauri/src/commands/agents.rs b/desktop/src-tauri/src/commands/agents.rs index 5112c3ead..5ca180713 100644 --- a/desktop/src-tauri/src/commands/agents.rs +++ b/desktop/src-tauri/src/commands/agents.rs @@ -158,10 +158,9 @@ fn build_deploy_payload( // Resolve effective model/provider from the persona's structured fields. // Agent record's model takes precedence (user override via UI). + let personas = load_personas(app) + .map_err(|e| format!("failed to load personas for deploy payload resolution: {e}"))?; let (effective_model, effective_provider) = if let Some(ref pid) = record.persona_id { - let personas = load_personas(app).map_err(|e| { - format!("failed to load personas for deploy payload model resolution: {e}") - })?; let persona = personas.iter().find(|p| p.id == *pid); let model = record .model @@ -173,6 +172,17 @@ fn build_deploy_payload( (record.model.clone(), None) }; + // Resolve the effective harness (persona-wins, override-honored) so the + // remote provider runs the same harness a local spawn would — derive args + // from it rather than the frozen record snapshot. + let effective_command = crate::managed_agents::effective_agent_command( + record.persona_id.as_deref(), + &personas, + record.agent_command_override.as_deref(), + ); + let effective_args = + crate::managed_agents::normalize_agent_args(&effective_command, record.agent_args.clone()); + Ok(serde_json::json!({ "name": &record.name, // Resolve the per-agent pin against the active workspace relay here: @@ -186,8 +196,8 @@ fn build_deploy_payload( ), "private_key_nsec": &record.private_key_nsec, "auth_tag": &record.auth_tag, - "agent_command": &record.agent_command, - "agent_args": &record.agent_args, + "agent_command": &effective_command, + "agent_args": &effective_args, "system_prompt": &record.system_prompt, "model": effective_model, "provider": effective_provider, @@ -461,13 +471,31 @@ pub async fn create_managed_agent( None }; - let agent_command = input - .agent_command - .as_deref() - .map(str::trim) - .filter(|value| !value.is_empty()) - .map(str::to_string) - .unwrap_or_else(crate::managed_agents::default_agent_command); + // Load personas once for harness/pack/avatar resolution below. + let personas = load_personas(&app).unwrap_or_default(); + + // Harness resolution: the persona's runtime is authoritative. A + // persona-backed create stores an `agent_command_override` ONLY when the + // user deliberately picked a divergent runtime (`harness_override`) — + // e.g. AddChannelBotDialog's runtime selector. A divergence WITHOUT that + // flag is a missing-runtime fallback from `resolvePersonaRuntime`, not a + // pin, and must inherit so it doesn't freeze on the fallback harness once + // the persona's runtime is installed. A persona-less create always + // preserves the picked command as a real pin. + let agent_command_override = crate::managed_agents::create_time_agent_command_override( + requested_persona_id.as_deref(), + &personas, + input.agent_command.as_deref(), + input.harness_override, + ); + // The create-time snapshot used for arg/mcp/avatar derivations and + // legacy reconcile. Authoritative spawn resolution re-derives this via + // `effective_agent_command` at use-time. + let agent_command = crate::managed_agents::effective_agent_command( + requested_persona_id.as_deref(), + &personas, + agent_command_override.as_deref(), + ); let agent_args = normalize_agent_args( &agent_command, input @@ -496,7 +524,6 @@ pub async fn create_managed_agent( // matches on this internal name, NOT display_name. let pack_metadata: Option<(std::path::PathBuf, String)> = requested_persona_id.as_deref().and_then(|pid| { - let personas = load_personas(&app).ok()?; let persona = personas.iter().find(|p| p.id == pid)?; let team_id = persona.source_team.as_deref()?; let slug = persona.source_team_persona_slug.as_deref()?; @@ -512,11 +539,11 @@ pub async fn create_managed_agent( // fallback. Storing it lets reconciliation compare against what was // actually published instead of re-deriving it. let persona_avatar_url = requested_persona_id.as_ref().and_then(|persona_id| { - load_personas(&app) - .ok()? - .into_iter() + personas + .iter() .find(|persona| persona.id == *persona_id)? .avatar_url + .clone() }); let resolved_avatar_url = resolve_created_avatar_url( input.avatar_url.as_deref(), @@ -540,6 +567,7 @@ pub async fn create_managed_agent( .unwrap_or(DEFAULT_ACP_COMMAND) .to_string(), agent_command, + agent_command_override, agent_args, mcp_command, turn_timeout_seconds: input @@ -797,6 +825,16 @@ pub async fn start_managed_agent( let record = find_managed_agent_mut(&mut records, &pubkey)?; + // Resolve the effective harness for the avatar-fallback derivation in + // profile reconcile (the create-time snapshot may be empty or stale for + // a persona-inherited harness). + let reconcile_personas = load_personas(&app).unwrap_or_default(); + let reconcile_effective_command = crate::managed_agents::effective_agent_command( + record.persona_id.as_deref(), + &reconcile_personas, + record.agent_command_override.as_deref(), + ); + let reconcile = ProfileReconcileData { private_key_nsec: record.private_key_nsec.clone(), name: record.name.clone(), @@ -804,7 +842,7 @@ pub async fn start_managed_agent( avatar_url: record.avatar_url.clone(), auth_tag: record.auth_tag.clone(), pubkey: record.pubkey.clone(), - agent_command: record.agent_command.clone(), + agent_command: reconcile_effective_command, persona_id: record.persona_id.clone(), }; diff --git a/desktop/src-tauri/src/managed_agents/discovery.rs b/desktop/src-tauri/src/managed_agents/discovery.rs index 21ca25d58..2e3518b50 100644 --- a/desktop/src-tauri/src/managed_agents/discovery.rs +++ b/desktop/src-tauri/src/managed_agents/discovery.rs @@ -243,6 +243,107 @@ pub fn default_agent_command() -> String { .to_string() } +/// Resolve the agent command (harness) for a spawn/deploy/summary. Mirrors the +/// model resolution in `resolve_effective_prompt_model_provider`: the linked +/// persona wins so persona harness edits propagate on the next spawn. An +/// explicit per-instance override (`agent_command_override`) takes precedence, +/// matching the opt-in `record.model` override pattern. +/// +/// Resolution order: +/// 1. explicit override (non-empty) — a deliberate per-instance pin; +/// 2. the linked persona's `runtime` id mapped to its primary command; +/// 3. `default_agent_command()` — no persona/runtime, or persona deleted. +pub fn effective_agent_command( + persona_id: Option<&str>, + personas: &[crate::managed_agents::types::PersonaRecord], + agent_command_override: Option<&str>, +) -> String { + if let Some(pin) = agent_command_override + .map(str::trim) + .filter(|value| !value.is_empty()) + { + return pin.to_string(); + } + + persona_id + .and_then(|pid| personas.iter().find(|p| p.id == pid)) + .and_then(|persona| persona.runtime.as_deref()) + .and_then(known_acp_runtime_exact) + .and_then(|r| r.commands.first().copied()) + .map(str::to_string) + .unwrap_or_else(default_agent_command) +} + +/// Decide whether a user-picked harness command is an explicit per-instance +/// pin or merely the persona's own runtime restated. Returns the override to +/// persist: `Some(picked)` when it diverges from the persona, `None` when it +/// inherits. +/// +/// Comparison is by RUNTIME IDENTITY, not raw string: a persona on the `claude` +/// runtime resolves to `claude-agent-acp`, but a client with only the +/// `claude-code-acp` adapter installed sends that command instead. Both map to +/// the same `claude` runtime, so neither is a real divergence — string equality +/// would wrongly bake a pin. An unknown/custom command (no matching runtime) +/// only inherits when it exactly equals the persona command. +pub fn divergent_agent_command_override( + persona_id: Option<&str>, + personas: &[crate::managed_agents::types::PersonaRecord], + picked_command: Option<&str>, +) -> Option { + let picked = picked_command + .map(str::trim) + .filter(|value| !value.is_empty())?; + let persona_command = effective_agent_command(persona_id, personas, None); + let same_runtime = match ( + known_acp_runtime(picked), + known_acp_runtime(&persona_command), + ) { + (Some(a), Some(b)) => std::ptr::eq(a, b), + _ => picked == persona_command, + }; + if same_runtime { + None + } else { + Some(picked.to_string()) + } +} + +/// Decide the `agent_command_override` to persist at AGENT CREATE time. +/// +/// A persona-backed create receives its harness command from +/// `resolvePersonaRuntime` (frontend), which produces a divergent command in two +/// distinct cases that the backend MUST tell apart: +/// +/// - DELIBERATE OVERRIDE (`harness_override` true): the user explicitly picked a +/// non-persona runtime in a deploy dialog that exposes a runtime selector (e.g. +/// `AddChannelBotDialog`, "overriding persona preferences"). This is a real pin +/// and is preserved via `divergent_agent_command_override`. +/// - MISSING-RUNTIME FALLBACK (`harness_override` false): the persona's runtime +/// isn't installed locally, so `resolvePersonaRuntime` substitutes a fallback +/// default. This is NOT a pin — baking it would freeze the agent on the fallback +/// harness even after the persona's runtime is installed and the persona is +/// re-edited, the exact bug this resolver chain exists to prevent. Stores `None` +/// so the persona stays authoritative. +/// +/// `isOverridden` from `resolvePersonaRuntime` cannot distinguish these — it is +/// `true` for BOTH — so the caller must thread the explicit user-intent bit. +/// +/// Persona-less creates (`persona_id` is `None`, e.g. the standalone +/// CreateAgentDialog) have no persona to inherit, so the picked command is always a +/// real pin and is preserved via `divergent_agent_command_override` regardless of +/// `harness_override`. +pub fn create_time_agent_command_override( + persona_id: Option<&str>, + personas: &[crate::managed_agents::types::PersonaRecord], + picked_command: Option<&str>, + harness_override: bool, +) -> Option { + if persona_id.is_some() && !harness_override { + return None; + } + divergent_agent_command_override(persona_id, personas, picked_command) +} + fn default_agent_args(command: &str) -> Option> { match normalize_command_identity(command).as_str() { "goose" => Some(vec!["acp".to_string()]), @@ -577,9 +678,10 @@ mod tests { use std::path::PathBuf; use super::{ - classify_runtime, default_agent_command, find_via_login_shell, managed_agent_avatar_url, - normalize_agent_args, BUZZ_AGENT_AVATAR_URL, CLAUDE_CODE_AVATAR_URL, CODEX_AVATAR_URL, - GOOSE_AVATAR_URL, + classify_runtime, create_time_agent_command_override, default_agent_command, + divergent_agent_command_override, effective_agent_command, find_via_login_shell, + managed_agent_avatar_url, normalize_agent_args, BUZZ_AGENT_AVATAR_URL, + CLAUDE_CODE_AVATAR_URL, CODEX_AVATAR_URL, GOOSE_AVATAR_URL, }; use crate::managed_agents::AcpAvailabilityStatus; @@ -760,4 +862,181 @@ mod tests { assert_eq!(cmd.as_deref(), Some("codex-acp")); assert_eq!(path.as_deref(), Some("/opt/homebrew/bin/codex-acp")); } + + fn persona_with_runtime( + id: &str, + runtime: Option<&str>, + ) -> crate::managed_agents::PersonaRecord { + crate::managed_agents::PersonaRecord { + id: id.to_string(), + display_name: id.to_string(), + avatar_url: None, + system_prompt: String::new(), + runtime: runtime.map(str::to_string), + model: None, + provider: None, + name_pool: Vec::new(), + is_builtin: false, + is_active: true, + source_team: None, + source_team_persona_slug: None, + env_vars: std::collections::BTreeMap::new(), + created_at: "2026-06-09T00:00:00Z".to_string(), + updated_at: "2026-06-09T00:00:00Z".to_string(), + } + } + + #[test] + fn effective_agent_command_explicit_override_wins() { + // An explicit pin beats the persona's runtime. + let personas = vec![persona_with_runtime("p1", Some("claude"))]; + assert_eq!( + effective_agent_command(Some("p1"), &personas, Some("codex-acp")), + "codex-acp" + ); + } + + #[test] + fn effective_agent_command_inherits_persona_runtime() { + // No override → persona runtime id maps to its primary command. + let personas = vec![persona_with_runtime("p1", Some("claude"))]; + assert_eq!( + effective_agent_command(Some("p1"), &personas, None), + "claude-agent-acp" + ); + } + + #[test] + fn effective_agent_command_empty_override_is_inherit() { + // A blank/whitespace override is treated as "inherit", not a pin. + let personas = vec![persona_with_runtime("p1", Some("goose"))]; + assert_eq!( + effective_agent_command(Some("p1"), &personas, Some(" ")), + "goose" + ); + } + + #[test] + fn effective_agent_command_falls_back_to_default() { + // No override, no persona runtime, and a deleted persona all fall back + // to the bundled default. + let personas = vec![persona_with_runtime("p1", None)]; + assert_eq!( + effective_agent_command(Some("p1"), &personas, None), + default_agent_command() + ); + assert_eq!( + effective_agent_command(Some("gone"), &personas, None), + default_agent_command() + ); + assert_eq!( + effective_agent_command(None, &personas, None), + default_agent_command() + ); + } + + #[test] + fn divergent_override_none_when_picked_matches_persona_runtime() { + // The persona-backed create/edit flow sends the persona's resolved + // command. It must be treated as "inherit" (None), not a pin. + let personas = vec![persona_with_runtime("p1", Some("goose"))]; + assert_eq!( + divergent_agent_command_override(Some("p1"), &personas, Some("goose")), + None + ); + } + + #[test] + fn divergent_override_none_for_alternate_command_of_same_runtime() { + // A client with only `claude-code-acp` installed sends that command for + // a `claude` persona whose primary command is `claude-agent-acp`. Both + // map to the `claude` runtime, so it inherits — string equality would + // wrongly bake a pin (CRITICAL-3). + let personas = vec![persona_with_runtime("p1", Some("claude"))]; + assert_eq!( + divergent_agent_command_override(Some("p1"), &personas, Some("claude-code-acp")), + None + ); + } + + #[test] + fn divergent_override_some_when_picked_is_different_runtime() { + // A deliberate pin to a different runtime is preserved. + let personas = vec![persona_with_runtime("p1", Some("goose"))]; + assert_eq!( + divergent_agent_command_override(Some("p1"), &personas, Some("codex-acp")), + Some("codex-acp".to_string()) + ); + } + + #[test] + fn divergent_override_none_for_empty_or_absent_pick() { + // The "Inherit from persona" sentinel (empty) and a name-only edit + // (absent) both clear the pin. + let personas = vec![persona_with_runtime("p1", Some("goose"))]; + assert_eq!( + divergent_agent_command_override(Some("p1"), &personas, Some(" ")), + None + ); + assert_eq!( + divergent_agent_command_override(Some("p1"), &personas, None), + None + ); + } + + #[test] + fn create_time_override_none_when_persona_runtime_not_installed() { + // CRITICAL-3 (Case 3): a `claude`-persona agent created on a machine + // where the claude adapter isn't installed. `resolvePersonaRuntime` + // falls back to the default (`buzz-agent`) and sends THAT command with + // `harness_override` false (the user did not pick it). At create this + // is a fallback, not a deliberate pin — it must store `None` so the + // agent inherits the persona's runtime once it's installed and the + // persona is re-edited. Baking `Some("buzz-agent")` here is the exact + // bug this resolver chain exists to kill. + let personas = vec![persona_with_runtime("p1", Some("claude"))]; + assert_eq!( + create_time_agent_command_override(Some("p1"), &personas, Some("buzz-agent"), false), + None + ); + } + + #[test] + fn create_time_override_some_when_user_deliberately_overrides_installed_runtime() { + // Case 2 + deliberate override: the persona's `claude` runtime IS + // available, but the user explicitly picked `codex` in a deploy dialog's + // runtime selector ("overriding persona preferences"), so the frontend + // sends `codex-acp` with `harness_override` true. This is a real pin and + // MUST be preserved — returning `None` would silently swallow the + // deliberate override and inherit `claude` on spawn. + let personas = vec![persona_with_runtime("p1", Some("claude"))]; + assert_eq!( + create_time_agent_command_override(Some("p1"), &personas, Some("codex-acp"), true), + Some("codex-acp".to_string()) + ); + } + + #[test] + fn create_time_override_none_when_persona_runtime_installed() { + // Case 2: the persona's runtime is available, so `resolvePersonaRuntime` + // sends the persona's own command with no override. Inherits — no pin. + let personas = vec![persona_with_runtime("p1", Some("goose"))]; + assert_eq!( + create_time_agent_command_override(Some("p1"), &personas, Some("goose"), false), + None + ); + } + + #[test] + fn create_time_override_preserves_pin_for_persona_less_create() { + // The standalone CreateAgentDialog creates persona-LESS agents. With no + // persona to inherit, the picked command IS the agent's harness and must + // be preserved as a real pin (divergence from the bundled default), + // regardless of the override flag. + let personas = vec![persona_with_runtime("p1", Some("goose"))]; + assert_eq!( + create_time_agent_command_override(None, &personas, Some("codex-acp"), false), + Some("codex-acp".to_string()) + ); + } } diff --git a/desktop/src-tauri/src/managed_agents/nest.rs b/desktop/src-tauri/src/managed_agents/nest.rs index 9fec60d6d..5a1551fad 100644 --- a/desktop/src-tauri/src/managed_agents/nest.rs +++ b/desktop/src-tauri/src/managed_agents/nest.rs @@ -995,6 +995,7 @@ mod tests { avatar_url: None, acp_command: String::new(), agent_command: String::new(), + agent_command_override: None, agent_args: vec![], mcp_command: String::new(), turn_timeout_seconds: 0, diff --git a/desktop/src-tauri/src/managed_agents/relay_mesh.rs b/desktop/src-tauri/src/managed_agents/relay_mesh.rs index 808546aa4..5310a9391 100644 --- a/desktop/src-tauri/src/managed_agents/relay_mesh.rs +++ b/desktop/src-tauri/src/managed_agents/relay_mesh.rs @@ -71,6 +71,7 @@ mod tests { avatar_url: None, acp_command: "buzz-acp".into(), agent_command: "goose".into(), + agent_command_override: None, agent_args: vec![], mcp_command: String::new(), turn_timeout_seconds: 320, diff --git a/desktop/src-tauri/src/managed_agents/restore.rs b/desktop/src-tauri/src/managed_agents/restore.rs index 3469dc80d..c1ab2c088 100644 --- a/desktop/src-tauri/src/managed_agents/restore.rs +++ b/desktop/src-tauri/src/managed_agents/restore.rs @@ -198,11 +198,20 @@ pub async fn restore_managed_agents_on_launch( // releasing the lock. This mirrors the fire-and-forget pattern in // start_managed_agent — ensuring boot-restored agents get the same profile // self-healing as UI-started agents. + let reconcile_personas = super::load_personas(app).unwrap_or_default(); let reconcile_items: Vec<(String, crate::commands::ProfileReconcileData)> = successfully_spawned .iter() .filter_map(|pubkey| { let record = records.iter().find(|r| r.pubkey == *pubkey)?; + // Resolve the effective harness for the avatar-fallback + // derivation (the snapshot may be empty/stale for an inherited + // harness). Mirrors the UI start path. + let effective_command = crate::managed_agents::effective_agent_command( + record.persona_id.as_deref(), + &reconcile_personas, + record.agent_command_override.as_deref(), + ); Some(( pubkey.clone(), crate::commands::ProfileReconcileData { @@ -212,7 +221,7 @@ pub async fn restore_managed_agents_on_launch( avatar_url: record.avatar_url.clone(), auth_tag: record.auth_tag.clone(), pubkey: record.pubkey.clone(), - agent_command: record.agent_command.clone(), + agent_command: effective_command, persona_id: record.persona_id.clone(), }, )) diff --git a/desktop/src-tauri/src/managed_agents/runtime.rs b/desktop/src-tauri/src/managed_agents/runtime.rs index b0470bd70..65fd220be 100644 --- a/desktop/src-tauri/src/managed_agents/runtime.rs +++ b/desktop/src-tauri/src/managed_agents/runtime.rs @@ -1353,15 +1353,29 @@ pub fn build_managed_agent_summary( record.model.clone(), ); + // Resolve the effective harness the same way, then derive args/mcp from it, + // so the UI reflects the persona's current harness (or an explicit pin). + let effective_command = crate::managed_agents::effective_agent_command( + record.persona_id.as_deref(), + personas, + record.agent_command_override.as_deref(), + ); + let effective_args = normalize_agent_args(&effective_command, record.agent_args.clone()); + let effective_mcp_command = known_acp_runtime(&effective_command) + .and_then(|r| r.mcp_command) + .unwrap_or("") + .to_string(); + Ok(ManagedAgentSummary { pubkey: record.pubkey.clone(), name: record.name.clone(), persona_id: record.persona_id.clone(), relay_url: record.relay_url.clone(), acp_command: record.acp_command.clone(), - agent_command: record.agent_command.clone(), - agent_args: record.agent_args.clone(), - mcp_command: record.mcp_command.clone(), + agent_command: effective_command, + agent_command_override: record.agent_command_override.clone(), + agent_args: effective_args, + mcp_command: effective_mcp_command, turn_timeout_seconds: record.turn_timeout_seconds, idle_timeout_seconds: record.idle_timeout_seconds, max_turn_duration_seconds: record.max_turn_duration_seconds, @@ -1500,27 +1514,40 @@ pub fn spawn_agent_child( let stderr = stdout .try_clone() .map_err(|error| format!("failed to clone log handle: {error}"))?; - let agent_args = normalize_agent_args(&record.agent_command, record.agent_args.clone()); + // Resolve the effective harness (agent command) from the linked persona, so + // persona harness edits propagate on the next spawn; an explicit per-agent + // override wins. `agent_args` and `mcp_command` are pure derivations of the + // command, so we recompute them from the effective value rather than the + // frozen record snapshot. Mirrors the model resolution below. + let personas = super::load_personas(app).unwrap_or_default(); + let effective_command = super::effective_agent_command( + record.persona_id.as_deref(), + &personas, + record.agent_command_override.as_deref(), + ); + let agent_args = normalize_agent_args(&effective_command, record.agent_args.clone()); let resolved_acp_command = resolve_command(&record.acp_command) .ok_or_else(|| missing_command_message(&record.acp_command, "ACP harness command"))?; - let resolved_mcp_command: Option = if record.mcp_command.is_empty() { + let effective_mcp_command = known_acp_runtime(&effective_command) + .and_then(|r| r.mcp_command) + .unwrap_or(""); + let resolved_mcp_command: Option = if effective_mcp_command.is_empty() { None } else { - match resolve_command(&record.mcp_command) { + match resolve_command(effective_mcp_command) { Some(path) => Some(path), None => { eprintln!( - "buzz-desktop: mcp_command {:?} not found, skipping", - record.mcp_command + "buzz-desktop: mcp_command {effective_mcp_command:?} not found, skipping" ); None } } }; // Resolve agent command to a full path (DMG launches have minimal PATH). - let resolved_agent_command = resolve_command(&record.agent_command) + let resolved_agent_command = resolve_command(&effective_command) .map(|p| p.display().to_string()) - .unwrap_or_else(|| record.agent_command.clone()); + .unwrap_or_else(|| effective_command.clone()); // The agent's effective relay drives both the child's relay connection // (BUZZ_RELAY_URL) and git credential-helper URL: an explicit per-agent @@ -1571,7 +1598,7 @@ pub fn spawn_agent_child( } // Enable MCP hook tools (_Stop, _PostCompact) for agents that need them. // Uses "*" because build_mcp_servers() hard-codes the server name to "buzz-mcp". - let runtime_meta = known_acp_runtime(&record.agent_command); + let runtime_meta = known_acp_runtime(&effective_command); if runtime_meta.is_some_and(|r| r.mcp_hooks) { command.env("MCP_HOOK_SERVERS", "*"); } @@ -1610,7 +1637,7 @@ pub fn spawn_agent_child( // source of truth, so persona edits reach the agent on the next spawn. Fall // back to the record snapshot only when no persona is linked or it was // deleted. Provider flows from the persona (the record has no provider). - let personas = super::load_personas(app).unwrap_or_default(); + // `personas` was loaded above for the harness resolution. let (effective_prompt, effective_model, effective_provider) = resolve_effective_prompt_model_provider( record.persona_id.as_deref(), diff --git a/desktop/src-tauri/src/managed_agents/runtime/tests.rs b/desktop/src-tauri/src/managed_agents/runtime/tests.rs index f8a922da5..51ba378cc 100644 --- a/desktop/src-tauri/src/managed_agents/runtime/tests.rs +++ b/desktop/src-tauri/src/managed_agents/runtime/tests.rs @@ -132,6 +132,7 @@ fn fixture( avatar_url: None, acp_command: "buzz-acp".into(), agent_command: "goose".into(), + agent_command_override: None, agent_args: vec![], mcp_command: String::new(), turn_timeout_seconds: 320, diff --git a/desktop/src-tauri/src/managed_agents/team_repair.rs b/desktop/src-tauri/src/managed_agents/team_repair.rs index d9e272066..00f4a981c 100644 --- a/desktop/src-tauri/src/managed_agents/team_repair.rs +++ b/desktop/src-tauri/src/managed_agents/team_repair.rs @@ -281,6 +281,7 @@ mod tests { avatar_url: None, acp_command: String::new(), agent_command: String::new(), + agent_command_override: None, agent_args: vec![], mcp_command: String::new(), turn_timeout_seconds: 0, diff --git a/desktop/src-tauri/src/managed_agents/types.rs b/desktop/src-tauri/src/managed_agents/types.rs index 82445106c..2eddb4e10 100644 --- a/desktop/src-tauri/src/managed_agents/types.rs +++ b/desktop/src-tauri/src/managed_agents/types.rs @@ -109,6 +109,15 @@ pub struct ManagedAgentRecord { pub avatar_url: Option, pub acp_command: String, pub agent_command: String, + /// Explicit per-instance harness pin. `None` (the default) means inherit + /// the harness from the linked persona's `runtime`, so persona harness + /// edits propagate on the next spawn — mirroring the opt-in `model` + /// override. `Some` is set only when the user deliberately picks a harness + /// that diverges from the persona. Resolved via `effective_agent_command`; + /// `agent_command` above is the create-time snapshot kept for avatar/legacy + /// derivations and is not authoritative for spawn. + #[serde(default)] + pub agent_command_override: Option, pub agent_args: Vec, pub mcp_command: String, pub turn_timeout_seconds: u64, @@ -226,6 +235,11 @@ pub struct ManagedAgentSummary { pub relay_url: String, pub acp_command: String, pub agent_command: String, + /// Mirrors `ManagedAgentRecord.agent_command_override`: `Some` when the user + /// has explicitly pinned this instance's harness, `None` when it inherits + /// from the persona. Lets the Edit dialog seed "Inherit from persona" vs a + /// concrete pin (`agent_command` above is the resolved/effective command). + pub agent_command_override: Option, pub agent_args: Vec, pub mcp_command: String, pub turn_timeout_seconds: u64, @@ -262,6 +276,13 @@ pub struct CreateManagedAgentRequest { pub relay_url: Option, pub acp_command: Option, pub agent_command: Option, + /// True when `agent_command` is a runtime the user deliberately picked to + /// override the linked persona (a deploy-dialog runtime selector). Distinguishes + /// a real pin from a missing-runtime fallback so a persona-backed create only + /// stores an `agent_command_override` for the former. Defaults `false`: callers + /// that don't set it (persona-less creates, fallback divergence) inherit. + #[serde(default)] + pub harness_override: bool, #[serde(default)] pub agent_args: Vec, pub mcp_command: Option, diff --git a/desktop/src-tauri/src/migration.rs b/desktop/src-tauri/src/migration.rs index b6d3262d8..d44245190 100644 --- a/desktop/src-tauri/src/migration.rs +++ b/desktop/src-tauri/src/migration.rs @@ -819,12 +819,31 @@ pub fn migrate_packs_to_teams(app: &tauri::AppHandle) { } fn reconcile_mcp_commands_in_file(path: &Path) { + // Resolve each record's EFFECTIVE harness (persona-wins, override-honored) + // before deriving its mcp_command, so a persona-inherited harness switch + // doesn't leave a stale persisted mcp_command. The persona runtime is read + // from the sibling personas.json; missing entries fall back to the record's + // own agent_command (the create-time snapshot). + let persona_runtimes = load_persona_runtimes(path); patch_json_records(path, |obj| { - let agent_command = match obj.get("agent_command").and_then(|v| v.as_str()) { + let override_cmd = obj + .get("agent_command_override") + .and_then(|v| v.as_str()) + .map(str::trim) + .filter(|v| !v.is_empty()); + let snapshot = obj.get("agent_command").and_then(|v| v.as_str()); + let persona_cmd = obj + .get("persona_id") + .and_then(|v| v.as_str()) + .and_then(|pid| persona_runtimes.get(pid)) + .map(String::as_str) + .and_then(crate::managed_agents::known_acp_runtime_exact) + .and_then(|r| r.commands.first().copied()); + let effective_command = match override_cmd.or(persona_cmd).or(snapshot) { Some(cmd) => cmd.to_string(), None => return false, }; - let Some(runtime) = crate::managed_agents::known_acp_runtime(&agent_command) else { + let Some(runtime) = crate::managed_agents::known_acp_runtime(&effective_command) else { return false; }; let expected = runtime.mcp_command.unwrap_or(""); @@ -843,7 +862,7 @@ fn reconcile_mcp_commands_in_file(path: &Path) { eprintln!( "buzz-desktop: runtime-reconcile: {:?} ({:?}): mcp_command {:?} → {:?}", obj.get("name").and_then(|v| v.as_str()).unwrap_or("?"), - agent_command, + effective_command, current, expected, ); @@ -855,6 +874,31 @@ fn reconcile_mcp_commands_in_file(path: &Path) { }); } +/// Build a `persona_id → runtime` map from the personas.json sibling of the +/// given managed-agents.json path. Returns an empty map when personas can't be +/// read or parsed — callers then fall back to the record's own snapshot. +fn load_persona_runtimes(agents_path: &Path) -> std::collections::HashMap { + let mut map = std::collections::HashMap::new(); + let Some(personas_path) = agents_path.parent().map(|dir| dir.join("personas.json")) else { + return map; + }; + let Ok(content) = std::fs::read_to_string(&personas_path) else { + return map; + }; + let Ok(records) = serde_json::from_str::>(&content) else { + return map; + }; + for record in records { + if let (Some(id), Some(runtime)) = ( + record.get("id").and_then(|v| v.as_str()), + record.get("runtime").and_then(|v| v.as_str()), + ) { + map.insert(id.to_string(), runtime.to_string()); + } + } + map +} + fn replace_command_field( obj: &mut serde_json::Map, field: &str, diff --git a/desktop/src-tauri/src/migration_tests.rs b/desktop/src-tauri/src/migration_tests.rs index 4a79ae02b..f60f394fd 100644 --- a/desktop/src-tauri/src/migration_tests.rs +++ b/desktop/src-tauri/src/migration_tests.rs @@ -829,6 +829,55 @@ fn reconcile_mcp_commands_handles_mixed_agents() { assert_eq!(records[3]["mcp_command"], "buzz-dev-mcp"); } +#[test] +fn reconcile_mcp_commands_resolves_persona_runtime_over_stale_snapshot() { + // The frozen snapshot is buzz-agent (wants buzz-dev-mcp), but the linked + // persona's runtime is goose (wants no mcp). The reconcile must follow the + // EFFECTIVE harness (persona-wins) and clear the stale buzz-mcp-server. + let dir = tempfile::tempdir().unwrap(); + write_agents_json( + dir.path(), + &serde_json::json!([{ + "name": "Fizz", + "persona_id": "p1", + "agent_command": "buzz-agent", + "mcp_command": "buzz-mcp-server" + }]), + ); + write_personas_json( + dir.path(), + &serde_json::json!([{"id": "p1", "runtime": "goose"}]), + ); + reconcile_mcp_commands_in_file(&dir.path().join("agents/managed-agents.json")); + let records = read_agents_json(dir.path()); + assert_eq!(records[0]["mcp_command"], ""); +} + +#[test] +fn reconcile_mcp_commands_honors_explicit_override_over_persona() { + // An explicit per-instance pin (agent_command_override) beats the persona + // runtime: persona is goose (no mcp) but the pin is buzz-agent, so the + // reconcile sets the buzz-agent mcp_command. + let dir = tempfile::tempdir().unwrap(); + write_agents_json( + dir.path(), + &serde_json::json!([{ + "name": "Fizz", + "persona_id": "p1", + "agent_command": "goose", + "agent_command_override": "buzz-agent", + "mcp_command": "" + }]), + ); + write_personas_json( + dir.path(), + &serde_json::json!([{"id": "p1", "runtime": "goose"}]), + ); + reconcile_mcp_commands_in_file(&dir.path().join("agents/managed-agents.json")); + let records = read_agents_json(dir.path()); + assert_eq!(records[0]["mcp_command"], "buzz-dev-mcp"); +} + #[test] fn reconcile_mcp_commands_skips_record_without_agent_command() { let dir = tempfile::tempdir().unwrap(); diff --git a/desktop/src/features/agents/channelAgents.ts b/desktop/src/features/agents/channelAgents.ts index 4ce40ec41..f55130725 100644 --- a/desktop/src/features/agents/channelAgents.ts +++ b/desktop/src/features/agents/channelAgents.ts @@ -60,6 +60,13 @@ export type CreateChannelManagedAgentInput = { systemPrompt?: string; avatarUrl?: string; personaId?: string | null; + /** + * True when `runtime` is a runtime the user deliberately picked to override + * the persona (a deploy-dialog runtime selector), as opposed to a + * missing-runtime fallback. Forwarded to the backend so a persona-backed + * create only pins the harness for a deliberate override. + */ + harnessOverride?: boolean; /** Preferred model ID from the persona. Passed to createManagedAgent. */ model?: string; role?: Exclude; @@ -368,6 +375,7 @@ export async function createChannelManagedAgent( name: trimmedName, acpCommand: "buzz-acp", agentCommand: input.runtime.command, + harnessOverride: input.harnessOverride ?? false, agentArgs: input.runtime.defaultArgs, mcpCommand: input.runtime.mcpCommand ?? "", personaId: input.personaId ?? undefined, diff --git a/desktop/src/features/agents/ui/EditAgentDialog.tsx b/desktop/src/features/agents/ui/EditAgentDialog.tsx index dddc7caef..5d47f5b2b 100644 --- a/desktop/src/features/agents/ui/EditAgentDialog.tsx +++ b/desktop/src/features/agents/ui/EditAgentDialog.tsx @@ -41,6 +41,12 @@ export function EditAgentDialog({ const [relayUrl, setRelayUrl] = React.useState(agent.relayUrl); const [acpCommand, setAcpCommand] = React.useState(agent.acpCommand); const [agentCommand, setAgentCommand] = React.useState(agent.agentCommand); + // Whether the harness inherits from the linked persona (no explicit pin). + // Only meaningful when a persona is linked; seeded from the override field + // so an unset override shows as "inherit" rather than re-pinning on save. + const [inheritHarness, setInheritHarness] = React.useState( + agent.personaId != null && agent.agentCommandOverride == null, + ); const [agentArgs, setAgentArgs] = React.useState(agent.agentArgs.join(",")); const [mcpCommand, setMcpCommand] = React.useState(agent.mcpCommand); const [mcpToolsets, setMcpToolsets] = React.useState(agent.mcpToolsets ?? ""); @@ -55,11 +61,14 @@ export function EditAgentDialog({ ); const [envVars, setEnvVars] = React.useState(agent.envVars); const personasQuery = usePersonasQuery(); - const inheritedEnvVars = React.useMemo(() => { - if (!agent.personaId) return {}; - const persona = personasQuery.data?.find((p) => p.id === agent.personaId); - return persona?.envVars ?? {}; - }, [agent.personaId, personasQuery.data]); + const linkedPersona = React.useMemo( + () => + agent.personaId + ? (personasQuery.data?.find((p) => p.id === agent.personaId) ?? null) + : null, + [agent.personaId, personasQuery.data], + ); + const inheritedEnvVars = linkedPersona?.envVars ?? {}; const [respondTo, setRespondTo] = React.useState( agent.respondTo, ); @@ -78,6 +87,9 @@ export function EditAgentDialog({ setRelayUrl(agent.relayUrl); setAcpCommand(agent.acpCommand); setAgentCommand(agent.agentCommand); + setInheritHarness( + agent.personaId != null && agent.agentCommandOverride == null, + ); setAgentArgs(agent.agentArgs.join(",")); setMcpCommand(agent.mcpCommand); setMcpToolsets(agent.mcpToolsets ?? ""); @@ -127,6 +139,20 @@ export function EditAgentDialog({ .map((v) => v.trim()) .filter((v) => v.length > 0); + // Harness pin resolution. The backend treats an empty string as the + // "inherit from persona" sentinel (clears the override) and any concrete + // command as an explicit pin. When inheriting, only send the sentinel if + // there's a pin to clear — a name-only edit must leave the record alone. + // When pinning, send the command only if it diverges from the resolved + // value the dialog opened with, so an unchanged save stays a no-op. + const agentCommandUpdate = inheritHarness + ? agent.agentCommandOverride != null + ? "" + : undefined + : agentCommand.trim() !== agent.agentCommand + ? agentCommand.trim() + : undefined; + const input: UpdateManagedAgentInput = { pubkey: agent.pubkey, name: name.trim() !== agent.name ? name.trim() : undefined, @@ -136,10 +162,7 @@ export function EditAgentDialog({ acpCommand.trim() !== agent.acpCommand ? acpCommand.trim() : undefined, - agentCommand: - agentCommand.trim() !== agent.agentCommand - ? agentCommand.trim() - : undefined, + agentCommand: agentCommandUpdate, agentArgs: parsedArgs.join(",") !== agent.agentArgs.join(",") ? parsedArgs @@ -214,6 +237,34 @@ export function EditAgentDialog({ onModeChange={setRespondTo} /> + {linkedPersona ? ( +

+ ) : null} + diff --git a/desktop/src/features/channels/ui/AddChannelBotDialog.tsx b/desktop/src/features/channels/ui/AddChannelBotDialog.tsx index 403fa84c1..924a95adc 100644 --- a/desktop/src/features/channels/ui/AddChannelBotDialog.tsx +++ b/desktop/src/features/channels/ui/AddChannelBotDialog.tsx @@ -355,6 +355,10 @@ export function AddChannelBotDialog({ runtime: resolved.runtime ?? effectiveFallback ?? providers[0], name: persona.displayName, personaId: persona.id, + // A deliberate runtime-selector pick overrides the persona; a Case-3 + // fallback (persona runtime not installed) is NOT a pin. `isOverridden` + // alone can't tell them apart, so thread the explicit user intent. + harnessOverride: isOverrideActive, systemPrompt: persona.systemPrompt, avatarUrl: persona.avatarUrl ?? undefined, model: persona.model ?? undefined, diff --git a/desktop/src/shared/api/tauri.ts b/desktop/src/shared/api/tauri.ts index 1975e016e..5b63b6cdd 100644 --- a/desktop/src/shared/api/tauri.ts +++ b/desktop/src/shared/api/tauri.ts @@ -198,6 +198,7 @@ export type RawManagedAgent = { relay_url: string; acp_command: string; agent_command: string; + agent_command_override?: string | null; agent_args: string[]; mcp_command: string; turn_timeout_seconds: number; @@ -856,6 +857,7 @@ export function fromRawManagedAgent(agent: RawManagedAgent): ManagedAgent { relayUrl: agent.relay_url, acpCommand: agent.acp_command, agentCommand: agent.agent_command, + agentCommandOverride: agent.agent_command_override ?? null, agentArgs: agent.agent_args, mcpCommand: agent.mcp_command, turnTimeoutSeconds: agent.turn_timeout_seconds, @@ -1005,6 +1007,7 @@ export async function createManagedAgent(input: CreateManagedAgentInput) { relayUrl: input.relayUrl, acpCommand: input.acpCommand, agentCommand: input.agentCommand, + harnessOverride: input.harnessOverride ?? false, agentArgs: input.agentArgs, mcpCommand: input.mcpCommand, mcpToolsets: input.mcpToolsets, diff --git a/desktop/src/shared/api/types.ts b/desktop/src/shared/api/types.ts index 1ca74eca3..ec4ed526a 100644 --- a/desktop/src/shared/api/types.ts +++ b/desktop/src/shared/api/types.ts @@ -277,7 +277,14 @@ export type ManagedAgent = { personaId: string | null; relayUrl: string; acpCommand: string; + /** Resolved/effective harness command (persona-wins, override-honored). */ agentCommand: string; + /** + * Explicit per-instance harness pin. `null` means the agent inherits its + * harness from the linked persona's runtime. Lets the Edit dialog show + * "Inherit from persona" vs a concrete pin. + */ + agentCommandOverride: string | null; agentArgs: string[]; mcpCommand: string; turnTimeoutSeconds: number; @@ -340,6 +347,13 @@ export type CreateManagedAgentInput = { relayUrl?: string; acpCommand?: string; agentCommand?: string; + /** + * True when `agentCommand` is a runtime the user deliberately picked to + * override the linked persona (a deploy-dialog runtime selector). Lets the + * backend distinguish a real pin from a missing-runtime fallback. Omit/false + * for persona-less creates and fallback divergence — both inherit. + */ + harnessOverride?: boolean; agentArgs?: string[]; mcpCommand?: string; turnTimeoutSeconds?: number; From 092546495d73d305e4d0226ee14bf0d5de4d2f53 Mon Sep 17 00:00:00 2001 From: klopez4212 Date: Wed, 24 Jun 2026 20:54:05 +0100 Subject: [PATCH 05/60] Polish desktop navigation chrome (#1238) --- desktop/src-tauri/tauri.conf.json | 4 +- desktop/src/app/AppShell.tsx | 98 ++++++++++--------- desktop/src/app/AppTopChrome.tsx | 58 ++++------- desktop/src/features/agents/ui/AgentsView.tsx | 9 +- .../channels/ui/AgentSessionThreadPanel.tsx | 8 +- desktop/src/features/chat/ui/ChatHeader.tsx | 85 ++++++++-------- .../src/features/home/ui/HomeLoadingState.tsx | 4 +- desktop/src/features/home/ui/HomeView.tsx | 7 +- .../src/features/home/ui/InboxDetailPane.tsx | 2 +- .../src/features/home/ui/InboxListPane.tsx | 13 +-- .../messages/ui/MessageThreadPanel.tsx | 12 +-- .../features/profile/ui/UserProfilePanel.tsx | 10 +- .../projects/ui/ProjectDetailScreen.tsx | 9 +- .../src/features/projects/ui/ProjectsView.tsx | 9 +- desktop/src/features/pulse/ui/PulseTabBar.tsx | 2 +- .../src/features/search/ui/TopbarSearch.tsx | 2 +- .../src/features/settings/ui/SettingsView.tsx | 6 +- .../src/features/sidebar/ui/AppSidebar.tsx | 4 +- .../workflows/ui/WorkflowDetailPanel.tsx | 2 +- .../features/workflows/ui/WorkflowsView.tsx | 7 +- .../shared/layout/AuxiliaryPanelHeader.tsx | 6 +- .../shared/layout/TopChromeInsetHeader.tsx | 7 +- desktop/src/shared/layout/chromeLayout.ts | 22 ++--- desktop/src/shared/ui/ViewLoadingFallback.tsx | 43 +++----- desktop/src/shared/ui/sidebar.tsx | 2 +- .../e2e/sidebar-more-unread-overlap.spec.ts | 55 ++++------- 26 files changed, 198 insertions(+), 288 deletions(-) diff --git a/desktop/src-tauri/tauri.conf.json b/desktop/src-tauri/tauri.conf.json index 1043c8240..2d8b54a7a 100644 --- a/desktop/src-tauri/tauri.conf.json +++ b/desktop/src-tauri/tauri.conf.json @@ -25,8 +25,8 @@ "hiddenTitle": true, "dragDropEnabled": false, "trafficLightPosition": { - "x": 12, - "y": 22 + "x": 16, + "y": 24 }, "backgroundThrottling": "disabled", "minWidth": 800, diff --git a/desktop/src/app/AppShell.tsx b/desktop/src/app/AppShell.tsx index afa5f3ea8..05babfa6c 100644 --- a/desktop/src/app/AppShell.tsx +++ b/desktop/src/app/AppShell.tsx @@ -768,7 +768,7 @@ export function AppShell() { isHuddleDrawerOpen && "buzz-huddle-app-surface-open", )} > - + {!settingsOpen ? ( ) : null} {settingsOpen ? ( - - - +
+ + + +
) : ( - <> +
- - - +
+ + +
- +
)} - { - const handleWheel = (event: WheelEvent) => { - if (event.clientY <= TOP_CHROME_WHEEL_GUARD_HEIGHT) { - event.preventDefault(); - } - }; - - document.addEventListener("wheel", handleWheel, { - capture: true, - passive: false, - }); - return () => { - document.removeEventListener("wheel", handleWheel, { capture: true }); - }; - }, []); + // On macOS the traffic-light buttons overlay the chrome (see + // `trafficLightPosition` in `tauri.conf.json`), so the nav row clears their + // x-position and shifts to align the nav icon centers with the native dot + // centers. In fullscreen those buttons hide, so use the standard alignment. + const navRowPaddingClass = + isMacPlatform() && !isFullscreen ? "pl-20" : "pl-3"; + const navRowAlignmentClass = + isMacPlatform() && !isFullscreen ? "translate-y-[3px]" : null; return ( - <> -