diff --git a/Cargo.lock b/Cargo.lock index 406a872940b..2c16f832c22 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -43,6 +43,19 @@ dependencies = [ "subtle", ] +[[package]] +name = "ahash" +version = "0.8.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5a15f179cd60c4584b8a8c596927aadc462e27f2ca70c04e0071964a73ba7a75" +dependencies = [ + "cfg-if 1.0.4", + "getrandom 0.3.4", + "once_cell", + "version_check", + "zerocopy", +] + [[package]] name = "aho-corasick" version = "1.1.4" @@ -3160,8 +3173,8 @@ dependencies = [ "libc", "log", "rustversion", - "windows-link 0.2.1", - "windows-result 0.4.1", + "windows-link 0.1.3", + "windows-result 0.3.4", ] [[package]] @@ -3766,7 +3779,7 @@ dependencies = [ "js-sys", "log", "wasm-bindgen", - "windows-core 0.62.2", + "windows-core 0.61.2", ] [[package]] @@ -4761,8 +4774,8 @@ dependencies = [ [[package]] name = "mesh-llm-api-client" -version = "0.73.1" -source = "git+https://github.com/Mesh-LLM/mesh-llm.git?tag=v0.73.1#43103c5c40292be688ac0261129bcbab0e7b9132" +version = "0.74.0" +source = "git+https://github.com/Mesh-LLM/mesh-llm.git?tag=v0.74.0#e60b2fe43aa05271569fbeff2a457133aef456a1" dependencies = [ "hex", "mesh-llm-client", @@ -4771,8 +4784,8 @@ dependencies = [ [[package]] name = "mesh-llm-api-server" -version = "0.73.1" -source = "git+https://github.com/Mesh-LLM/mesh-llm.git?tag=v0.73.1#43103c5c40292be688ac0261129bcbab0e7b9132" +version = "0.74.0" +source = "git+https://github.com/Mesh-LLM/mesh-llm.git?tag=v0.74.0#e60b2fe43aa05271569fbeff2a457133aef456a1" dependencies = [ "anyhow", "mesh-llm-api-client", @@ -4782,13 +4795,13 @@ dependencies = [ [[package]] name = "mesh-llm-build-info" -version = "0.73.1" -source = "git+https://github.com/Mesh-LLM/mesh-llm.git?tag=v0.73.1#43103c5c40292be688ac0261129bcbab0e7b9132" +version = "0.74.0" +source = "git+https://github.com/Mesh-LLM/mesh-llm.git?tag=v0.74.0#e60b2fe43aa05271569fbeff2a457133aef456a1" [[package]] name = "mesh-llm-client" -version = "0.73.1" -source = "git+https://github.com/Mesh-LLM/mesh-llm.git?tag=v0.73.1#43103c5c40292be688ac0261129bcbab0e7b9132" +version = "0.74.0" +source = "git+https://github.com/Mesh-LLM/mesh-llm.git?tag=v0.74.0#e60b2fe43aa05271569fbeff2a457133aef456a1" dependencies = [ "anyhow", "async-trait", @@ -4819,8 +4832,8 @@ dependencies = [ [[package]] name = "mesh-llm-config" -version = "0.73.1" -source = "git+https://github.com/Mesh-LLM/mesh-llm.git?tag=v0.73.1#43103c5c40292be688ac0261129bcbab0e7b9132" +version = "0.74.0" +source = "git+https://github.com/Mesh-LLM/mesh-llm.git?tag=v0.74.0#e60b2fe43aa05271569fbeff2a457133aef456a1" dependencies = [ "anyhow", "dirs", @@ -4835,8 +4848,8 @@ dependencies = [ [[package]] name = "mesh-llm-embedded-runtime" -version = "0.73.1" -source = "git+https://github.com/Mesh-LLM/mesh-llm.git?tag=v0.73.1#43103c5c40292be688ac0261129bcbab0e7b9132" +version = "0.74.0" +source = "git+https://github.com/Mesh-LLM/mesh-llm.git?tag=v0.74.0#e60b2fe43aa05271569fbeff2a457133aef456a1" dependencies = [ "anyhow", "mesh-llm-host-runtime", @@ -4845,8 +4858,8 @@ dependencies = [ [[package]] name = "mesh-llm-events" -version = "0.73.1" -source = "git+https://github.com/Mesh-LLM/mesh-llm.git?tag=v0.73.1#43103c5c40292be688ac0261129bcbab0e7b9132" +version = "0.74.0" +source = "git+https://github.com/Mesh-LLM/mesh-llm.git?tag=v0.74.0#e60b2fe43aa05271569fbeff2a457133aef456a1" dependencies = [ "anyhow", "clap", @@ -4857,8 +4870,8 @@ dependencies = [ [[package]] name = "mesh-llm-gpu-bench" -version = "0.73.1" -source = "git+https://github.com/Mesh-LLM/mesh-llm.git?tag=v0.73.1#43103c5c40292be688ac0261129bcbab0e7b9132" +version = "0.74.0" +source = "git+https://github.com/Mesh-LLM/mesh-llm.git?tag=v0.74.0#e60b2fe43aa05271569fbeff2a457133aef456a1" dependencies = [ "anyhow", "cc", @@ -4870,8 +4883,8 @@ dependencies = [ [[package]] name = "mesh-llm-guardrails" -version = "0.73.1" -source = "git+https://github.com/Mesh-LLM/mesh-llm.git?tag=v0.73.1#43103c5c40292be688ac0261129bcbab0e7b9132" +version = "0.74.0" +source = "git+https://github.com/Mesh-LLM/mesh-llm.git?tag=v0.74.0#e60b2fe43aa05271569fbeff2a457133aef456a1" dependencies = [ "serde", "serde_json", @@ -4879,16 +4892,16 @@ dependencies = [ [[package]] name = "mesh-llm-hardware-profile" -version = "0.73.1" -source = "git+https://github.com/Mesh-LLM/mesh-llm.git?tag=v0.73.1#43103c5c40292be688ac0261129bcbab0e7b9132" +version = "0.74.0" +source = "git+https://github.com/Mesh-LLM/mesh-llm.git?tag=v0.74.0#e60b2fe43aa05271569fbeff2a457133aef456a1" dependencies = [ "mesh-llm-native-runtime", ] [[package]] name = "mesh-llm-host-runtime" -version = "0.73.1" -source = "git+https://github.com/Mesh-LLM/mesh-llm.git?tag=v0.73.1#43103c5c40292be688ac0261129bcbab0e7b9132" +version = "0.74.0" +source = "git+https://github.com/Mesh-LLM/mesh-llm.git?tag=v0.74.0#e60b2fe43aa05271569fbeff2a457133aef456a1" dependencies = [ "anyhow", "argon2", @@ -4910,7 +4923,6 @@ dependencies = [ "http", "http-body-util", "httparse", - "if-addrs", "iroh", "json5", "keyring", @@ -4958,6 +4970,7 @@ dependencies = [ "serde_yaml", "sha2 0.10.9", "skippy-coordinator", + "skippy-ffi", "skippy-protocol", "skippy-runtime", "skippy-server", @@ -4980,8 +4993,8 @@ dependencies = [ [[package]] name = "mesh-llm-identity" -version = "0.73.1" -source = "git+https://github.com/Mesh-LLM/mesh-llm.git?tag=v0.73.1#43103c5c40292be688ac0261129bcbab0e7b9132" +version = "0.74.0" +source = "git+https://github.com/Mesh-LLM/mesh-llm.git?tag=v0.74.0#e60b2fe43aa05271569fbeff2a457133aef456a1" dependencies = [ "argon2", "base64 0.22.1", @@ -5002,8 +5015,8 @@ dependencies = [ [[package]] name = "mesh-llm-native-runtime" -version = "0.73.1" -source = "git+https://github.com/Mesh-LLM/mesh-llm.git?tag=v0.73.1#43103c5c40292be688ac0261129bcbab0e7b9132" +version = "0.74.0" +source = "git+https://github.com/Mesh-LLM/mesh-llm.git?tag=v0.74.0#e60b2fe43aa05271569fbeff2a457133aef456a1" dependencies = [ "anyhow", "serde", @@ -5013,8 +5026,8 @@ dependencies = [ [[package]] name = "mesh-llm-node" -version = "0.73.1" -source = "git+https://github.com/Mesh-LLM/mesh-llm.git?tag=v0.73.1#43103c5c40292be688ac0261129bcbab0e7b9132" +version = "0.74.0" +source = "git+https://github.com/Mesh-LLM/mesh-llm.git?tag=v0.74.0#e60b2fe43aa05271569fbeff2a457133aef456a1" dependencies = [ "anyhow", "mesh-llm-types", @@ -5027,8 +5040,8 @@ dependencies = [ [[package]] name = "mesh-llm-plugin" -version = "0.73.1" -source = "git+https://github.com/Mesh-LLM/mesh-llm.git?tag=v0.73.1#43103c5c40292be688ac0261129bcbab0e7b9132" +version = "0.74.0" +source = "git+https://github.com/Mesh-LLM/mesh-llm.git?tag=v0.74.0#e60b2fe43aa05271569fbeff2a457133aef456a1" dependencies = [ "anyhow", "async-trait", @@ -5044,8 +5057,8 @@ dependencies = [ [[package]] name = "mesh-llm-plugin-manager" -version = "0.73.1" -source = "git+https://github.com/Mesh-LLM/mesh-llm.git?tag=v0.73.1#43103c5c40292be688ac0261129bcbab0e7b9132" +version = "0.74.0" +source = "git+https://github.com/Mesh-LLM/mesh-llm.git?tag=v0.74.0#e60b2fe43aa05271569fbeff2a457133aef456a1" dependencies = [ "anyhow", "dirs", @@ -5055,6 +5068,7 @@ dependencies = [ "reqwest 0.12.28", "serde", "serde_json", + "sha2 0.10.9", "tar", "tempfile", "zip", @@ -5062,8 +5076,8 @@ dependencies = [ [[package]] name = "mesh-llm-protocol" -version = "0.73.1" -source = "git+https://github.com/Mesh-LLM/mesh-llm.git?tag=v0.73.1#43103c5c40292be688ac0261129bcbab0e7b9132" +version = "0.74.0" +source = "git+https://github.com/Mesh-LLM/mesh-llm.git?tag=v0.74.0#e60b2fe43aa05271569fbeff2a457133aef456a1" dependencies = [ "anyhow", "hex", @@ -5075,16 +5089,16 @@ dependencies = [ [[package]] name = "mesh-llm-routing" -version = "0.73.1" -source = "git+https://github.com/Mesh-LLM/mesh-llm.git?tag=v0.73.1#43103c5c40292be688ac0261129bcbab0e7b9132" +version = "0.74.0" +source = "git+https://github.com/Mesh-LLM/mesh-llm.git?tag=v0.74.0#e60b2fe43aa05271569fbeff2a457133aef456a1" dependencies = [ "iroh", ] [[package]] name = "mesh-llm-runtime-install" -version = "0.73.1" -source = "git+https://github.com/Mesh-LLM/mesh-llm.git?tag=v0.73.1#43103c5c40292be688ac0261129bcbab0e7b9132" +version = "0.74.0" +source = "git+https://github.com/Mesh-LLM/mesh-llm.git?tag=v0.74.0#e60b2fe43aa05271569fbeff2a457133aef456a1" dependencies = [ "anyhow", "dirs", @@ -5106,8 +5120,8 @@ dependencies = [ [[package]] name = "mesh-llm-sdk" -version = "0.73.1" -source = "git+https://github.com/Mesh-LLM/mesh-llm.git?tag=v0.73.1#43103c5c40292be688ac0261129bcbab0e7b9132" +version = "0.74.0" +source = "git+https://github.com/Mesh-LLM/mesh-llm.git?tag=v0.74.0#e60b2fe43aa05271569fbeff2a457133aef456a1" dependencies = [ "anyhow", "mesh-llm-api-client", @@ -5121,8 +5135,8 @@ dependencies = [ [[package]] name = "mesh-llm-skills" -version = "0.73.1" -source = "git+https://github.com/Mesh-LLM/mesh-llm.git?tag=v0.73.1#43103c5c40292be688ac0261129bcbab0e7b9132" +version = "0.74.0" +source = "git+https://github.com/Mesh-LLM/mesh-llm.git?tag=v0.74.0#e60b2fe43aa05271569fbeff2a457133aef456a1" dependencies = [ "anyhow", "dirs", @@ -5132,8 +5146,8 @@ dependencies = [ [[package]] name = "mesh-llm-system" -version = "0.73.1" -source = "git+https://github.com/Mesh-LLM/mesh-llm.git?tag=v0.73.1#43103c5c40292be688ac0261129bcbab0e7b9132" +version = "0.74.0" +source = "git+https://github.com/Mesh-LLM/mesh-llm.git?tag=v0.74.0#e60b2fe43aa05271569fbeff2a457133aef456a1" dependencies = [ "anyhow", "chrono", @@ -5155,8 +5169,8 @@ dependencies = [ [[package]] name = "mesh-llm-types" -version = "0.73.1" -source = "git+https://github.com/Mesh-LLM/mesh-llm.git?tag=v0.73.1#43103c5c40292be688ac0261129bcbab0e7b9132" +version = "0.74.0" +source = "git+https://github.com/Mesh-LLM/mesh-llm.git?tag=v0.74.0#e60b2fe43aa05271569fbeff2a457133aef456a1" dependencies = [ "hex", "serde", @@ -5166,13 +5180,13 @@ dependencies = [ [[package]] name = "mesh-llm-ui" -version = "0.73.1" -source = "git+https://github.com/Mesh-LLM/mesh-llm.git?tag=v0.73.1#43103c5c40292be688ac0261129bcbab0e7b9132" +version = "0.74.0" +source = "git+https://github.com/Mesh-LLM/mesh-llm.git?tag=v0.74.0#e60b2fe43aa05271569fbeff2a457133aef456a1" [[package]] name = "mesh-mixture-of-agents" -version = "0.73.1" -source = "git+https://github.com/Mesh-LLM/mesh-llm.git?tag=v0.73.1#43103c5c40292be688ac0261129bcbab0e7b9132" +version = "0.74.0" +source = "git+https://github.com/Mesh-LLM/mesh-llm.git?tag=v0.74.0#e60b2fe43aa05271569fbeff2a457133aef456a1" dependencies = [ "async-trait", "mesh-llm-guardrails", @@ -5298,8 +5312,8 @@ dependencies = [ [[package]] name = "model-artifact" -version = "0.73.1" -source = "git+https://github.com/Mesh-LLM/mesh-llm.git?tag=v0.73.1#43103c5c40292be688ac0261129bcbab0e7b9132" +version = "0.74.0" +source = "git+https://github.com/Mesh-LLM/mesh-llm.git?tag=v0.74.0#e60b2fe43aa05271569fbeff2a457133aef456a1" dependencies = [ "anyhow", "async-trait", @@ -5309,8 +5323,8 @@ dependencies = [ [[package]] name = "model-hf" -version = "0.73.1" -source = "git+https://github.com/Mesh-LLM/mesh-llm.git?tag=v0.73.1#43103c5c40292be688ac0261129bcbab0e7b9132" +version = "0.74.0" +source = "git+https://github.com/Mesh-LLM/mesh-llm.git?tag=v0.74.0#e60b2fe43aa05271569fbeff2a457133aef456a1" dependencies = [ "anyhow", "async-trait", @@ -5327,8 +5341,8 @@ dependencies = [ [[package]] name = "model-package" -version = "0.73.1" -source = "git+https://github.com/Mesh-LLM/mesh-llm.git?tag=v0.73.1#43103c5c40292be688ac0261129bcbab0e7b9132" +version = "0.74.0" +source = "git+https://github.com/Mesh-LLM/mesh-llm.git?tag=v0.74.0#e60b2fe43aa05271569fbeff2a457133aef456a1" dependencies = [ "anyhow", "bytes", @@ -5347,16 +5361,16 @@ dependencies = [ [[package]] name = "model-ref" -version = "0.73.1" -source = "git+https://github.com/Mesh-LLM/mesh-llm.git?tag=v0.73.1#43103c5c40292be688ac0261129bcbab0e7b9132" +version = "0.74.0" +source = "git+https://github.com/Mesh-LLM/mesh-llm.git?tag=v0.74.0#e60b2fe43aa05271569fbeff2a457133aef456a1" dependencies = [ "serde", ] [[package]] name = "model-resolver" -version = "0.73.1" -source = "git+https://github.com/Mesh-LLM/mesh-llm.git?tag=v0.73.1#43103c5c40292be688ac0261129bcbab0e7b9132" +version = "0.74.0" +source = "git+https://github.com/Mesh-LLM/mesh-llm.git?tag=v0.74.0#e60b2fe43aa05271569fbeff2a457133aef456a1" dependencies = [ "anyhow", "model-artifact", @@ -6075,8 +6089,8 @@ checksum = "c08d65885ee38876c4f86fa503fb49d7b507c2b62552df7c70b2fce627e06381" [[package]] name = "openai-frontend" -version = "0.73.1" -source = "git+https://github.com/Mesh-LLM/mesh-llm.git?tag=v0.73.1#43103c5c40292be688ac0261129bcbab0e7b9132" +version = "0.74.0" +source = "git+https://github.com/Mesh-LLM/mesh-llm.git?tag=v0.74.0#e60b2fe43aa05271569fbeff2a457133aef456a1" dependencies = [ "async-trait", "axum", @@ -7704,9 +7718,9 @@ dependencies = [ [[package]] name = "rmcp" -version = "1.7.0" +version = "1.8.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0810a9f717d9828f475fe1f629f4c305c8464b7f496c3a854b58d29e65f4058e" +checksum = "1d1f571c72940a19d9532fe52dbea8bc9912bf1d766c2970bb824056b86f3f59" dependencies = [ "async-trait", "base64 0.22.1", @@ -7737,9 +7751,9 @@ dependencies = [ [[package]] name = "rmcp-macros" -version = "1.7.0" +version = "1.8.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6aefac48c364756e97f04c0401ba3231e8607882c7c1d92da0437dc16307904d" +checksum = "1aad0035b69380782d78ea95b508327e6deaa2235909053e596eea8f27b5e1d5" dependencies = [ "darling 0.23.0", "proc-macro2", @@ -8572,8 +8586,8 @@ checksum = "0c6f73aeb92d671e0cc4dca167e59b2deb6387c375391bc99ee743f326994a2b" [[package]] name = "skippy-cache" -version = "0.73.1" -source = "git+https://github.com/Mesh-LLM/mesh-llm.git?tag=v0.73.1#43103c5c40292be688ac0261129bcbab0e7b9132" +version = "0.74.0" +source = "git+https://github.com/Mesh-LLM/mesh-llm.git?tag=v0.74.0#e60b2fe43aa05271569fbeff2a457133aef456a1" dependencies = [ "anyhow", "blake3", @@ -8582,29 +8596,29 @@ dependencies = [ [[package]] name = "skippy-coordinator" -version = "0.73.1" -source = "git+https://github.com/Mesh-LLM/mesh-llm.git?tag=v0.73.1#43103c5c40292be688ac0261129bcbab0e7b9132" +version = "0.74.0" +source = "git+https://github.com/Mesh-LLM/mesh-llm.git?tag=v0.74.0#e60b2fe43aa05271569fbeff2a457133aef456a1" dependencies = [ "thiserror 2.0.18", ] [[package]] name = "skippy-ffi" -version = "0.73.1" -source = "git+https://github.com/Mesh-LLM/mesh-llm.git?tag=v0.73.1#43103c5c40292be688ac0261129bcbab0e7b9132" +version = "0.74.0" +source = "git+https://github.com/Mesh-LLM/mesh-llm.git?tag=v0.74.0#e60b2fe43aa05271569fbeff2a457133aef456a1" dependencies = [ "libloading", ] [[package]] name = "skippy-metrics" -version = "0.73.1" -source = "git+https://github.com/Mesh-LLM/mesh-llm.git?tag=v0.73.1#43103c5c40292be688ac0261129bcbab0e7b9132" +version = "0.74.0" +source = "git+https://github.com/Mesh-LLM/mesh-llm.git?tag=v0.74.0#e60b2fe43aa05271569fbeff2a457133aef456a1" [[package]] name = "skippy-protocol" -version = "0.73.1" -source = "git+https://github.com/Mesh-LLM/mesh-llm.git?tag=v0.73.1#43103c5c40292be688ac0261129bcbab0e7b9132" +version = "0.74.0" +source = "git+https://github.com/Mesh-LLM/mesh-llm.git?tag=v0.74.0#e60b2fe43aa05271569fbeff2a457133aef456a1" dependencies = [ "prost", "prost-build", @@ -8614,8 +8628,8 @@ dependencies = [ [[package]] name = "skippy-runtime" -version = "0.73.1" -source = "git+https://github.com/Mesh-LLM/mesh-llm.git?tag=v0.73.1#43103c5c40292be688ac0261129bcbab0e7b9132" +version = "0.74.0" +source = "git+https://github.com/Mesh-LLM/mesh-llm.git?tag=v0.74.0#e60b2fe43aa05271569fbeff2a457133aef456a1" dependencies = [ "anyhow", "libc", @@ -8628,9 +8642,10 @@ dependencies = [ [[package]] name = "skippy-server" -version = "0.73.1" -source = "git+https://github.com/Mesh-LLM/mesh-llm.git?tag=v0.73.1#43103c5c40292be688ac0261129bcbab0e7b9132" +version = "0.74.0" +source = "git+https://github.com/Mesh-LLM/mesh-llm.git?tag=v0.74.0#e60b2fe43aa05271569fbeff2a457133aef456a1" dependencies = [ + "ahash", "anyhow", "async-trait", "axum", @@ -8656,8 +8671,8 @@ dependencies = [ [[package]] name = "skippy-topology" -version = "0.73.1" -source = "git+https://github.com/Mesh-LLM/mesh-llm.git?tag=v0.73.1#43103c5c40292be688ac0261129bcbab0e7b9132" +version = "0.74.0" +source = "git+https://github.com/Mesh-LLM/mesh-llm.git?tag=v0.74.0#e60b2fe43aa05271569fbeff2a457133aef456a1" dependencies = [ "serde", "serde_json", @@ -11056,8 +11071,8 @@ dependencies = [ "log", "serde", "thiserror 2.0.18", - "windows 0.62.2", - "windows-core 0.62.2", + "windows 0.61.3", + "windows-core 0.61.2", ] [[package]] diff --git a/Justfile b/Justfile index bcef8983bcc..a2fa408e7f4 100644 --- a/Justfile +++ b/Justfile @@ -276,6 +276,7 @@ test-unit: #!/usr/bin/env bash if command -v cargo-nextest &>/dev/null; then cargo nextest run -p buzz-core -p buzz-auth --lib + cargo nextest run -p buzz-cli # buzz-db migrator/lint tests: pure SQL-parsing unit tests (no infra). # They guard the embedded-migrator invariant (exactly the consolidated # 0001; cutover/backfill stays an operator script, not startup state) @@ -620,6 +621,11 @@ mobile-check: mobile-test: unset GIT_DIR GIT_WORK_TREE; cd {{mobile_dir}} && flutter test +# Regenerate the emoji dataset asset from desktop's emoji-mart install. +# Output is committed — rerun after bumping @emoji-mart/data. +mobile-emoji-data: + node {{mobile_dir}}/scripts/generate-emoji-data.mjs + # Compile an unsigned Android debug APK (worktree-aware debug identity) mobile-build-android: ./scripts/mobile-worktree-overrides.sh diff --git a/VISION_PROJECTS.md b/VISION_PROJECTS.md index a44d7e05f70..8601b87829e 100644 --- a/VISION_PROJECTS.md +++ b/VISION_PROJECTS.md @@ -38,12 +38,42 @@ Branch protections live in the same event — `buzz-protect` tags. The relay enf Agents inherit access from their owner via [NIP-OA](docs/nips/NIP-OA.md). The relay checks: does the push carry a valid NIP-OA auth tag, and is the owner pubkey in that tag listed in `push-allowed`? If yes, the push is accepted — the agent's own pubkey doesn't need to be in the list. Add a maintainer, and all their authorized agents can push. Remove the maintainer, and all their agents lose access instantly. Agents without NIP-OA attestation are treated as their own identity and must be listed explicitly. -Standard NIP-34 clients see a normal repo. gitworkshop.dev renders it. ngit-cli works with it. Buzz clients read the `buzz-` tags and wire up the channel and project UI. One event, two audiences, zero custom kinds. +Standard NIP-34 clients see a normal repo. gitworkshop.dev renders it. ngit-cli works with it. Buzz clients read the `buzz-` tags and wire up the channel and project UI. One event, two audiences, no custom kind for the repo itself. NIP-34 is the metadata and discovery layer. Git remains the transport. The transport is boring. The metadata is portable. --- +## One Project, Many Repos + +Real work spans repositories. The platform is a relay, a desktop app, and a mobile app — three repos, one project. Render one card per repo and they look like three unrelated things. + +Grouping is the one forge semantic that per-repo tags cannot express, and it's worth being precise about why, because everything else here deliberately avoids a custom kind. + +Put membership in each `kind:30617` and a project spanning Alice's and Bob's repos needs *both* of them to publish a tag naming the group. Alice can't enroll Bob's repo — she can't sign for his key. Cross-owner grouping becomes impossible, and the project's own name, description, and channel end up scattered across events with no single writer and no deletion story: dropping a repo from the group would mean editing an event you don't control. + +So there is exactly one custom kind — [NIP-MP](docs/nips/NIP-MP.md), `kind:30621`. One signer, one replaceable event, all group state in one place: + +```json +{ + "kind": 30621, + "tags": [ + ["d", "platform"], + ["name", "Platform"], + ["a", "30617::buzz"], + ["a", "30617::buzz-infra"], + ["buzz-channel", ""], + ["buzz-visibility", "listed"] + ] +} +``` + +A project points at repos. That's all it does. The signer gets no authority over any member — no edit, no delete, no push, no admin. Adding Bob's repo to your project is your signed assertion that the two belong together, and it changes nothing about Bob's repo or who can push to it. Push policy reads the repo's own event, never the project's. + +The cost is stated plainly: a third-party NIP-34 client sees the member repos individually and ignores the grouping. Nothing degrades — the repos are still standard, portable `kind:30617` events. And a repo in no project still renders on its own, exactly as before. + +--- + ## Branches as Channels A feature branch is a conversation. @@ -205,6 +235,7 @@ Standard kinds as substrate. Custom kinds only where genuinely novel. | **Workflows** | — | 46001-46012 | No NIP equivalent | | **Job dispatch** | — | 43001-43006 | Delegation trees | | **Project binding** | 30617 (NIP-34) | `buzz-` tags | Channel, visibility | +| **Multi-repo projects** | — | 30621 ([NIP-MP](docs/nips/NIP-MP.md)) | Cross-owner grouping is unexpressible in per-repo tags | | **Audit** | — | 48001 | Hash-chain tamper-evident log | If Buzz disappears tomorrow, your repos still work on gitworkshop.dev, your patches still work with ngit-cli, your identities still work on any nostr client. Centralized deployment, decentralized protocol. @@ -221,6 +252,7 @@ If Buzz disappears tomorrow, your repos still work on gitworkshop.dev, your patc | Blossom media storage (SHA-256, S3) | ✅ Ships today | | Approval gates | 🚧 Infrastructure exists; executor wiring in progress | | Project binding (kind:30617 + `buzz-` tags) | 📋 Designed | +| Multi-repo projects (kind:30621, [NIP-MP](docs/nips/NIP-MP.md)) | 📋 Designed | | Git hosting (smart HTTP + NIP-34) | ✅ Ships today | | Merge coordinator | 📋 Designed | | NIP-34 issues (kind:1621) | 📋 Designed | diff --git a/crates/buzz-acp/src/pool.rs b/crates/buzz-acp/src/pool.rs index d1e005cbcce..158477c0af0 100644 --- a/crates/buzz-acp/src/pool.rs +++ b/crates/buzz-acp/src/pool.rs @@ -19,6 +19,7 @@ //! //! `AcpClient` is NOT Clone — ownership moves out on claim and back on return. +use std::cmp::Reverse; use std::collections::{HashMap, HashSet}; use std::sync::{Arc, Mutex}; use std::time::Duration; @@ -800,6 +801,9 @@ pub enum IdleSwitchResult { /// 2 × CONTEXT_FETCH_TIMEOUT + CONTEXT_FETCH_RETRY_DELAY ≈ 6.5 s. const CONTEXT_FETCH_TIMEOUT: Duration = Duration::from_millis(3_000); +/// Short, single-attempt timeout for best-effort exact truncated-thread counts. +const CONTEXT_COUNT_TIMEOUT: Duration = Duration::from_millis(500); + /// Delay between the first failed context fetch and the single retry. const CONTEXT_FETCH_RETRY_DELAY: Duration = Duration::from_millis(500); @@ -2600,7 +2604,14 @@ async fn fetch_conversation_context( let last_event = batch.events.last()?; let tags = crate::queue::parse_thread_tags(&last_event.event); if let Some(root_id) = tags.root_event_id { - return fetch_thread_context(batch.channel_id, &root_id, limit, &ctx.rest_client).await; + return fetch_thread_context( + batch.channel_id, + &root_id, + limit, + ctx.agent_keys.public_key(), + &ctx.rest_client, + ) + .await; } // DM non-reply: fetch recent conversation history. @@ -2762,12 +2773,48 @@ async fn fetch_prompt_profile_lookup( } /// Fetch thread context via Nostr query: root event by ID + replies by `#e` tag. +/// +/// The reply query intentionally requests one more reply than the configured +/// display window. That sentinel event lets the prompt say `N of M, truncated` +/// when the relay has more thread history, instead of reporting the capped page +/// as the total. When the window is full, a best-effort `/count` attempts to +/// improve that lower-bound total; because it is a separate racy request, the +/// result is clamped to the sentinel-proven minimum. The query also asks for the +/// agent's newest reply separately so the next prompt can include the agent's +/// own prior turn even in busy threads where the recent-message window would +/// otherwise push it out. async fn fetch_thread_context( channel_id: Uuid, root_event_id: &str, limit: u32, + agent_pubkey: nostr::PublicKey, rest: &RestClient, ) -> Option { + fetch_thread_context_with( + channel_id, + root_event_id, + limit, + agent_pubkey, + |filters| async move { rest.query(&filters).await }, + |filters| async move { rest.count(&filters).await }, + ) + .await +} + +async fn fetch_thread_context_with( + channel_id: Uuid, + root_event_id: &str, + limit: u32, + agent_pubkey: nostr::PublicKey, + query: Query, + count: Count, +) -> Option +where + Query: Fn(Vec) -> QueryFut, + QueryFut: std::future::Future>, + Count: Fn(Vec) -> CountFut, + CountFut: std::future::Future>, +{ use nostr::{Alphabet, SingleLetterTag}; // Defense-in-depth: validate hex event ID. @@ -2786,7 +2833,8 @@ async fn fetch_thread_context( let h_tag = SingleLetterTag::lowercase(Alphabet::H); let ch_str = channel_id.to_string(); - // Two filters: (1) root event by ID, (2) replies with #e=root + #h=channel. + // Three filters: (1) root event by ID, (2) recent replies with #e=root + + // #h=channel plus a sentinel, and (3) the agent's newest reply for pinning. let root_filter = nostr::Filter::new().id(nostr::EventId::from_hex(root_event_id).ok()?); let replies_filter = nostr::Filter::new() .kinds([ @@ -2795,16 +2843,23 @@ async fn fetch_thread_context( ]) .custom_tags(e_tag, [root_event_id]) .custom_tags(h_tag, [ch_str.as_str()]) - .limit(limit as usize); + .limit(limit.saturating_add(1) as usize); + let agent_reply_filter = replies_filter.clone().author(agent_pubkey).limit(1); - fetch_with_retry(|| async { + let context = fetch_with_retry(|| async { match timeout( CONTEXT_FETCH_TIMEOUT, - rest.query(&[root_filter.clone(), replies_filter.clone()]), + query(vec![ + root_filter.clone(), + replies_filter.clone(), + agent_reply_filter.clone(), + ]), ) .await { - Ok(Ok(json)) => parse_nostr_thread_response(json, root_event_id), + Ok(Ok(json)) => { + parse_nostr_thread_response_with_meta(json, root_event_id, limit, &agent_pubkey) + } Ok(Err(e)) => { tracing::warn!( channel_id = %channel_id, @@ -2823,7 +2878,75 @@ async fn fetch_thread_context( } } }) - .await + .await; + + let mut parsed = context?; + + if matches!( + parsed.context, + ConversationContext::Thread { + truncated: true, + .. + } + ) { + let replies_count_filter = replies_filter.clone().limit(0); + if let Some(total) = fetch_thread_total( + channel_id, + &replies_count_filter, + parsed.root_present, + &count, + ) + .await + { + if let ConversationContext::Thread { + total: context_total, + .. + } = &mut parsed.context + { + let sentinel_minimum = *context_total; + // `/count` is a separate best-effort request after the message + // query. If replies are deleted between the two, the exact count + // can fall below the already-proven sentinel minimum; never + // render impossible labels like `13 of 12 messages, truncated`. + *context_total = total.max(sentinel_minimum); + } + } + } + + Some(parsed.context) +} + +/// Best-effort exact thread size for truncated context labels. +async fn fetch_thread_total( + channel_id: Uuid, + replies_filter: &nostr::Filter, + root_present: bool, + count: &Count, +) -> Option +where + Count: Fn(Vec) -> CountFut, + CountFut: std::future::Future>, +{ + let replies_count = + match timeout(CONTEXT_COUNT_TIMEOUT, count(vec![replies_filter.clone()])).await { + Ok(Ok(json)) => json.get("count").and_then(|v| v.as_u64())?, + Ok(Err(e)) => { + tracing::debug!( + channel_id = %channel_id, + "thread context count failed; using sentinel minimum: {e}" + ); + return None; + } + Err(_) => { + tracing::debug!( + channel_id = %channel_id, + "thread context count timed out; using sentinel minimum" + ); + return None; + } + }; + + Some(replies_count as usize + usize::from(root_present)) } /// Fetch DM context via Nostr query: recent messages in channel by `#h` tag. @@ -2976,48 +3099,110 @@ fn json_to_context_message(obj: &serde_json::Value) -> Option { /// Parse a Nostr query response (array of events) into thread context. /// -/// Separates the root event (matching `root_event_id`) from replies, sorts -/// chronologically by `created_at`. +/// Separates the root event (matching `root_event_id`) from replies, keeps the +/// newest `limit` replies returned by the sentinel query, then sorts the +/// displayed window chronologically for the prompt. If the agent's newest reply +/// is outside that window, keep it instead of the oldest displayed reply so the +/// next prompt always includes the agent's most recent prior turn. +#[cfg(test)] fn parse_nostr_thread_response( json: serde_json::Value, root_event_id: &str, + limit: u32, + agent_pubkey: &nostr::PublicKey, ) -> Option { + parse_nostr_thread_response_with_meta(json, root_event_id, limit, agent_pubkey) + .map(|parsed| parsed.context) +} + +struct ParsedThreadContext { + context: ConversationContext, + root_present: bool, +} + +fn parse_nostr_thread_response_with_meta( + json: serde_json::Value, + root_event_id: &str, + limit: u32, + agent_pubkey: &nostr::PublicKey, +) -> Option { let events = json.as_array()?; + let agent_pubkey_hex = agent_pubkey.to_hex(); let mut root_msg = None; let mut reply_msgs = Vec::new(); + let mut seen_reply_ids = HashSet::new(); for ev in events { let ev_id = ev.get("id").and_then(|v| v.as_str()).unwrap_or(""); if let Some(msg) = json_to_context_message(ev) { if ev_id == root_event_id { root_msg = Some(msg); - } else { + } else if seen_reply_ids.insert(ev_id.to_string()) { + let is_agent = msg.pubkey.eq_ignore_ascii_case(&agent_pubkey_hex); reply_msgs.push(( + ev_id.to_string(), ev.get("created_at").and_then(|v| v.as_u64()).unwrap_or(0), + is_agent, msg, )); } } } - // Sort replies chronologically. - reply_msgs.sort_by_key(|(ts, _)| *ts); + let root_present = root_msg.is_some(); + let fetched_total = reply_msgs.len() + usize::from(root_present); + let newest_agent_reply = reply_msgs + .iter() + .filter(|(_, _, is_agent, _)| *is_agent) + .max_by_key(|(_, ts, _, _)| *ts) + .cloned(); + + let truncated = reply_msgs.len() > limit as usize; + if truncated { + // The relay returns limited REQ results newest-first. Sort explicitly so + // the sentinel we drop is the oldest reply in the fetched window, not an + // arbitrary last element if the HTTP bridge ever changes iteration order. + reply_msgs.sort_by_key(|(_, ts, _, _)| Reverse(*ts)); + reply_msgs.truncate(limit as usize); + } + + if let Some(agent_reply) = newest_agent_reply { + let agent_reply_already_displayed = + reply_msgs.iter().any(|(id, _, _, _)| *id == agent_reply.0); + if !agent_reply_already_displayed { + reply_msgs.sort_by_key(|(_, ts, _, _)| *ts); + if let Some(oldest) = reply_msgs.first_mut() { + *oldest = agent_reply; + } + } + } + + // Sort displayed replies chronologically. + reply_msgs.sort_by_key(|(_, ts, _, _)| *ts); let mut messages = Vec::new(); if let Some(root) = root_msg { messages.push(root); } - messages.extend(reply_msgs.into_iter().map(|(_, msg)| msg)); + messages.extend(reply_msgs.into_iter().map(|(_, _, _, msg)| msg)); - let total = messages.len(); if messages.is_empty() { return None; } - Some(ConversationContext::Thread { - messages, - total, - truncated: false, // query returns all within limit + let total = if truncated { + fetched_total // all distinct fetched replies plus the root are proven visible history + } else { + messages.len() + }; + + Some(ParsedThreadContext { + context: ConversationContext::Thread { + messages, + total, + truncated, + }, + root_present, }) } @@ -4204,6 +4389,572 @@ mod tests { assert!(parse_dm_response(json, 12).is_none()); } + #[test] + fn test_parse_nostr_thread_response_marks_query_window_truncated() { + let agent = Keys::generate(); + let root_id = "1111111111111111111111111111111111111111111111111111111111111111"; + let agent_hex = agent.public_key().to_hex(); + let json = json!([ + { + "id": root_id, + "pubkey": "rootpub", + "content": "root", + "created_at": 1000 + }, + { + "id": "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", + "pubkey": agent_hex, + "content": "newest agent reply", + "created_at": 4000 + }, + { + "id": "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb", + "pubkey": "humanpub", + "content": "middle reply", + "created_at": 3000 + }, + { + "id": "cccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc", + "pubkey": "oldpub", + "content": "sentinel omitted reply", + "created_at": 2000 + } + ]); + + let ctx = parse_nostr_thread_response(json, root_id, 2, &agent.public_key()) + .expect("should parse"); + match ctx { + ConversationContext::Thread { + messages, + total, + truncated, + } => { + assert_eq!(messages.len(), 3); // root + 2 displayed replies + assert_eq!(total, 4); // root + displayed replies + sentinel + assert!(truncated); + assert_eq!(messages[0].content, "root"); + assert_eq!(messages[1].content, "middle reply"); + assert_eq!(messages[2].content, "newest agent reply"); + assert!(messages + .iter() + .all(|msg| msg.content != "sentinel omitted reply")); + } + _ => panic!("expected Thread context"), + } + } + + #[test] + fn test_parse_nostr_thread_response_not_truncated_below_limit() { + let agent = Keys::generate(); + let root_id = "1111111111111111111111111111111111111111111111111111111111111111"; + let json = json!([ + { + "id": root_id, + "pubkey": "rootpub", + "content": "root", + "created_at": 1000 + }, + { + "id": "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", + "pubkey": "replypub", + "content": "reply", + "created_at": 2000 + } + ]); + + let ctx = parse_nostr_thread_response(json, root_id, 2, &agent.public_key()) + .expect("should parse"); + match ctx { + ConversationContext::Thread { + messages, + total, + truncated, + } => { + assert_eq!(messages.len(), 2); + assert_eq!(total, 2); + assert!(!truncated); + } + _ => panic!("expected Thread context"), + } + } + + #[test] + fn test_parse_nostr_thread_response_keeps_agent_reply_outside_recent_window() { + let agent = Keys::generate(); + let root_id = "1111111111111111111111111111111111111111111111111111111111111111"; + let agent_hex = agent.public_key().to_hex(); + let json = json!([ + { + "id": root_id, + "pubkey": "rootpub", + "content": "root", + "created_at": 1000 + }, + { + "id": "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", + "pubkey": "humanpub", + "content": "newer human reply", + "created_at": 5000 + }, + { + "id": "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb", + "pubkey": "humanpub", + "content": "middle human reply", + "created_at": 4000 + }, + { + "id": "cccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc", + "pubkey": "humanpub", + "content": "oldest displayed reply without agent pin", + "created_at": 3000 + }, + { + "id": "dddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddd", + "pubkey": agent_hex, + "content": "agent reply outside recent window", + "created_at": 2000 + } + ]); + + let ctx = parse_nostr_thread_response(json, root_id, 2, &agent.public_key()) + .expect("should parse"); + match ctx { + ConversationContext::Thread { messages, .. } => { + assert_eq!(messages.len(), 3); // root + 2 displayed replies + assert_eq!(messages[0].content, "root"); + assert!(messages + .iter() + .any(|msg| msg.content == "agent reply outside recent window")); + assert!(messages + .iter() + .any(|msg| msg.content == "newer human reply")); + assert!(messages + .iter() + .all(|msg| msg.content != "middle human reply")); + assert!(messages + .iter() + .all(|msg| msg.content != "oldest displayed reply without agent pin")); + } + _ => panic!("expected Thread context"), + } + } + + #[tokio::test] + async fn test_fetch_thread_context_uses_exact_count_when_above_sentinel_minimum() { + let agent = Keys::generate(); + let root_id = "1111111111111111111111111111111111111111111111111111111111111111"; + let channel_id = Uuid::new_v4(); + let agent_pubkey = agent.public_key(); + let json = json!([ + thread_event(root_id, "rootpub", "root", 1000), + thread_event( + "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", + "humanpub", + "newest reply", + 4000 + ), + thread_event( + "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb", + "humanpub", + "middle reply", + 3000 + ), + thread_event( + "cccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc", + "humanpub", + "sentinel reply", + 2000 + ) + ]); + + let ctx = fetch_thread_context_with( + channel_id, + root_id, + 2, + agent_pubkey, + move |filters| { + assert_thread_query_filters(&filters, channel_id, root_id, agent_pubkey, 3); + std::future::ready(Ok(json.clone())) + }, + move |filters| { + assert_thread_count_filter(&filters, channel_id, root_id); + std::future::ready(Ok(json!({ "count": 6 }))) + }, + ) + .await + .expect("thread context"); + + match ctx { + ConversationContext::Thread { + messages, + total, + truncated, + } => { + assert!(truncated); + assert_eq!(messages.len(), 3); + assert_eq!(total, 7); // 6 replies + root + } + _ => panic!("expected Thread context"), + } + } + + #[tokio::test] + async fn test_fetch_thread_context_does_not_add_missing_root_to_exact_count() { + let agent = Keys::generate(); + let root_id = "1111111111111111111111111111111111111111111111111111111111111111"; + let channel_id = Uuid::new_v4(); + let json = json!([ + thread_event( + "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", + "humanpub", + "newest reply", + 4000 + ), + thread_event( + "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb", + "humanpub", + "middle reply", + 3000 + ), + thread_event( + "cccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc", + "humanpub", + "sentinel reply", + 2000 + ) + ]); + + let ctx = fetch_thread_context_with( + channel_id, + root_id, + 2, + agent.public_key(), + move |_filters| std::future::ready(Ok(json.clone())), + |_filters| std::future::ready(Ok(json!({ "count": 6 }))), + ) + .await + .expect("thread context"); + + match ctx { + ConversationContext::Thread { + messages, + total, + truncated, + } => { + assert!(truncated); + assert_eq!(messages.len(), 2); + assert_eq!(total, 6); + } + _ => panic!("expected Thread context"), + } + } + + #[tokio::test] + async fn test_fetch_thread_context_clamps_count_below_sentinel_minimum() { + let agent = Keys::generate(); + let root_id = "1111111111111111111111111111111111111111111111111111111111111111"; + let channel_id = Uuid::new_v4(); + let json = json!([ + thread_event(root_id, "rootpub", "root", 1000), + thread_event( + "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", + "humanpub", + "newest reply", + 4000 + ), + thread_event( + "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb", + "humanpub", + "middle reply", + 3000 + ), + thread_event( + "cccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc", + "humanpub", + "sentinel reply", + 2000 + ) + ]); + + let ctx = fetch_thread_context_with( + channel_id, + root_id, + 2, + agent.public_key(), + move |_filters| std::future::ready(Ok(json.clone())), + |_filters| std::future::ready(Ok(json!({ "count": 1 }))), + ) + .await + .expect("thread context"); + + match ctx { + ConversationContext::Thread { + messages, + total, + truncated, + } => { + assert!(truncated); + assert_eq!(messages.len(), 3); + assert_eq!(total, 4); // root + displayed replies + sentinel minimum + } + _ => panic!("expected Thread context"), + } + } + + #[tokio::test] + async fn test_fetch_thread_context_preserves_sentinel_minimum_when_count_fails() { + let agent = Keys::generate(); + let root_id = "1111111111111111111111111111111111111111111111111111111111111111"; + let channel_id = Uuid::new_v4(); + let json = json!([ + thread_event(root_id, "rootpub", "root", 1000), + thread_event( + "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", + "humanpub", + "newest reply", + 4000 + ), + thread_event( + "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb", + "humanpub", + "middle reply", + 3000 + ), + thread_event( + "cccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc", + "humanpub", + "sentinel reply", + 2000 + ) + ]); + + let ctx = fetch_thread_context_with( + channel_id, + root_id, + 2, + agent.public_key(), + move |_filters| std::future::ready(Ok(json.clone())), + |_filters| std::future::ready(Err(crate::relay::RelayError::Http("boom".into()))), + ) + .await + .expect("thread context"); + + match ctx { + ConversationContext::Thread { + messages, + total, + truncated, + } => { + assert!(truncated); + assert_eq!(messages.len(), 3); + assert_eq!(total, 4); // count failure leaves parser's sentinel minimum intact + } + _ => panic!("expected Thread context"), + } + } + + #[tokio::test] + async fn test_fetch_thread_context_deduplicates_and_pins_agent_reply() { + let agent = Keys::generate(); + let agent_hex = agent.public_key().to_hex(); + let root_id = "1111111111111111111111111111111111111111111111111111111111111111"; + let channel_id = Uuid::new_v4(); + let json = json!([ + thread_event(root_id, "rootpub", "root", 1000), + thread_event( + "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", + "humanpub", + "newer human reply", + 5000 + ), + thread_event( + "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb", + "humanpub", + "middle human reply", + 4000 + ), + thread_event( + "cccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc", + &agent_hex, + "agent reply outside recent window", + 2000 + ), + // Same event as the separately fetched author-filtered result; the + // parser should deduplicate it before pinning. + thread_event( + "cccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc", + &agent_hex, + "agent reply outside recent window", + 2000 + ) + ]); + + let ctx = fetch_thread_context_with( + channel_id, + root_id, + 2, + agent.public_key(), + move |_filters| std::future::ready(Ok(json.clone())), + |_filters| std::future::ready(Ok(json!({ "count": 3 }))), + ) + .await + .expect("thread context"); + + match ctx { + ConversationContext::Thread { + messages, + total, + truncated, + } => { + assert!(truncated); + assert_eq!(total, 4); + assert_eq!(messages.len(), 3); + assert_eq!( + messages + .iter() + .filter(|msg| msg.content == "agent reply outside recent window") + .count(), + 1, + "separate agent-reply query must not duplicate the same event" + ); + assert!(messages + .iter() + .any(|msg| msg.content == "newer human reply")); + assert!(messages + .iter() + .all(|msg| msg.content != "middle human reply")); + } + _ => panic!("expected Thread context"), + } + } + + #[tokio::test] + async fn test_fetch_thread_context_uses_distinct_fetched_replies_as_minimum() { + let agent = Keys::generate(); + let agent_hex = agent.public_key().to_hex(); + let root_id = "1111111111111111111111111111111111111111111111111111111111111111"; + let channel_id = Uuid::new_v4(); + let json = json!([ + thread_event(root_id, "rootpub", "root", 1000), + thread_event( + "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", + "humanpub", + "newest human reply", + 5000 + ), + thread_event( + "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb", + "humanpub", + "middle human reply", + 4000 + ), + thread_event( + "cccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc", + "humanpub", + "sentinel human reply", + 3000 + ), + thread_event( + "dddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddd", + &agent_hex, + "older distinct agent reply", + 2000 + ) + ]); + + let ctx = fetch_thread_context_with( + channel_id, + root_id, + 2, + agent.public_key(), + move |_filters| std::future::ready(Ok(json.clone())), + |_filters| std::future::ready(Err(crate::relay::RelayError::Http("boom".into()))), + ) + .await + .expect("thread context"); + + match ctx { + ConversationContext::Thread { + messages, + total, + truncated, + } => { + assert!(truncated); + assert_eq!(messages.len(), 3); + assert_eq!( + total, 5, + "root plus all four distinct fetched replies prove the lower bound" + ); + assert!(messages + .iter() + .any(|msg| msg.content == "older distinct agent reply")); + assert!(messages + .iter() + .any(|msg| msg.content == "newest human reply")); + assert!(messages + .iter() + .all(|msg| msg.content != "middle human reply")); + assert!(messages + .iter() + .all(|msg| msg.content != "sentinel human reply")); + } + _ => panic!("expected Thread context"), + } + } + + fn assert_thread_query_filters( + filters: &[nostr::Filter], + channel_id: Uuid, + root_id: &str, + agent_pubkey: nostr::PublicKey, + reply_limit: u64, + ) { + assert_eq!( + filters.len(), + 3, + "root, recent replies, and agent reply filters" + ); + + let root = serde_json::to_value(&filters[0]).expect("serialize root filter"); + assert_eq!(root.get("ids"), Some(&json!([root_id]))); + assert!(root.get("limit").is_none()); + + let replies = serde_json::to_value(&filters[1]).expect("serialize replies filter"); + assert_eq!(replies.get("kinds"), Some(&json!([9, 40002]))); + assert_eq!(replies.get("#e"), Some(&json!([root_id]))); + assert_eq!(replies.get("#h"), Some(&json!([channel_id.to_string()]))); + assert_eq!(replies.get("limit"), Some(&json!(reply_limit))); + assert!(replies.get("authors").is_none()); + + let agent = serde_json::to_value(&filters[2]).expect("serialize agent filter"); + assert_eq!(agent.get("kinds"), Some(&json!([9, 40002]))); + assert_eq!(agent.get("#e"), Some(&json!([root_id]))); + assert_eq!(agent.get("#h"), Some(&json!([channel_id.to_string()]))); + assert_eq!(agent.get("authors"), Some(&json!([agent_pubkey.to_hex()]))); + assert_eq!(agent.get("limit"), Some(&json!(1))); + } + + fn assert_thread_count_filter(filters: &[nostr::Filter], channel_id: Uuid, root_id: &str) { + assert_eq!(filters.len(), 1, "count should query only matching replies"); + + let count = serde_json::to_value(&filters[0]).expect("serialize count filter"); + assert_eq!(count.get("kinds"), Some(&json!([9, 40002]))); + assert_eq!(count.get("#e"), Some(&json!([root_id]))); + assert_eq!(count.get("#h"), Some(&json!([channel_id.to_string()]))); + assert_eq!(count.get("limit"), Some(&json!(0))); + assert!(count.get("ids").is_none()); + assert!(count.get("authors").is_none()); + } + + fn thread_event(id: &str, pubkey: &str, content: &str, created_at: u64) -> serde_json::Value { + json!({ + "id": id, + "pubkey": pubkey, + "content": content, + "created_at": created_at + }) + } + #[test] fn test_json_to_context_message_integer_timestamp() { let obj = json!({ diff --git a/crates/buzz-acp/src/relay.rs b/crates/buzz-acp/src/relay.rs index c8312cc61e5..aea5cee0770 100644 --- a/crates/buzz-acp/src/relay.rs +++ b/crates/buzz-acp/src/relay.rs @@ -405,6 +405,19 @@ impl RestClient { .map_err(|e| RelayError::Http(e.to_string())) } + /// Count events via the HTTP bridge: `POST /count` with NIP-98 auth. + /// + /// Accepts a slice of `nostr::Filter` (serialized as JSON array). + /// Returns the bridge response as a `serde_json::Value` (usually `{ "count": n }`). + pub async fn count(&self, filters: &[nostr::Filter]) -> Result { + let body_bytes = serde_json::to_vec(filters) + .map_err(|e| RelayError::Http(format!("filter serialize error: {e}")))?; + let resp = self.bridge_post("/count", &body_bytes).await?; + resp.json() + .await + .map_err(|e| RelayError::Http(e.to_string())) + } + /// Submit a signed event via the HTTP bridge: `POST /events` with NIP-98 auth. /// /// The event must already be signed. Returns the relay response JSON. diff --git a/crates/buzz-cli/README.md b/crates/buzz-cli/README.md index 40699459fc0..a2dcdce6d21 100644 --- a/crates/buzz-cli/README.md +++ b/crates/buzz-cli/README.md @@ -56,6 +56,7 @@ buzz reactions get --event buzz users get # your own profile buzz users get --pubkey # single user buzz users get --pubkey --pubkey # batch (max 200) +buzz users get --name Honey --owner me # exact-name lookup in your managed agents buzz users set-presence --status online buzz users set-status --text "heads down on the CLI" --emoji "🚀" buzz users set-status --clear # remove your status diff --git a/crates/buzz-cli/src/commands/users.rs b/crates/buzz-cli/src/commands/users.rs index f5a0bee8799..7c15d285a0d 100644 --- a/crates/buzz-cli/src/commands/users.rs +++ b/crates/buzz-cli/src/commands/users.rs @@ -1,4 +1,7 @@ -use crate::client::{normalize_write_response, BuzzClient}; +use buzz_core::kind::KIND_MANAGED_AGENT; +use nostr::PublicKey; + +use crate::client::{extract_d_tag, normalize_write_response, BuzzClient}; use crate::error::CliError; use crate::validate::validate_hex64; @@ -13,6 +16,7 @@ pub async fn cmd_get_users( client: &BuzzClient, pubkeys: &[String], name: Option<&str>, + owner: Option<&str>, format: &crate::OutputFormat, ) -> Result<(), CliError> { if let Some(query) = name { @@ -21,7 +25,11 @@ pub async fn cmd_get_users( "--name and --pubkey are mutually exclusive".into(), )); } - return search_by_name(client, query, format).await; + return search_by_name(client, query, owner, format).await; + } + + if owner.is_some() { + return Err(CliError::Usage("--owner requires --name".into())); } for pk in pubkeys { @@ -76,68 +84,269 @@ pub async fn cmd_get_users( Ok(()) } -/// Search for users by display name via NIP-50 full-text search on kind:0 profiles. -/// Returns [] if the relay does not implement NIP-50 search. -async fn search_by_name( +fn effective_owner(client: &BuzzClient) -> String { + client + .auth_tag_owner_hex() + .unwrap_or_else(|| client.keys().public_key().to_hex()) +} + +fn resolve_owner(client: &BuzzClient, owner: Option<&str>) -> Result, CliError> { + owner + .map(|owner| { + if owner == "me" { + Ok(effective_owner(client)) + } else { + PublicKey::parse(owner) + .map(|pubkey| pubkey.to_hex()) + .map_err(|e| { + CliError::Usage(format!("--owner must be `me`, a pubkey, or npub: {e}")) + }) + } + }) + .transpose() +} + +fn owned_agent_pubkeys_from_events(events: &[serde_json::Value], query: &str) -> Vec { + let mut pubkeys: Vec = events + .iter() + .filter_map(|event| { + let content: serde_json::Value = + serde_json::from_str(event.get("content")?.as_str()?).ok()?; + let name = content.get("name")?.as_str()?; + if !name.eq_ignore_ascii_case(query) { + return None; + } + let pubkey = extract_d_tag(event); + (!pubkey.is_empty()).then_some(pubkey) + }) + .collect(); + pubkeys.sort(); + pubkeys.dedup(); + pubkeys +} + +async fn owned_agent_pubkeys_by_name( client: &BuzzClient, + owner: &str, query: &str, - format: &crate::OutputFormat, -) -> Result<(), CliError> { - if query.trim().is_empty() { - return Err(CliError::Usage("--name cannot be empty".into())); - } - +) -> Result, CliError> { let filter = serde_json::json!({ - "kinds": [0], - "search": query, - "limit": 100 + "kinds": [KIND_MANAGED_AGENT], + "authors": [owner], }); - let raw = client.query(&filter).await?; - - // Parse and filter client-side for case-insensitive substring match - // on display_name or name fields (NIP-50 may return broader matches). - let events: serde_json::Value = serde_json::from_str(&raw) - .map_err(|e| CliError::Other(format!("failed to parse response: {e}")))?; + let events = client.query_all(filter).await?; + Ok(owned_agent_pubkeys_from_events(&events, query)) +} - let Some(arr) = events.as_array() else { - println!("[]"); - return Ok(()); - }; +fn profile_content(event: &serde_json::Value) -> serde_json::Map { + event + .get("content") + .and_then(|value| value.as_str()) + .and_then(|content| serde_json::from_str::(content).ok()) + .and_then(|content| content.as_object().cloned()) + .unwrap_or_default() +} +fn name_search_profiles(events: &[serde_json::Value], query: &str) -> Vec { let lower_query = query.to_ascii_lowercase(); - let profiles: Vec = arr + events .iter() .filter_map(|event| { - let content_str = event.get("content").and_then(|v| v.as_str())?; - let content: serde_json::Value = serde_json::from_str(content_str).ok()?; - let display_name = content + let mut profile = profile_content(event); + let display_name = profile .get("display_name") - .and_then(|v| v.as_str()) + .and_then(|value| value.as_str()) + .unwrap_or(""); + let name = profile + .get("name") + .and_then(|value| value.as_str()) .unwrap_or(""); - let name = content.get("name").and_then(|v| v.as_str()).unwrap_or(""); if !display_name.to_ascii_lowercase().contains(&lower_query) && !name.to_ascii_lowercase().contains(&lower_query) { return None; } - let mut profile = content; - if let Some(obj) = profile.as_object_mut() { - obj.insert( - "pubkey".to_string(), - serde_json::json!(event.get("pubkey").and_then(|v| v.as_str()).unwrap_or("")), - ); + profile.insert( + "pubkey".to_string(), + serde_json::json!(event + .get("pubkey") + .and_then(|value| value.as_str()) + .unwrap_or("")), + ); + Some(serde_json::Value::Object(profile)) + }) + .collect() +} + +fn auth_tag_values(event: &serde_json::Value) -> Vec<&serde_json::Value> { + event + .get("tags") + .and_then(|tags| tags.as_array()) + .into_iter() + .flatten() + .filter(|tag| { + tag.as_array() + .and_then(|values| values.first()) + .and_then(|value| value.as_str()) + == Some("auth") + }) + .collect() +} + +fn auth_conditions_apply(auth_tag: &serde_json::Value, event: &serde_json::Value) -> bool { + let Some(conditions) = auth_tag + .as_array() + .and_then(|values| values.get(2)) + .and_then(|value| value.as_str()) + else { + return false; + }; + let Some(kind) = event.get("kind").and_then(|value| value.as_u64()) else { + return false; + }; + let Some(created_at) = event.get("created_at").and_then(|value| value.as_u64()) else { + return false; + }; + + conditions.split('&').all(|clause| { + if let Some(value) = clause.strip_prefix("kind=") { + value.parse::() == Ok(kind) + } else if let Some(value) = clause.strip_prefix("created_at<") { + value.parse::().is_ok_and(|bound| created_at < bound) + } else if let Some(value) = clause.strip_prefix("created_at>") { + value.parse::().is_ok_and(|bound| created_at > bound) + } else { + clause.is_empty() + } + }) +} + +fn owner_verification(event: &serde_json::Value, expected_owner: &str) -> &'static str { + let Some(agent_pubkey) = event + .get("pubkey") + .and_then(|value| value.as_str()) + .and_then(|value| PublicKey::parse(value).ok()) + else { + return "invalid_agent_pubkey"; + }; + let auth_tags = auth_tag_values(event); + let [auth_tag] = auth_tags.as_slice() else { + return if auth_tags.is_empty() { + "missing_auth" + } else { + "multiple_auth_tags" + }; + }; + let Ok(auth_tag_json) = serde_json::to_string(auth_tag) else { + return "invalid_auth"; + }; + match buzz_sdk::nip_oa::verify_auth_tag(&auth_tag_json, &agent_pubkey) { + Ok(owner) if owner.to_hex() != expected_owner => "owner_mismatch", + Ok(_) if !auth_conditions_apply(auth_tag, event) => "condition_mismatch", + Ok(_) => "verified", + Err(_) => "invalid_auth", + } +} + +fn owner_scoped_profiles( + events: &[serde_json::Value], + pubkeys: &[String], + owner: &str, + effective_owner: &str, +) -> Vec { + pubkeys + .iter() + .map(|pubkey| { + let event = events.iter().find(|event| { + event.get("pubkey").and_then(|value| value.as_str()) == Some(pubkey.as_str()) + }); + let mut profile = event.map(profile_content).unwrap_or_default(); + let verification = if PublicKey::parse(pubkey).is_err() { + "invalid_agent_pubkey" + } else { + event + .map(|event| owner_verification(event, owner)) + .unwrap_or("missing_profile") + }; + profile.insert("pubkey".to_string(), serde_json::json!(pubkey)); + profile.insert("verification".to_string(), serde_json::json!(verification)); + profile.insert( + "owned_by_me".to_string(), + serde_json::json!(verification == "verified" && owner == effective_owner), + ); + if verification == "verified" { + profile.insert("owner_pubkey".to_string(), serde_json::json!(owner)); } - Some(profile) + serde_json::Value::Object(profile) }) - .collect(); + .collect() +} + +/// Search for users by display name. Owner-scoped searches resolve managed-agent records +/// and verify their profiles; unscoped searches use NIP-50 and return [] if unsupported. +async fn search_by_name( + client: &BuzzClient, + query: &str, + owner: Option<&str>, + format: &crate::OutputFormat, +) -> Result<(), CliError> { + if query.trim().is_empty() { + return Err(CliError::Usage("--name cannot be empty".into())); + } + + let owner = resolve_owner(client, owner)?; + let profiles = if let Some(owner) = owner { + let pubkeys = owned_agent_pubkeys_by_name(client, &owner, query).await?; + if pubkeys.is_empty() { + println!("[]"); + return Ok(()); + } + let valid_pubkeys: Vec<&String> = pubkeys + .iter() + .filter(|pubkey| PublicKey::parse(pubkey.as_str()).is_ok()) + .collect(); + let events = if valid_pubkeys.is_empty() { + Vec::new() + } else { + let filter = serde_json::json!({ + "kinds": [0], + "authors": valid_pubkeys, + "limit": valid_pubkeys.len(), + }); + let raw = client.query(&filter).await?; + serde_json::from_str(&raw) + .map_err(|e| CliError::Other(format!("failed to parse response: {e}")))? + }; + owner_scoped_profiles(&events, &pubkeys, &owner, &effective_owner(client)) + } else { + let filter = serde_json::json!({ + "kinds": [0], + "search": query, + "limit": 100 + }); + let raw = client.query(&filter).await?; + let events: Vec = serde_json::from_str(&raw) + .map_err(|e| CliError::Other(format!("failed to parse response: {e}")))?; + name_search_profiles(&events, query) + }; let output = match format { crate::OutputFormat::Compact => { let compact: Vec = profiles .iter() - .map(|p| serde_json::json!({ - "pubkey": p.get("pubkey").cloned().unwrap_or_default(), - "display_name": p.get("display_name").or_else(|| p.get("name")).cloned().unwrap_or_default(), - })) + .map(|p| { + let mut value = serde_json::json!({ + "pubkey": p.get("pubkey").cloned().unwrap_or_default(), + "display_name": p.get("display_name").or_else(|| p.get("name")).cloned().unwrap_or_default(), + }); + if let Some(obj) = value.as_object_mut() { + for field in ["owner_pubkey", "owned_by_me", "verification"] { + if let Some(field_value) = p.get(field) { + obj.insert(field.to_string(), field_value.clone()); + } + } + } + value + }) .collect(); serde_json::to_string(&compact).unwrap_or_default() } @@ -327,9 +536,11 @@ pub async fn dispatch( ) -> Result<(), CliError> { use crate::UsersCmd; match cmd { - UsersCmd::Get { pubkeys, name } => { - cmd_get_users(client, &pubkeys, name.as_deref(), format).await - } + UsersCmd::Get { + pubkeys, + name, + owner, + } => cmd_get_users(client, &pubkeys, name.as_deref(), owner.as_deref(), format).await, UsersCmd::SetProfile { name, avatar, @@ -362,9 +573,178 @@ pub async fn dispatch( #[cfg(test)] mod tests { - use super::presence_subject; + use super::{ + owned_agent_pubkeys_from_events, owner_scoped_profiles, owner_verification, + presence_subject, + }; + use nostr::Keys; use serde_json::json; + #[test] + fn owned_agent_lookup_matches_exact_name_case_insensitively() { + let events = vec![ + json!({"content": r#"{"name":"Honey"}"#, "tags": [["d", "b"]]}), + json!({"content": r#"{"name":"Honeybee"}"#, "tags": [["d", "c"]]}), + json!({"content": r#"{"name":"honey"}"#, "tags": [["d", "a"]]}), + ]; + assert_eq!( + owned_agent_pubkeys_from_events(&events, "Honey"), + vec!["a", "b"] + ); + } + + #[test] + fn owned_agent_lookup_ignores_malformed_events() { + let events = vec![ + json!({"content": "not json", "tags": [["d", "a"]]}), + json!({"content": r#"{"name":"Honey"}"#, "tags": [["p", "b"]]}), + ]; + assert!(owned_agent_pubkeys_from_events(&events, "Honey").is_empty()); + } + + fn profile_event(agent_keys: &Keys, auth_tags: Vec) -> serde_json::Value { + json!({ + "pubkey": agent_keys.public_key().to_hex(), + "kind": 0, + "created_at": 100, + "content": r#"{"display_name":"Renamed Honey"}"#, + "tags": auth_tags, + }) + } + + #[test] + fn owner_verification_requires_one_valid_auth_tag_for_requested_owner() { + let owner_keys = Keys::generate(); + let agent_keys = Keys::generate(); + let foreign_owner_keys = Keys::generate(); + let valid_tag: serde_json::Value = serde_json::from_str( + &buzz_sdk::nip_oa::compute_auth_tag(&owner_keys, &agent_keys.public_key(), "kind=0") + .unwrap(), + ) + .unwrap(); + let foreign_tag: serde_json::Value = serde_json::from_str( + &buzz_sdk::nip_oa::compute_auth_tag( + &foreign_owner_keys, + &agent_keys.public_key(), + "kind=9", + ) + .unwrap(), + ) + .unwrap(); + + assert_eq!( + owner_verification( + &profile_event(&agent_keys, vec![valid_tag.clone()]), + &owner_keys.public_key().to_hex(), + ), + "verified" + ); + assert_eq!( + owner_verification( + &profile_event(&agent_keys, vec![foreign_tag]), + &owner_keys.public_key().to_hex(), + ), + "owner_mismatch" + ); + assert_eq!( + owner_verification( + &profile_event(&agent_keys, vec![]), + &owner_keys.public_key().to_hex() + ), + "missing_auth" + ); + assert_eq!( + owner_verification( + &profile_event(&agent_keys, vec![valid_tag.clone(), valid_tag]), + &owner_keys.public_key().to_hex(), + ), + "multiple_auth_tags" + ); + assert_eq!( + owner_verification( + &profile_event( + &agent_keys, + vec![json!([ + "auth", + owner_keys.public_key().to_hex(), + "kind=9", + "0".repeat(128) + ])], + ), + &owner_keys.public_key().to_hex(), + ), + "invalid_auth" + ); + } + + #[test] + fn owner_verification_requires_conditions_to_apply_to_profile_event() { + let owner_keys = Keys::generate(); + let agent_keys = Keys::generate(); + let verification = |conditions: &str| { + let auth_tag: serde_json::Value = serde_json::from_str( + &buzz_sdk::nip_oa::compute_auth_tag( + &owner_keys, + &agent_keys.public_key(), + conditions, + ) + .unwrap(), + ) + .unwrap(); + owner_verification( + &profile_event(&agent_keys, vec![auth_tag]), + &owner_keys.public_key().to_hex(), + ) + }; + + assert_eq!(verification("kind=9"), "condition_mismatch"); + assert_eq!(verification("created_at<100"), "condition_mismatch"); + assert_eq!(verification("created_at>100"), "condition_mismatch"); + assert_eq!( + verification("kind=0&created_at>99&created_at<101"), + "verified" + ); + } + + #[test] + fn owner_scoped_profiles_keep_drifted_and_missing_profiles_without_claiming_ownership() { + let owner_keys = Keys::generate(); + let agent_keys = Keys::generate(); + let missing_keys = Keys::generate(); + let auth_tag: serde_json::Value = serde_json::from_str( + &buzz_sdk::nip_oa::compute_auth_tag(&owner_keys, &agent_keys.public_key(), "kind=0") + .unwrap(), + ) + .unwrap(); + let events = vec![profile_event(&agent_keys, vec![auth_tag])]; + let pubkeys = vec![ + agent_keys.public_key().to_hex(), + missing_keys.public_key().to_hex(), + "malformed".to_string(), + ]; + + let profiles = owner_scoped_profiles( + &events, + &pubkeys, + &owner_keys.public_key().to_hex(), + &owner_keys.public_key().to_hex(), + ); + + assert_eq!(profiles[0]["display_name"], "Renamed Honey"); + assert_eq!(profiles[0]["verification"], "verified"); + assert_eq!(profiles[0]["owned_by_me"], true); + assert_eq!( + profiles[0]["owner_pubkey"], + owner_keys.public_key().to_hex() + ); + assert_eq!(profiles[1]["verification"], "missing_profile"); + assert_eq!(profiles[1]["owned_by_me"], false); + assert!(profiles[1].get("owner_pubkey").is_none()); + assert_eq!(profiles[2]["verification"], "invalid_agent_pubkey"); + assert_eq!(profiles[2]["owned_by_me"], false); + assert!(profiles[2].get("owner_pubkey").is_none()); + } + #[test] fn presence_subject_uses_p_tag() { let event = json!({"pubkey": "relay", "tags": [["p", "user"]]}); diff --git a/crates/buzz-cli/src/lib.rs b/crates/buzz-cli/src/lib.rs index 6e82013dcdc..1946eb1639a 100644 --- a/crates/buzz-cli/src/lib.rs +++ b/crates/buzz-cli/src/lib.rs @@ -927,6 +927,9 @@ pub enum UsersCmd { /// Search by display name (case-insensitive substring match) #[arg(long = "name")] name: Option, + /// Scope an exact-name agent lookup to its owner (`me`, hex, or npub) + #[arg(long = "owner", requires = "name")] + owner: Option, }, /// Update the current identity's profile #[command(name = "set-profile")] diff --git a/crates/buzz-relay/Cargo.toml b/crates/buzz-relay/Cargo.toml index 01f78a2d496..41bdc3b9e9b 100644 --- a/crates/buzz-relay/Cargo.toml +++ b/crates/buzz-relay/Cargo.toml @@ -84,8 +84,8 @@ async-compression = { version = "0.4.42", features = ["tokio", "gzip"] } dev = ["buzz-auth/dev"] [dev-dependencies] -mesh-llm-sdk = { git = "https://github.com/Mesh-LLM/mesh-llm.git", tag = "v0.73.1", package = "mesh-llm-sdk", default-features = false, features = ["client", "serving"] } -mesh-llm-host-runtime = { git = "https://github.com/Mesh-LLM/mesh-llm.git", tag = "v0.73.1", package = "mesh-llm-host-runtime", default-features = false, features = ["dynamic-native-runtime"] } +mesh-llm-sdk = { git = "https://github.com/Mesh-LLM/mesh-llm.git", tag = "v0.74.0", package = "mesh-llm-sdk", default-features = false, features = ["client", "serving"] } +mesh-llm-host-runtime = { git = "https://github.com/Mesh-LLM/mesh-llm.git", tag = "v0.74.0", package = "mesh-llm-host-runtime", default-features = false, features = ["dynamic-native-runtime"] } buzz-core = { workspace = true, features = ["test-utils"] } buzz-auth = { workspace = true, features = ["dev"] } reqwest = { workspace = true } diff --git a/crates/buzz-relay/examples/mesh_agent_e2e.rs b/crates/buzz-relay/examples/mesh_agent_e2e.rs index b6f723f35af..345ca4c746c 100644 --- a/crates/buzz-relay/examples/mesh_agent_e2e.rs +++ b/crates/buzz-relay/examples/mesh_agent_e2e.rs @@ -278,7 +278,9 @@ async fn agent_chat_in_isolated_home( .env("OPENAI_COMPAT_API_KEY", "buzz-mesh-local") .env("OPENAI_COMPAT_API", "chat") .env("BUZZ_AGENT_MAX_OUTPUT_TOKENS", "4096") - .env("BUZZ_AGENT_THINKING_EFFORT", "none") + // No BUZZ_AGENT_THINKING_EFFORT: apply_relay_mesh_env() deliberately + // leaves it unset so each model's chat template picks its own default. + // Pinning a value here would test a config the product does not ship. .stdin(Stdio::piped()) .stdout(Stdio::piped()) .stderr(Stdio::null()); diff --git a/desktop/playwright.config.ts b/desktop/playwright.config.ts index 459fa757432..c79ef1bf9df 100644 --- a/desktop/playwright.config.ts +++ b/desktop/playwright.config.ts @@ -34,6 +34,7 @@ export default defineConfig({ "**/hosted-communities-settings-screenshots.spec.ts", "**/invites-settings-screenshots.spec.ts", "**/messaging.spec.ts", + "**/message-feedback-snapshots.spec.ts", "**/custom-emoji.spec.ts", "**/profile-custom-emoji-status.spec.ts", "**/custom-emoji-ui.spec.ts", @@ -121,6 +122,7 @@ export default defineConfig({ "**/signout-confirmation.spec.ts", "**/agent-provider-dropdowns.spec.ts", "**/agent-lifecycle-feedback.spec.ts", + "**/agent-access-warning.spec.ts", "**/inbox-live-update.spec.ts", "**/mesh-compute.spec.ts", "**/observer-archive-policy.spec.ts", diff --git a/desktop/src-tauri/Cargo.lock b/desktop/src-tauri/Cargo.lock index 9a8ecb3e0ad..a18b142c3cc 100644 --- a/desktop/src-tauri/Cargo.lock +++ b/desktop/src-tauri/Cargo.lock @@ -75,6 +75,19 @@ dependencies = [ "subtle", ] +[[package]] +name = "ahash" +version = "0.8.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5a15f179cd60c4584b8a8c596927aadc462e27f2ca70c04e0071964a73ba7a75" +dependencies = [ + "cfg-if 1.0.4", + "getrandom 0.3.4", + "once_cell", + "version_check", + "zerocopy", +] + [[package]] name = "aho-corasick" version = "1.1.4" @@ -1050,7 +1063,9 @@ dependencies = [ "neteq", "nostr", "notify-rust", + "objc2", "objc2-app-kit", + "objc2-foundation", "opus", "plist", "png 0.18.1", @@ -1088,6 +1103,7 @@ dependencies = [ "url", "user-idle", "uuid", + "webkit2gtk", "window-vibrancy", "windows-sys 0.61.2", "zeroize", @@ -4987,8 +5003,8 @@ dependencies = [ [[package]] name = "mesh-llm-api-client" -version = "0.73.1" -source = "git+https://github.com/Mesh-LLM/mesh-llm.git?rev=f455d493a2ae82baf2a326e2d0fda351433b4b30#f455d493a2ae82baf2a326e2d0fda351433b4b30" +version = "0.74.0" +source = "git+https://github.com/Mesh-LLM/mesh-llm.git?tag=v0.74.0#e60b2fe43aa05271569fbeff2a457133aef456a1" dependencies = [ "hex", "mesh-llm-client", @@ -4997,8 +5013,8 @@ dependencies = [ [[package]] name = "mesh-llm-api-server" -version = "0.73.1" -source = "git+https://github.com/Mesh-LLM/mesh-llm.git?rev=f455d493a2ae82baf2a326e2d0fda351433b4b30#f455d493a2ae82baf2a326e2d0fda351433b4b30" +version = "0.74.0" +source = "git+https://github.com/Mesh-LLM/mesh-llm.git?tag=v0.74.0#e60b2fe43aa05271569fbeff2a457133aef456a1" dependencies = [ "anyhow", "mesh-llm-api-client", @@ -5008,13 +5024,13 @@ dependencies = [ [[package]] name = "mesh-llm-build-info" -version = "0.73.1" -source = "git+https://github.com/Mesh-LLM/mesh-llm.git?rev=f455d493a2ae82baf2a326e2d0fda351433b4b30#f455d493a2ae82baf2a326e2d0fda351433b4b30" +version = "0.74.0" +source = "git+https://github.com/Mesh-LLM/mesh-llm.git?tag=v0.74.0#e60b2fe43aa05271569fbeff2a457133aef456a1" [[package]] name = "mesh-llm-client" -version = "0.73.1" -source = "git+https://github.com/Mesh-LLM/mesh-llm.git?rev=f455d493a2ae82baf2a326e2d0fda351433b4b30#f455d493a2ae82baf2a326e2d0fda351433b4b30" +version = "0.74.0" +source = "git+https://github.com/Mesh-LLM/mesh-llm.git?tag=v0.74.0#e60b2fe43aa05271569fbeff2a457133aef456a1" dependencies = [ "anyhow", "async-trait", @@ -5045,8 +5061,8 @@ dependencies = [ [[package]] name = "mesh-llm-config" -version = "0.73.1" -source = "git+https://github.com/Mesh-LLM/mesh-llm.git?rev=f455d493a2ae82baf2a326e2d0fda351433b4b30#f455d493a2ae82baf2a326e2d0fda351433b4b30" +version = "0.74.0" +source = "git+https://github.com/Mesh-LLM/mesh-llm.git?tag=v0.74.0#e60b2fe43aa05271569fbeff2a457133aef456a1" dependencies = [ "anyhow", "dirs", @@ -5061,8 +5077,8 @@ dependencies = [ [[package]] name = "mesh-llm-embedded-runtime" -version = "0.73.1" -source = "git+https://github.com/Mesh-LLM/mesh-llm.git?rev=f455d493a2ae82baf2a326e2d0fda351433b4b30#f455d493a2ae82baf2a326e2d0fda351433b4b30" +version = "0.74.0" +source = "git+https://github.com/Mesh-LLM/mesh-llm.git?tag=v0.74.0#e60b2fe43aa05271569fbeff2a457133aef456a1" dependencies = [ "anyhow", "mesh-llm-host-runtime", @@ -5071,8 +5087,8 @@ dependencies = [ [[package]] name = "mesh-llm-events" -version = "0.73.1" -source = "git+https://github.com/Mesh-LLM/mesh-llm.git?rev=f455d493a2ae82baf2a326e2d0fda351433b4b30#f455d493a2ae82baf2a326e2d0fda351433b4b30" +version = "0.74.0" +source = "git+https://github.com/Mesh-LLM/mesh-llm.git?tag=v0.74.0#e60b2fe43aa05271569fbeff2a457133aef456a1" dependencies = [ "anyhow", "clap", @@ -5083,8 +5099,8 @@ dependencies = [ [[package]] name = "mesh-llm-gpu-bench" -version = "0.73.1" -source = "git+https://github.com/Mesh-LLM/mesh-llm.git?rev=f455d493a2ae82baf2a326e2d0fda351433b4b30#f455d493a2ae82baf2a326e2d0fda351433b4b30" +version = "0.74.0" +source = "git+https://github.com/Mesh-LLM/mesh-llm.git?tag=v0.74.0#e60b2fe43aa05271569fbeff2a457133aef456a1" dependencies = [ "anyhow", "cc", @@ -5096,8 +5112,8 @@ dependencies = [ [[package]] name = "mesh-llm-guardrails" -version = "0.73.1" -source = "git+https://github.com/Mesh-LLM/mesh-llm.git?rev=f455d493a2ae82baf2a326e2d0fda351433b4b30#f455d493a2ae82baf2a326e2d0fda351433b4b30" +version = "0.74.0" +source = "git+https://github.com/Mesh-LLM/mesh-llm.git?tag=v0.74.0#e60b2fe43aa05271569fbeff2a457133aef456a1" dependencies = [ "serde", "serde_json", @@ -5105,16 +5121,16 @@ dependencies = [ [[package]] name = "mesh-llm-hardware-profile" -version = "0.73.1" -source = "git+https://github.com/Mesh-LLM/mesh-llm.git?rev=f455d493a2ae82baf2a326e2d0fda351433b4b30#f455d493a2ae82baf2a326e2d0fda351433b4b30" +version = "0.74.0" +source = "git+https://github.com/Mesh-LLM/mesh-llm.git?tag=v0.74.0#e60b2fe43aa05271569fbeff2a457133aef456a1" dependencies = [ "mesh-llm-native-runtime", ] [[package]] name = "mesh-llm-host-runtime" -version = "0.73.1" -source = "git+https://github.com/Mesh-LLM/mesh-llm.git?rev=f455d493a2ae82baf2a326e2d0fda351433b4b30#f455d493a2ae82baf2a326e2d0fda351433b4b30" +version = "0.74.0" +source = "git+https://github.com/Mesh-LLM/mesh-llm.git?tag=v0.74.0#e60b2fe43aa05271569fbeff2a457133aef456a1" dependencies = [ "anyhow", "argon2", @@ -5136,7 +5152,6 @@ dependencies = [ "http", "http-body-util", "httparse", - "if-addrs", "iroh", "json5", "keyring", @@ -5184,6 +5199,7 @@ dependencies = [ "serde_yaml", "sha2 0.10.9", "skippy-coordinator", + "skippy-ffi", "skippy-protocol", "skippy-runtime", "skippy-server", @@ -5206,8 +5222,8 @@ dependencies = [ [[package]] name = "mesh-llm-identity" -version = "0.73.1" -source = "git+https://github.com/Mesh-LLM/mesh-llm.git?rev=f455d493a2ae82baf2a326e2d0fda351433b4b30#f455d493a2ae82baf2a326e2d0fda351433b4b30" +version = "0.74.0" +source = "git+https://github.com/Mesh-LLM/mesh-llm.git?tag=v0.74.0#e60b2fe43aa05271569fbeff2a457133aef456a1" dependencies = [ "argon2", "base64 0.22.1", @@ -5228,8 +5244,8 @@ dependencies = [ [[package]] name = "mesh-llm-native-runtime" -version = "0.73.1" -source = "git+https://github.com/Mesh-LLM/mesh-llm.git?rev=f455d493a2ae82baf2a326e2d0fda351433b4b30#f455d493a2ae82baf2a326e2d0fda351433b4b30" +version = "0.74.0" +source = "git+https://github.com/Mesh-LLM/mesh-llm.git?tag=v0.74.0#e60b2fe43aa05271569fbeff2a457133aef456a1" dependencies = [ "anyhow", "serde", @@ -5239,8 +5255,8 @@ dependencies = [ [[package]] name = "mesh-llm-node" -version = "0.73.1" -source = "git+https://github.com/Mesh-LLM/mesh-llm.git?rev=f455d493a2ae82baf2a326e2d0fda351433b4b30#f455d493a2ae82baf2a326e2d0fda351433b4b30" +version = "0.74.0" +source = "git+https://github.com/Mesh-LLM/mesh-llm.git?tag=v0.74.0#e60b2fe43aa05271569fbeff2a457133aef456a1" dependencies = [ "anyhow", "mesh-llm-types", @@ -5253,8 +5269,8 @@ dependencies = [ [[package]] name = "mesh-llm-plugin" -version = "0.73.1" -source = "git+https://github.com/Mesh-LLM/mesh-llm.git?rev=f455d493a2ae82baf2a326e2d0fda351433b4b30#f455d493a2ae82baf2a326e2d0fda351433b4b30" +version = "0.74.0" +source = "git+https://github.com/Mesh-LLM/mesh-llm.git?tag=v0.74.0#e60b2fe43aa05271569fbeff2a457133aef456a1" dependencies = [ "anyhow", "async-trait", @@ -5270,8 +5286,8 @@ dependencies = [ [[package]] name = "mesh-llm-plugin-manager" -version = "0.73.1" -source = "git+https://github.com/Mesh-LLM/mesh-llm.git?rev=f455d493a2ae82baf2a326e2d0fda351433b4b30#f455d493a2ae82baf2a326e2d0fda351433b4b30" +version = "0.74.0" +source = "git+https://github.com/Mesh-LLM/mesh-llm.git?tag=v0.74.0#e60b2fe43aa05271569fbeff2a457133aef456a1" dependencies = [ "anyhow", "dirs", @@ -5281,6 +5297,7 @@ dependencies = [ "reqwest 0.12.28", "serde", "serde_json", + "sha2 0.10.9", "tar", "tempfile", "zip 2.4.2", @@ -5288,8 +5305,8 @@ dependencies = [ [[package]] name = "mesh-llm-protocol" -version = "0.73.1" -source = "git+https://github.com/Mesh-LLM/mesh-llm.git?rev=f455d493a2ae82baf2a326e2d0fda351433b4b30#f455d493a2ae82baf2a326e2d0fda351433b4b30" +version = "0.74.0" +source = "git+https://github.com/Mesh-LLM/mesh-llm.git?tag=v0.74.0#e60b2fe43aa05271569fbeff2a457133aef456a1" dependencies = [ "anyhow", "hex", @@ -5301,16 +5318,16 @@ dependencies = [ [[package]] name = "mesh-llm-routing" -version = "0.73.1" -source = "git+https://github.com/Mesh-LLM/mesh-llm.git?rev=f455d493a2ae82baf2a326e2d0fda351433b4b30#f455d493a2ae82baf2a326e2d0fda351433b4b30" +version = "0.74.0" +source = "git+https://github.com/Mesh-LLM/mesh-llm.git?tag=v0.74.0#e60b2fe43aa05271569fbeff2a457133aef456a1" dependencies = [ "iroh", ] [[package]] name = "mesh-llm-runtime-install" -version = "0.73.1" -source = "git+https://github.com/Mesh-LLM/mesh-llm.git?rev=f455d493a2ae82baf2a326e2d0fda351433b4b30#f455d493a2ae82baf2a326e2d0fda351433b4b30" +version = "0.74.0" +source = "git+https://github.com/Mesh-LLM/mesh-llm.git?tag=v0.74.0#e60b2fe43aa05271569fbeff2a457133aef456a1" dependencies = [ "anyhow", "dirs", @@ -5332,8 +5349,8 @@ dependencies = [ [[package]] name = "mesh-llm-sdk" -version = "0.73.1" -source = "git+https://github.com/Mesh-LLM/mesh-llm.git?rev=f455d493a2ae82baf2a326e2d0fda351433b4b30#f455d493a2ae82baf2a326e2d0fda351433b4b30" +version = "0.74.0" +source = "git+https://github.com/Mesh-LLM/mesh-llm.git?tag=v0.74.0#e60b2fe43aa05271569fbeff2a457133aef456a1" dependencies = [ "anyhow", "mesh-llm-api-client", @@ -5347,8 +5364,8 @@ dependencies = [ [[package]] name = "mesh-llm-skills" -version = "0.73.1" -source = "git+https://github.com/Mesh-LLM/mesh-llm.git?rev=f455d493a2ae82baf2a326e2d0fda351433b4b30#f455d493a2ae82baf2a326e2d0fda351433b4b30" +version = "0.74.0" +source = "git+https://github.com/Mesh-LLM/mesh-llm.git?tag=v0.74.0#e60b2fe43aa05271569fbeff2a457133aef456a1" dependencies = [ "anyhow", "dirs", @@ -5358,8 +5375,8 @@ dependencies = [ [[package]] name = "mesh-llm-system" -version = "0.73.1" -source = "git+https://github.com/Mesh-LLM/mesh-llm.git?rev=f455d493a2ae82baf2a326e2d0fda351433b4b30#f455d493a2ae82baf2a326e2d0fda351433b4b30" +version = "0.74.0" +source = "git+https://github.com/Mesh-LLM/mesh-llm.git?tag=v0.74.0#e60b2fe43aa05271569fbeff2a457133aef456a1" dependencies = [ "anyhow", "chrono", @@ -5381,8 +5398,8 @@ dependencies = [ [[package]] name = "mesh-llm-types" -version = "0.73.1" -source = "git+https://github.com/Mesh-LLM/mesh-llm.git?rev=f455d493a2ae82baf2a326e2d0fda351433b4b30#f455d493a2ae82baf2a326e2d0fda351433b4b30" +version = "0.74.0" +source = "git+https://github.com/Mesh-LLM/mesh-llm.git?tag=v0.74.0#e60b2fe43aa05271569fbeff2a457133aef456a1" dependencies = [ "hex", "serde", @@ -5392,13 +5409,13 @@ dependencies = [ [[package]] name = "mesh-llm-ui" -version = "0.73.1" -source = "git+https://github.com/Mesh-LLM/mesh-llm.git?rev=f455d493a2ae82baf2a326e2d0fda351433b4b30#f455d493a2ae82baf2a326e2d0fda351433b4b30" +version = "0.74.0" +source = "git+https://github.com/Mesh-LLM/mesh-llm.git?tag=v0.74.0#e60b2fe43aa05271569fbeff2a457133aef456a1" [[package]] name = "mesh-mixture-of-agents" -version = "0.73.1" -source = "git+https://github.com/Mesh-LLM/mesh-llm.git?rev=f455d493a2ae82baf2a326e2d0fda351433b4b30#f455d493a2ae82baf2a326e2d0fda351433b4b30" +version = "0.74.0" +source = "git+https://github.com/Mesh-LLM/mesh-llm.git?tag=v0.74.0#e60b2fe43aa05271569fbeff2a457133aef456a1" dependencies = [ "async-trait", "mesh-llm-guardrails", @@ -5470,8 +5487,8 @@ dependencies = [ [[package]] name = "model-artifact" -version = "0.73.1" -source = "git+https://github.com/Mesh-LLM/mesh-llm.git?rev=f455d493a2ae82baf2a326e2d0fda351433b4b30#f455d493a2ae82baf2a326e2d0fda351433b4b30" +version = "0.74.0" +source = "git+https://github.com/Mesh-LLM/mesh-llm.git?tag=v0.74.0#e60b2fe43aa05271569fbeff2a457133aef456a1" dependencies = [ "anyhow", "async-trait", @@ -5481,8 +5498,8 @@ dependencies = [ [[package]] name = "model-hf" -version = "0.73.1" -source = "git+https://github.com/Mesh-LLM/mesh-llm.git?rev=f455d493a2ae82baf2a326e2d0fda351433b4b30#f455d493a2ae82baf2a326e2d0fda351433b4b30" +version = "0.74.0" +source = "git+https://github.com/Mesh-LLM/mesh-llm.git?tag=v0.74.0#e60b2fe43aa05271569fbeff2a457133aef456a1" dependencies = [ "anyhow", "async-trait", @@ -5499,8 +5516,8 @@ dependencies = [ [[package]] name = "model-package" -version = "0.73.1" -source = "git+https://github.com/Mesh-LLM/mesh-llm.git?rev=f455d493a2ae82baf2a326e2d0fda351433b4b30#f455d493a2ae82baf2a326e2d0fda351433b4b30" +version = "0.74.0" +source = "git+https://github.com/Mesh-LLM/mesh-llm.git?tag=v0.74.0#e60b2fe43aa05271569fbeff2a457133aef456a1" dependencies = [ "anyhow", "bytes", @@ -5519,16 +5536,16 @@ dependencies = [ [[package]] name = "model-ref" -version = "0.73.1" -source = "git+https://github.com/Mesh-LLM/mesh-llm.git?rev=f455d493a2ae82baf2a326e2d0fda351433b4b30#f455d493a2ae82baf2a326e2d0fda351433b4b30" +version = "0.74.0" +source = "git+https://github.com/Mesh-LLM/mesh-llm.git?tag=v0.74.0#e60b2fe43aa05271569fbeff2a457133aef456a1" dependencies = [ "serde", ] [[package]] name = "model-resolver" -version = "0.73.1" -source = "git+https://github.com/Mesh-LLM/mesh-llm.git?rev=f455d493a2ae82baf2a326e2d0fda351433b4b30#f455d493a2ae82baf2a326e2d0fda351433b4b30" +version = "0.74.0" +source = "git+https://github.com/Mesh-LLM/mesh-llm.git?tag=v0.74.0#e60b2fe43aa05271569fbeff2a457133aef456a1" dependencies = [ "anyhow", "model-artifact", @@ -6182,7 +6199,7 @@ version = "0.7.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "680998035259dcfcafe653688bf2aa6d3e2dc05e98be6ab46afb089dc84f1df8" dependencies = [ - "proc-macro-crate 3.5.0", + "proc-macro-crate 2.0.2", "proc-macro2", "quote", "syn 2.0.118", @@ -6556,8 +6573,8 @@ dependencies = [ [[package]] name = "openai-frontend" -version = "0.73.1" -source = "git+https://github.com/Mesh-LLM/mesh-llm.git?rev=f455d493a2ae82baf2a326e2d0fda351433b4b30#f455d493a2ae82baf2a326e2d0fda351433b4b30" +version = "0.74.0" +source = "git+https://github.com/Mesh-LLM/mesh-llm.git?tag=v0.74.0#e60b2fe43aa05271569fbeff2a457133aef456a1" dependencies = [ "async-trait", "axum", @@ -9120,8 +9137,8 @@ checksum = "8ee5873ec9cce0195efcb7a4e9507a04cd49aec9c83d0389df45b1ef7ba2e649" [[package]] name = "skippy-cache" -version = "0.73.1" -source = "git+https://github.com/Mesh-LLM/mesh-llm.git?rev=f455d493a2ae82baf2a326e2d0fda351433b4b30#f455d493a2ae82baf2a326e2d0fda351433b4b30" +version = "0.74.0" +source = "git+https://github.com/Mesh-LLM/mesh-llm.git?tag=v0.74.0#e60b2fe43aa05271569fbeff2a457133aef456a1" dependencies = [ "anyhow", "blake3", @@ -9130,29 +9147,29 @@ dependencies = [ [[package]] name = "skippy-coordinator" -version = "0.73.1" -source = "git+https://github.com/Mesh-LLM/mesh-llm.git?rev=f455d493a2ae82baf2a326e2d0fda351433b4b30#f455d493a2ae82baf2a326e2d0fda351433b4b30" +version = "0.74.0" +source = "git+https://github.com/Mesh-LLM/mesh-llm.git?tag=v0.74.0#e60b2fe43aa05271569fbeff2a457133aef456a1" dependencies = [ "thiserror 2.0.18", ] [[package]] name = "skippy-ffi" -version = "0.73.1" -source = "git+https://github.com/Mesh-LLM/mesh-llm.git?rev=f455d493a2ae82baf2a326e2d0fda351433b4b30#f455d493a2ae82baf2a326e2d0fda351433b4b30" +version = "0.74.0" +source = "git+https://github.com/Mesh-LLM/mesh-llm.git?tag=v0.74.0#e60b2fe43aa05271569fbeff2a457133aef456a1" dependencies = [ "libloading 0.8.9", ] [[package]] name = "skippy-metrics" -version = "0.73.1" -source = "git+https://github.com/Mesh-LLM/mesh-llm.git?rev=f455d493a2ae82baf2a326e2d0fda351433b4b30#f455d493a2ae82baf2a326e2d0fda351433b4b30" +version = "0.74.0" +source = "git+https://github.com/Mesh-LLM/mesh-llm.git?tag=v0.74.0#e60b2fe43aa05271569fbeff2a457133aef456a1" [[package]] name = "skippy-protocol" -version = "0.73.1" -source = "git+https://github.com/Mesh-LLM/mesh-llm.git?rev=f455d493a2ae82baf2a326e2d0fda351433b4b30#f455d493a2ae82baf2a326e2d0fda351433b4b30" +version = "0.74.0" +source = "git+https://github.com/Mesh-LLM/mesh-llm.git?tag=v0.74.0#e60b2fe43aa05271569fbeff2a457133aef456a1" dependencies = [ "prost", "prost-build", @@ -9162,8 +9179,8 @@ dependencies = [ [[package]] name = "skippy-runtime" -version = "0.73.1" -source = "git+https://github.com/Mesh-LLM/mesh-llm.git?rev=f455d493a2ae82baf2a326e2d0fda351433b4b30#f455d493a2ae82baf2a326e2d0fda351433b4b30" +version = "0.74.0" +source = "git+https://github.com/Mesh-LLM/mesh-llm.git?tag=v0.74.0#e60b2fe43aa05271569fbeff2a457133aef456a1" dependencies = [ "anyhow", "libc", @@ -9176,9 +9193,10 @@ dependencies = [ [[package]] name = "skippy-server" -version = "0.73.1" -source = "git+https://github.com/Mesh-LLM/mesh-llm.git?rev=f455d493a2ae82baf2a326e2d0fda351433b4b30#f455d493a2ae82baf2a326e2d0fda351433b4b30" +version = "0.74.0" +source = "git+https://github.com/Mesh-LLM/mesh-llm.git?tag=v0.74.0#e60b2fe43aa05271569fbeff2a457133aef456a1" dependencies = [ + "ahash", "anyhow", "async-trait", "axum", @@ -9204,8 +9222,8 @@ dependencies = [ [[package]] name = "skippy-topology" -version = "0.73.1" -source = "git+https://github.com/Mesh-LLM/mesh-llm.git?rev=f455d493a2ae82baf2a326e2d0fda351433b4b30#f455d493a2ae82baf2a326e2d0fda351433b4b30" +version = "0.74.0" +source = "git+https://github.com/Mesh-LLM/mesh-llm.git?tag=v0.74.0#e60b2fe43aa05271569fbeff2a457133aef456a1" dependencies = [ "serde", "serde_json", diff --git a/desktop/src-tauri/Cargo.toml b/desktop/src-tauri/Cargo.toml index 7606e48ac64..735a45c3b77 100644 --- a/desktop/src-tauri/Cargo.toml +++ b/desktop/src-tauri/Cargo.toml @@ -40,9 +40,15 @@ keyring = { version = "3.6.3", default-features = false, features = ["sync-secre # connection is dropped, which the plugin does immediately. Default features # keep the pure-Rust zbus backend, matching the plugin (no libdbus needed). notify-rust = "4" +# Enable getUserMedia in the WebKitGTK webview (see src/linux_media.rs). Pinned +# to the exact version wry links so both resolve to one webkit2gtk-sys and we +# don't get duplicate symbols; bump in lockstep with wry. +webkit2gtk = { version = "=2.0.2", features = ["v2_22"] } [target.'cfg(target_os = "macos")'.dependencies] -objc2-app-kit = { version = "0.3.2", default-features = false, features = ["NSHapticFeedback"] } +objc2 = { version = "0.6.4", default-features = false } +objc2-app-kit = { version = "0.3.2", default-features = false, features = ["NSHapticFeedback", "NSMenu", "NSMenuItem", "NSStatusItem"] } +objc2-foundation = { version = "0.3.2", default-features = false, features = ["NSProcessInfo", "NSString"] } keyring = { version = "3.6.3", default-features = false, features = ["apple-native", "vendored"], optional = true } security-framework = { version = "3.7.0", features = ["OSX_10_15"] } window-vibrancy = "0.6" @@ -58,7 +64,7 @@ user-idle = { version = "0.6", default-features = false } atomic-write-file = "0.3" anyhow = "1" dirs = "6" -tauri = { version = "2", features = ["macos-private-api"] } +tauri = { version = "2", features = ["macos-private-api", "tray-icon"] } tauri-plugin-deep-link = "2" tauri-plugin-opener = "2" tauri-plugin-single-instance = { version = "2", features = ["deep-link"] } @@ -90,14 +96,14 @@ buzz_persona_pkg = { package = "buzz-persona", path = "../../crates/buzz-persona buzz_sdk_pkg = { package = "buzz-sdk", path = "../../crates/buzz-sdk" } buzz_agent_pkg = { package = "buzz-agent", path = "../../crates/buzz-agent" } iroh = { version = "1.0.2", optional = true } -mesh-llm-sdk = { git = "https://github.com/Mesh-LLM/mesh-llm.git", rev = "f455d493a2ae82baf2a326e2d0fda351433b4b30", package = "mesh-llm-sdk", default-features = false, features = ["client", "serving"], optional = true } -mesh-llm-host-runtime = { git = "https://github.com/Mesh-LLM/mesh-llm.git", rev = "f455d493a2ae82baf2a326e2d0fda351433b4b30", package = "mesh-llm-host-runtime", default-features = false, features = ["dynamic-native-runtime"], optional = true } +mesh-llm-sdk = { git = "https://github.com/Mesh-LLM/mesh-llm.git", tag = "v0.74.0", package = "mesh-llm-sdk", default-features = false, features = ["client", "serving"], optional = true } +mesh-llm-host-runtime = { git = "https://github.com/Mesh-LLM/mesh-llm.git", tag = "v0.74.0", package = "mesh-llm-host-runtime", default-features = false, features = ["dynamic-native-runtime"], optional = true } # Model catalog + hardware survey for the Share-compute model picker (same # diagnose pattern as mesh-console). Lib name of mesh-llm-client is mesh_client. -mesh-llm-client = { git = "https://github.com/Mesh-LLM/mesh-llm.git", rev = "f455d493a2ae82baf2a326e2d0fda351433b4b30", package = "mesh-llm-client", optional = true } -mesh-llm-node = { git = "https://github.com/Mesh-LLM/mesh-llm.git", rev = "f455d493a2ae82baf2a326e2d0fda351433b4b30", package = "mesh-llm-node", optional = true } -mesh-llm-system = { git = "https://github.com/Mesh-LLM/mesh-llm.git", rev = "f455d493a2ae82baf2a326e2d0fda351433b4b30", package = "mesh-llm-system", optional = true } -mesh-llm-events = { git = "https://github.com/Mesh-LLM/mesh-llm.git", rev = "f455d493a2ae82baf2a326e2d0fda351433b4b30", package = "mesh-llm-events", optional = true } +mesh-llm-client = { git = "https://github.com/Mesh-LLM/mesh-llm.git", tag = "v0.74.0", package = "mesh-llm-client", optional = true } +mesh-llm-node = { git = "https://github.com/Mesh-LLM/mesh-llm.git", tag = "v0.74.0", package = "mesh-llm-node", optional = true } +mesh-llm-system = { git = "https://github.com/Mesh-LLM/mesh-llm.git", tag = "v0.74.0", package = "mesh-llm-system", optional = true } +mesh-llm-events = { git = "https://github.com/Mesh-LLM/mesh-llm.git", tag = "v0.74.0", package = "mesh-llm-events", optional = true } base64 = "0.22" sha2 = "0.11" tar = "0.4" diff --git a/desktop/src-tauri/src/commands/mesh_llm.rs b/desktop/src-tauri/src/commands/mesh_llm.rs index 305c54a2031..998bc6e7d28 100644 --- a/desktop/src-tauri/src/commands/mesh_llm.rs +++ b/desktop/src-tauri/src/commands/mesh_llm.rs @@ -5,12 +5,35 @@ use tauri::{AppHandle, Manager, State}; use crate::{app_state::AppState, mesh_llm, relay}; -#[derive(Debug, serde::Deserialize, serde::Serialize)] +#[derive(Clone, Debug, serde::Deserialize, serde::Serialize)] #[serde(rename_all = "camelCase")] struct MeshSharingConfig { enabled: bool, + /// A fresh Share Compute request that must cross a process boundary before + /// it can start. Consumed before startup so an interrupted download is not + /// resumed on a later launch. + #[serde(default)] + start_on_next_launch: bool, model_id: String, max_vram_gb: Option, + /// Community relay where Share Compute was explicitly enabled. Older + /// configs predate community binding and restore against the active relay. + #[serde(default)] + relay_url: Option, +} + +fn pending_new_start_checkpoint(config: &MeshSharingConfig) -> MeshSharingConfig { + let mut checkpoint = config.clone(); + checkpoint.enabled = false; + checkpoint.start_on_next_launch = false; + checkpoint +} + +fn one_shot_restart_checkpoint(config: &MeshSharingConfig) -> MeshSharingConfig { + let mut checkpoint = config.clone(); + checkpoint.enabled = false; + checkpoint.start_on_next_launch = true; + checkpoint } fn mesh_sharing_config_path(app: &AppHandle) -> Result { @@ -89,8 +112,10 @@ fn sharing_config_from_request( .ok_or_else(|| "modelId is required for serve mode".to_string())?; Ok(MeshSharingConfig { enabled: true, + start_on_next_launch: false, model_id: model_id.to_string(), max_vram_gb: request.max_vram_gb, + relay_url: request.relay_url.clone(), }) } @@ -117,7 +142,7 @@ fn restart_to_share( app: &AppHandle, config: &MeshSharingConfig, ) -> CmdResult { - save_mesh_sharing_config(app, config)?; + save_mesh_sharing_config(app, &one_shot_restart_checkpoint(config))?; let status = restarting_share_status(config); app.request_restart(); Ok(status) @@ -133,7 +158,7 @@ fn buzz_mesh_name_for_relay(relay_url: &str) -> String { format!("buzz-community-{}", &digest[..32]) } -fn buzz_mesh_name(state: &AppState) -> String { +pub(super) fn buzz_mesh_name(state: &AppState) -> String { buzz_mesh_name_for_relay(&relay::relay_ws_url_with_override(state)) } @@ -150,8 +175,13 @@ fn advance_mesh_status_cursor( Ok(cursor) } -async fn query_mesh_discovery_events(state: &AppState) -> Result, String> { - let mut events = relay::query_relay(state, &[mesh_llm::relay_membership_filter()]).await?; +async fn query_mesh_discovery_events_at( + state: &AppState, + relay_url: &str, +) -> Result, String> { + let api_base_url = relay::relay_http_base_url(relay_url); + let mut events = + relay::query_relay_at(state, &api_base_url, &[mesh_llm::relay_membership_filter()]).await?; let member_pubkeys = mesh_llm::current_member_pubkeys(&events); if member_pubkeys.is_empty() { // Distinguish "relay returned a membership snapshot listing zero @@ -172,7 +202,7 @@ async fn query_mesh_discovery_events(state: &AppState) -> Result = None; loop { - let page = relay::query_relay(state, &[status_filter.clone()]).await?; + let page = relay::query_relay_at(state, &api_base_url, &[status_filter.clone()]).await?; let done = page.len() < mesh_llm::MESH_STATUS_PAGE_SIZE; if !done { let cursor = advance_mesh_status_cursor(&mut status_filter, &page)?; @@ -188,6 +218,10 @@ async fn query_mesh_discovery_events(state: &AppState) -> Result Result, String> { + query_mesh_discovery_events_at(state, &relay::relay_ws_url_with_override(state)).await +} + /// Resolve the admission roster by intersecting member-signed mesh status /// reporters with the current NIP-43 direct-member list. /// @@ -201,6 +235,14 @@ pub(crate) async fn resolve_trusted_owner_ids(state: &AppState) -> Result Result, String> { + let events = query_mesh_discovery_events_at(state, relay_url).await?; + Ok(mesh_llm::owner_ids_from_events(&events)) +} + /// Resolve the roster for an initial node *start*, failing closed to self-only /// (an empty roster) when the relay query fails. This is safe only at start: /// there is no established allowlist to preserve yet. The periodic @@ -244,10 +286,11 @@ fn buzz_mesh_join_targets( /// Resolve the validated member endpoint this runtime should join to enter the /// existing Buzz community mesh. `Ok(None)` means this machine is the first /// live serving member (or is itself the shared bootstrap contact). -pub(crate) async fn resolve_buzz_mesh_join_targets( +pub(crate) async fn resolve_buzz_mesh_join_targets_at( state: &AppState, + relay_url: &str, ) -> Result, String> { - let events = query_mesh_discovery_events(state).await?; + let events = query_mesh_discovery_events_at(state, relay_url).await?; let self_owner_id = mesh_llm::ensure_owner_identity() .map_err(|error| format!("failed to load mesh owner identity: {error}"))? .owner_id; @@ -261,8 +304,11 @@ pub(crate) async fn resolve_buzz_mesh_join_targets( /// snapshot. A node start used to repeat the full membership + status query /// for each value, making Share Compute startup both slower and more exposed /// to inconsistent snapshots. -async fn resolve_buzz_mesh_startup(state: &AppState) -> (Vec, Option) { - match query_mesh_discovery_events(state).await { +async fn resolve_buzz_mesh_startup_at( + state: &AppState, + relay_url: &str, +) -> (Vec, Option) { + match query_mesh_discovery_events_at(state, relay_url).await { Ok(events) => { let trusted_owner_ids = mesh_llm::owner_ids_from_events(&events); let join_token = mesh_llm::ensure_owner_identity() @@ -291,32 +337,60 @@ async fn resolve_buzz_mesh_startup(state: &AppState) -> (Vec, Option CmdResult<()> { - let Some(config) = load_mesh_sharing_config(app)? else { + let Some(mut config) = load_mesh_sharing_config(app)? else { return Ok(()); }; - if !config.enabled || config.model_id.trim().is_empty() { + if (!config.enabled && !config.start_on_next_launch) || config.model_id.trim().is_empty() { return Ok(()); } + config.model_id = mesh_llm::canonical_curated_model_id(&config.model_id).to_string(); if state.mesh_llm_runtime.lock().await.is_some() { return Ok(()); } - let (trusted_owner_ids, join_token) = resolve_buzz_mesh_startup(state).await; + let relay_url = config + .relay_url + .clone() + .unwrap_or_else(|| relay::relay_ws_url_with_override(state)); + let (trusted_owner_ids, join_token) = resolve_buzz_mesh_startup_at(state, &relay_url).await; let mut runtime = state.mesh_llm_runtime.lock().await; if runtime.is_some() { return Ok(()); } + if config.start_on_next_launch { + // Consume a role-switch request before doing any potentially long model + // work. If Buzz exits during that work, the next launch stays stopped. + config = pending_new_start_checkpoint(&config); + save_mesh_sharing_config(app, &config)?; + } + // This is restoration of a previously inference-ready serving node. Keep + // the enabled checkpoint armed while restoring so a transient startup + // failure does not silently turn Share Compute off. New starts remain + // disarmed in `mesh_start_node` until their first inference probe passes. let request = mesh_llm::StartMeshNodeRequest { mode: mesh_llm::MeshNodeMode::Serve, - model_id: Some(config.model_id), + model_id: Some(config.model_id.clone()), max_vram_gb: config.max_vram_gb, join_token, - mesh_name: Some(buzz_mesh_name(state)), + mesh_name: Some(buzz_mesh_name_for_relay(&relay_url)), + relay_url: Some(relay_url), trusted_owner_ids: Some(trusted_owner_ids), }; let started = mesh_llm::DesktopMeshRuntime::start(request) .await .map_err(|error| format!("failed to restore Share Compute: {error:#}"))?; + if let Err(error) = wait_for_mesh_inference(&config.model_id).await { + let cleanup = started.stop().await; + if let Err(cleanup_error) = cleanup { + eprintln!( + "buzz-mesh: restored node failed inference readiness and cleanup was incomplete: {cleanup_error:#}" + ); + } + return Err(format!("failed to restore Share Compute: {error}")); + } *runtime = Some(started); + config.enabled = true; + config.start_on_next_launch = false; + save_mesh_sharing_config(app, &config)?; drop(runtime); mesh_llm::publish_current_status_once(app, "restore").await; Ok(()) @@ -328,6 +402,11 @@ pub async fn mesh_start_node( state: State<'_, AppState>, mut request: mesh_llm::StartMeshNodeRequest, ) -> CmdResult { + let relay_url = relay::relay_ws_url_with_override(&state); + request.relay_url = Some(relay_url.clone()); + if let Some(model_id) = request.model_id.as_mut() { + *model_id = mesh_llm::canonical_curated_model_id(model_id).to_string(); + } let sharing_config = if request.mode == mesh_llm::MeshNodeMode::Serve { Some(sharing_config_from_request(&request)?) } else { @@ -362,13 +441,14 @@ pub async fn mesh_start_node( // Frontend requests never carry a roster. Resolve it and the bootstrap // endpoint from one snapshot so UI startup does not repeat relay probes. if request.trusted_owner_ids.is_none() || request.join_token.is_none() { - let (trusted_owner_ids, join_token) = resolve_buzz_mesh_startup(&state).await; + let (trusted_owner_ids, join_token) = + resolve_buzz_mesh_startup_at(&state, &relay_url).await; request.trusted_owner_ids.get_or_insert(trusted_owner_ids); if request.join_token.is_none() { request.join_token = join_token; } } - request.mesh_name = Some(buzz_mesh_name(&state)); + request.mesh_name = Some(buzz_mesh_name_for_relay(&relay_url)); let mut runtime = state.mesh_llm_runtime.lock().await; let plan = match runtime.as_ref() { @@ -386,6 +466,13 @@ pub async fn mesh_start_node( return Err("mesh node is already running".to_string()); } + if let Some(config) = sharing_config.as_ref() { + // Do not arm launch restoration until the exact inference path used by + // agents succeeds. Mesh may bind its ports after primary weights load + // while package layers are still downloading. + save_mesh_sharing_config(&app, &pending_new_start_checkpoint(config))?; + } + let started = mesh_llm::DesktopMeshRuntime::start(request) .await .map_err(|error| format!("{error:#}"))?; @@ -409,6 +496,21 @@ pub async fn mesh_start_node( )); } }; + if let Some(config) = sharing_config.as_ref() { + if let Err(error) = wait_for_mesh_inference(&config.model_id).await { + let cleanup = started.stop().await; + if let Err(cleanup_error) = &cleanup { + eprintln!( + "buzz-mesh: started node failed inference readiness and cleanup was incomplete: {cleanup_error:#}" + ); + } + drop(runtime); + app.request_restart(); + return Err(format!( + "mesh node started but inference never became ready: {error}; Buzz is restarting to guarantee cleanup" + )); + } + } *runtime = Some(started); drop(runtime); if let Some(config) = sharing_config.as_ref() { @@ -612,6 +714,7 @@ pub(crate) async fn ensure_client_node_for_model( max_vram_gb: None, join_token: Some(join_token.clone()), mesh_name: Some(buzz_mesh_name(state)), + relay_url: Some(relay::relay_ws_url_with_override(state)), trusted_owner_ids: Some(resolve_trusted_owner_ids_or_self_only(state).await), }; let mut runtime = state.mesh_llm_runtime.lock().await; @@ -753,6 +856,18 @@ pub(crate) async fn ensure_relay_mesh_for_record( } } } + + // A persisted Share Compute configuration is authoritative about this + // machine's role. If no runtime is currently tracked (for example after a + // clean process restart), restore the serving node instead of treating an + // agent request as permission to replace it with a client node. + if load_mesh_sharing_config(app)? + .is_some_and(|config| config.enabled && !config.model_id.trim().is_empty()) + { + restore_mesh_sharing(app, &state).await?; + return wait_for_mesh_inference(model_id).await; + } + let target = match resolve_mesh_bootstrap_target(&state, model_id).await { Ok(Some(target)) => target, Ok(None) => { @@ -768,15 +883,9 @@ pub(crate) async fn ensure_relay_mesh_for_record( } }; - // Serve→Client re-arm transition (micspiral review #3, intentional-by-design): - // if the dead ingress belonged to a *serve* node with running consumer - // agents, this re-arms it as a Client (`MeshNodeMode::Client`). That is the - // correct/safe recovery here — config-backed serve restoration is - // `restore_mesh_sharing`'s job (`MeshNodeMode::Serve`), and - // `ensure_client_node_for_model` reuses any live runtime of *either* mode - // (the router resolves per-request), so it only cold-starts a Client when - // there is genuinely no runtime. Falling back to Client if a serve node - // crashed under local pressure is a desirable fail-safe, not a regression. + // No serving configuration exists, so this is a genuine consumer-only + // start. A configured serving machine is restored above and never reaches + // this client fallback. ensure_client_node_for_model(&state, model_id, Some(target.endpoint_addr)).await?; wait_for_mesh_inference(model_id).await } @@ -792,14 +901,17 @@ pub async fn mesh_stop_node( // role under the lock and, when it's a consume session, leave it running // and return its live status unchanged. The frontend also guards this, but // status can be stale between polls, so the backend is authoritative. - let taken = { + let (taken, bound_relay_url) = { let mut guard = state.mesh_llm_runtime.lock().await; if let Some(runtime) = guard.as_ref() { if !share_stop_should_teardown(runtime.mode()) { return runtime.status().await.map_err(|error| error.to_string()); } } - guard.take() + let bound_relay_url = guard + .as_ref() + .and_then(|runtime| runtime.start_request().relay_url.clone()); + (guard.take(), bound_relay_url) }; if let Some(runtime) = taken { runtime.stop().await.map_err(|error| error.to_string())?; @@ -808,11 +920,13 @@ pub async fn mesh_stop_node( &app, &MeshSharingConfig { enabled: false, + start_on_next_launch: false, model_id: String::new(), max_vram_gb: None, + relay_url: None, }, )?; - mesh_llm::publish_stopped_status_once(&app, "stop").await; + mesh_llm::publish_stopped_status_once_at(&app, bound_relay_url.as_deref(), "stop").await; Ok(mesh_llm::stopped_status()) } diff --git a/desktop/src-tauri/src/commands/mesh_llm_tests.rs b/desktop/src-tauri/src/commands/mesh_llm_tests.rs index ccc5287d62f..26eb1f5fbae 100644 --- a/desktop/src-tauri/src/commands/mesh_llm_tests.rs +++ b/desktop/src-tauri/src/commands/mesh_llm_tests.rs @@ -110,6 +110,74 @@ fn buzz_mesh_name_is_stable_and_does_not_expose_the_relay() { assert!(!first.contains("example")); } +#[test] +fn sharing_config_keeps_the_community_where_sharing_was_enabled() { + let request = mesh_llm::StartMeshNodeRequest { + mode: mesh_llm::MeshNodeMode::Serve, + model_id: Some("test-model".to_string()), + max_vram_gb: Some(24), + join_token: None, + mesh_name: Some("buzz-community-test".to_string()), + relay_url: Some("wss://community.example".to_string()), + trusted_owner_ids: Some(Vec::new()), + }; + + let config = sharing_config_from_request(&request).expect("valid sharing config"); + assert_eq!(config.relay_url.as_deref(), Some("wss://community.example")); +} + +#[test] +fn legacy_sharing_config_without_community_binding_still_loads() { + let config: MeshSharingConfig = serde_json::from_value(serde_json::json!({ + "enabled": true, + "modelId": "test-model", + "maxVramGb": null + })) + .expect("legacy sharing config"); + + assert_eq!(config.relay_url, None); + assert!(!config.start_on_next_launch); +} + +#[test] +fn new_start_checkpoint_prevents_incomplete_download_restore() { + let config = MeshSharingConfig { + enabled: true, + start_on_next_launch: false, + model_id: "test-model".to_string(), + max_vram_gb: Some(24), + relay_url: Some("wss://community.example".to_string()), + }; + + let checkpoint = pending_new_start_checkpoint(&config); + assert!(!checkpoint.enabled); + assert!(!checkpoint.start_on_next_launch); + assert_eq!(checkpoint.model_id, config.model_id); + assert_eq!(checkpoint.max_vram_gb, config.max_vram_gb); + assert_eq!(checkpoint.relay_url, config.relay_url); +} + +#[test] +fn role_switch_checkpoint_starts_exactly_once_after_restart() { + let config = MeshSharingConfig { + enabled: true, + start_on_next_launch: false, + model_id: "test-model".to_string(), + max_vram_gb: Some(24), + relay_url: Some("wss://community.example".to_string()), + }; + + let restart = one_shot_restart_checkpoint(&config); + assert!(!restart.enabled); + assert!(restart.start_on_next_launch); + + let consumed = pending_new_start_checkpoint(&restart); + assert!(!consumed.enabled); + assert!(!consumed.start_on_next_launch); + assert_eq!(consumed.model_id, config.model_id); + assert_eq!(consumed.relay_url, config.relay_url); +} + #[test] fn readiness_failure_is_catalog_sync_when_model_never_visible() { assert_eq!( @@ -345,6 +413,7 @@ fn ensure_serve_runtime_serves_other_model() { max_vram_gb: None, join_token: None, mesh_name: None, + relay_url: None, trusted_owner_ids: None, }) .await diff --git a/desktop/src-tauri/src/lib.rs b/desktop/src-tauri/src/lib.rs index 213d9413e83..e9bdc4d35cf 100644 --- a/desktop/src-tauri/src/lib.rs +++ b/desktop/src-tauri/src/lib.rs @@ -7,6 +7,7 @@ mod deep_link; mod event_sync; mod events; mod huddle; +mod linux_media; mod managed_agents; mod media_proxy; #[cfg(feature = "mesh-llm")] @@ -30,6 +31,8 @@ mod reset; mod secret_store; mod shutdown; mod templates; +#[cfg(target_os = "macos")] +mod tray_menu; mod util; #[cfg(target_os = "linux")] pub mod webkit_rendering; @@ -65,10 +68,12 @@ use std::sync::{ atomic::{AtomicBool, Ordering}, Arc, }; -#[cfg(target_os = "macos")] -use tauri::Listener; use tauri::{Emitter, Manager, RunEvent}; +#[cfg(target_os = "macos")] +use tauri::{Listener, WindowEvent}; use tauri_plugin_window_state::StateFlags; +#[cfg(target_os = "macos")] +use tray_menu::show_main_window; #[cfg(target_os = "macos")] const INITIAL_RENDER_READY_EVENT: &str = "initial-render-ready"; @@ -197,6 +202,11 @@ pub fn run() { return; } + // Linux/WebKitGTK needs media-stream settings and a + // permission-request handler for getUserMedia; no-op + // on macOS/Windows. + linux_media::enable_media_capture(&webview); + // macOS applies the restored geometry asynchronously. Wait // for several identical outer bounds and for React to // commit the startup surface before revealing it. @@ -362,6 +372,8 @@ pub fn run() { .manage(commands::pairing::PairingHandle::new()) .setup(move |app| { let app_handle = app.handle().clone(); + #[cfg(target_os = "macos")] + tray_menu::init(&app_handle)?; // ── Phase 2: boot-time sentinel wipe ────────────────────────────── // Must run before migrations and identity resolution so the wipe @@ -897,6 +909,14 @@ pub fn run() { archive::read_unindexed_observer_rows, is_auto_update_supported, set_window_vibrancy, + #[cfg(target_os = "macos")] + tray_menu::clear_tray_agent_activity, + #[cfg(target_os = "macos")] + tray_menu::requeue_tray_actions, + #[cfg(target_os = "macos")] + tray_menu::take_tray_actions, + #[cfg(target_os = "macos")] + tray_menu::update_tray_agent_activity, ]) .build(tauri::generate_context!()) .expect("error while building tauri application"); @@ -909,6 +929,22 @@ pub fn run() { let run_shutdown_done = Arc::clone(&shutdown_done); let restart_requested = Arc::new(AtomicBool::new(false)); app.run(move |app_handle, event| match event { + #[cfg(target_os = "macos")] + RunEvent::Reopen { .. } => show_main_window(app_handle), + #[cfg(target_os = "macos")] + RunEvent::WindowEvent { + label, + event: WindowEvent::CloseRequested { api, .. }, + .. + } if label == "main" => { + // Keep the webview alive so Buzz can be reopened from its tray menu. + api.prevent_close(); + if let Some(window) = app_handle.get_webview_window("main") { + if let Err(error) = window.hide() { + eprintln!("buzz-desktop: failed to hide main window: {error}"); + } + } + } RunEvent::ExitRequested { code, .. } => { if is_restart_request(code) { restart_requested.store(true, Ordering::SeqCst); diff --git a/desktop/src-tauri/src/linux_media.rs b/desktop/src-tauri/src/linux_media.rs new file mode 100644 index 00000000000..c768e154227 --- /dev/null +++ b/desktop/src-tauri/src/linux_media.rs @@ -0,0 +1,141 @@ +//! Linux-only: enable media capture (`getUserMedia`) in the WebKitGTK webview. +//! +//! On macOS (WKWebView) and Windows (WebView2) the media-permission prompt is +//! routed to the OS automatically, so microphone/camera capture "just works". +//! WebKitGTK is different on two counts, and both must be handled or capture +//! fails on Linux only: +//! +//! * `enable-media-stream` is **off by default**, so `navigator.mediaDevices` +//! never exposes a working `getUserMedia`; and +//! * the default `permission-request` handler **denies every request**, so even +//! with media-stream on, the call rejects with `NotAllowedError`. +//! +//! This module reaches the underlying `webkit2gtk::WebView` via +//! [`tauri::Webview::with_webview`], enables media-stream, and installs a +//! `permission-request` handler that is **deny-by-default**: a `UserMedia` +//! request is allowed only when it comes from a trusted app origin and asks for +//! an audio and/or video device. Tauri does not restrict navigation by default, +//! so without the origin check any document that ended up in this webview would +//! inherit silent mic/camera access for the process lifetime. +//! +//! Buzz's AppImage pins `GDK_BACKEND=x11` (see [`crate::webkit_rendering`]), +//! which is the backend WebKitGTK media capture is reliable on. + +/// The origin Tauri serves the packaged app from on Linux. +const PROD_ORIGIN: &str = "tauri://localhost"; + +/// The Vite dev-server origin (`devUrl` in `tauri.conf.json`, `strictPort` +/// 1420 in `vite.config.ts`). Only trusted in debug builds. +#[cfg(debug_assertions)] +const DEV_ORIGIN: &str = "http://localhost:1420"; + +/// Whether `uri` (the webview's current document URI) is a trusted app origin +/// allowed to use mic/camera. Matches the origin exactly or as a path prefix so +/// `tauri://localhost.evil.com` and `http://localhost:14200` do not slip +/// through. Pure and platform-independent so it can be unit-tested everywhere. +fn is_trusted_media_origin(uri: &str) -> bool { + fn matches(uri: &str, origin: &str) -> bool { + uri == origin + || uri + .strip_prefix(origin) + .is_some_and(|rest| rest.starts_with('/')) + } + + if matches(uri, PROD_ORIGIN) { + return true; + } + #[cfg(debug_assertions)] + if matches(uri, DEV_ORIGIN) { + return true; + } + false +} + +/// Enable microphone/camera capture for `webview` if it is running on +/// WebKitGTK. A no-op on every non-Linux target, so callers can invoke it +/// unconditionally from shared startup code. +#[cfg(target_os = "linux")] +pub fn enable_media_capture(webview: &tauri::Webview) { + use webkit2gtk::{ + glib::prelude::Cast, PermissionRequestExt, SettingsExt, UserMediaPermissionRequest, + UserMediaPermissionRequestExt, WebViewExt, + }; + + // `with_webview` runs the closure on the UI thread, which GTK calls + // require. It errors only if the platform webview is unavailable. + let result = webview.with_webview(|platform_webview| { + // On Linux this is the underlying `webkit2gtk::WebView`. + let webview = platform_webview.inner(); + + if let Some(settings) = WebViewExt::settings(&webview) { + settings.set_enable_media_stream(true); + } + + // Deny-by-default: allow only mic/camera requests from a trusted app + // origin; deny everything else (still returning `true` so WebKit's + // auto-deny default does not also run). Non-`UserMedia` requests return + // `false` and keep their default handling. + webview.connect_permission_request(|wv, request| { + let Some(request) = request.downcast_ref::() else { + return false; + }; + + let uri = wv.uri().map(|u| u.to_string()).unwrap_or_default(); + let for_device = request.is_for_audio_device() || request.is_for_video_device(); + + if for_device && is_trusted_media_origin(&uri) { + request.allow(); + } else { + request.deny(); + } + true + }); + }); + + if let Err(error) = result { + eprintln!("buzz-desktop: could not enable WebKitGTK media capture: {error}"); + } +} + +/// No-op stub so shared startup code can call [`enable_media_capture`] on every +/// platform. macOS and Windows route media permissions through the OS. +#[cfg(not(target_os = "linux"))] +pub fn enable_media_capture(_webview: &tauri::Webview) {} + +#[cfg(test)] +mod tests { + use super::is_trusted_media_origin; + + #[test] + fn allows_production_app_origin() { + assert!(is_trusted_media_origin("tauri://localhost")); + assert!(is_trusted_media_origin( + "tauri://localhost/channels/general" + )); + } + + #[test] + fn denies_untrusted_origins() { + assert!(!is_trusted_media_origin("")); + assert!(!is_trusted_media_origin("https://evil.example.com")); + // Prefix look-alikes must not slip through. + assert!(!is_trusted_media_origin("tauri://localhost.evil.com")); + assert!(!is_trusted_media_origin("tauri://localhostfoo")); + } + + #[cfg(debug_assertions)] + #[test] + fn allows_dev_origin_in_debug_only() { + assert!(is_trusted_media_origin("http://localhost:1420")); + assert!(is_trusted_media_origin("http://localhost:1420/")); + // A different localhost port is still untrusted. + assert!(!is_trusted_media_origin("http://localhost:14200")); + assert!(!is_trusted_media_origin("http://localhost:3000")); + } + + #[cfg(not(debug_assertions))] + #[test] + fn denies_dev_origin_in_release() { + assert!(!is_trusted_media_origin("http://localhost:1420")); + } +} diff --git a/desktop/src-tauri/src/managed_agents/relay_mesh.rs b/desktop/src-tauri/src/managed_agents/relay_mesh.rs index 7a6f5b094a9..327c106bc88 100644 --- a/desktop/src-tauri/src/managed_agents/relay_mesh.rs +++ b/desktop/src-tauri/src/managed_agents/relay_mesh.rs @@ -42,15 +42,51 @@ pub fn apply_relay_mesh_env( RELAY_MESH_PREFER_MESH_FOR_AUTO_ENV.to_string(), "1".to_string(), ); - // Keep the requested response inside smaller local-model context windows, - // and spend that budget on an answer/tool call instead of hidden reasoning. - // Without both settings Qwen3 either fails the router's fit check at the - // agent default (32K) or can consume a tight cap before serializing a tool. - env.insert( - "BUZZ_AGENT_MAX_OUTPUT_TOKENS".to_string(), - "4096".to_string(), - ); - env.insert("BUZZ_AGENT_THINKING_EFFORT".to_string(), "none".to_string()); + // Keep the requested response inside smaller local-model context windows. + // These are defaults, not policy: the effective agent/persona/global env + // may deliberately choose a smaller cap or a different effort. This function + // runs after those layers during readiness, so never clobber their values. + insert_default_if_unset(env, "BUZZ_AGENT_MAX_OUTPUT_TOKENS", "4096"); + // Deliberately no BUZZ_AGENT_THINKING_EFFORT default: mesh translates + // `reasoning_effort` into the chat template's `enable_thinking` flag, so any + // value we pick overrides each model's own template default — and the right + // value is model-specific. Measured with the real prompt and toolset: + // gemma-4-E4B delivers 0/8 at `none` but 6/6 with the field absent, while + // Qwen3-8B delivers 8/8 either way and burns ~4x the output tokens once + // thinking is on (121 -> ~470), risking the 4096 cap. Omitting the field + // lets every model use its own default; explicit agent/persona/global + // values still apply. +} + +#[cfg(feature = "mesh-llm")] +fn insert_default_if_unset( + env: &mut std::collections::BTreeMap, + key: &str, + value: &str, +) { + if env.get(key).is_none_or(|current| current.trim().is_empty()) { + env.insert(key.to_string(), value.to_string()); + } +} + +/// Build the final Mesh-specific process overrides from the already-resolved +/// harness environment. Only user-owned generation controls are seeded: the +/// derived provider/base URL/model values remain authoritative, and unrelated +/// credentials (notably `OPENAI_API_KEY`) must not be copied back after the +/// spawn path removes them. +#[cfg(feature = "mesh-llm")] +pub fn relay_mesh_process_env( + effective_env: &std::collections::BTreeMap, + model: &str, +) -> std::collections::BTreeMap { + let mut env = std::collections::BTreeMap::new(); + for key in ["BUZZ_AGENT_MAX_OUTPUT_TOKENS", "BUZZ_AGENT_THINKING_EFFORT"] { + if let Some(value) = effective_env.get(key) { + env.insert(key.to_string(), value.clone()); + } + } + apply_relay_mesh_env(&mut env, Some(RELAY_MESH_PROVIDER_ID), Some(model)); + env } #[cfg(all(test, feature = "mesh-llm"))] @@ -60,7 +96,7 @@ mod tests { use super::*; #[test] - fn native_provider_uses_context_safe_non_reasoning_budget() { + fn native_provider_uses_context_safe_tool_calling_budget() { let mut env = BTreeMap::new(); apply_relay_mesh_env( &mut env, @@ -72,14 +108,63 @@ mod tests { env.get("BUZZ_AGENT_MAX_OUTPUT_TOKENS").map(String::as_str), Some("4096") ); - assert_eq!( - env.get("BUZZ_AGENT_THINKING_EFFORT").map(String::as_str), - Some("none") - ); + // Must stay unset: any value we pick overrides the model's own chat + // template default, and the right value is model-specific ("none" + // stops gemma tool-calling; enabling thinking makes Qwen3 burn ~4x the + // output budget). + assert_eq!(env.get("BUZZ_AGENT_THINKING_EFFORT"), None); assert_eq!( env.get(RELAY_MESH_PREFER_MESH_FOR_AUTO_ENV) .map(String::as_str), Some("1") ); } + + #[test] + fn native_provider_preserves_explicit_generation_controls() { + let mut env = BTreeMap::from([ + ( + "BUZZ_AGENT_MAX_OUTPUT_TOKENS".to_string(), + "2048".to_string(), + ), + ("BUZZ_AGENT_THINKING_EFFORT".to_string(), "high".to_string()), + ]); + apply_relay_mesh_env( + &mut env, + Some(RELAY_MESH_PROVIDER_ID), + Some(RELAY_MESH_AUTO_MODEL_ID), + ); + + assert_eq!( + env.get("BUZZ_AGENT_MAX_OUTPUT_TOKENS").map(String::as_str), + Some("2048") + ); + assert_eq!( + env.get("BUZZ_AGENT_THINKING_EFFORT").map(String::as_str), + Some("high") + ); + } + + #[test] + fn process_env_seeds_controls_without_restoring_unrelated_credentials() { + let effective_env = BTreeMap::from([ + ( + "BUZZ_AGENT_MAX_OUTPUT_TOKENS".to_string(), + "1024".to_string(), + ), + ("OPENAI_API_KEY".to_string(), "must-not-leak".to_string()), + ]); + + let env = relay_mesh_process_env(&effective_env, "Gemma-4"); + + assert_eq!( + env.get("BUZZ_AGENT_MAX_OUTPUT_TOKENS").map(String::as_str), + Some("1024") + ); + assert_eq!( + env.get("OPENAI_COMPAT_MODEL").map(String::as_str), + Some("Gemma-4") + ); + assert!(!env.contains_key("OPENAI_API_KEY")); + } } diff --git a/desktop/src-tauri/src/managed_agents/runtime.rs b/desktop/src-tauri/src/managed_agents/runtime.rs index f3b4cb67fd5..37927961ed4 100644 --- a/desktop/src-tauri/src/managed_agents/runtime.rs +++ b/desktop/src-tauri/src/managed_agents/runtime.rs @@ -869,12 +869,7 @@ pub fn spawn_agent_child( // uses the same trim semantics as the preflight callers. #[cfg(feature = "mesh-llm")] if let Some(ref mesh_model_id) = mesh_model_id { - let mut mesh_env = std::collections::BTreeMap::new(); - super::apply_relay_mesh_env( - &mut mesh_env, - Some(super::RELAY_MESH_PROVIDER_ID), - Some(mesh_model_id.as_str()), - ); + let mesh_env = super::relay_mesh_process_env(&descriptor.env, mesh_model_id); command.env_remove("OPENAI_API_KEY"); for (key, value) in mesh_env { command.env(key, value); diff --git a/desktop/src-tauri/src/mesh_llm/catalog.rs b/desktop/src-tauri/src/mesh_llm/catalog.rs index 385971cb86c..1a11fcfcd13 100644 --- a/desktop/src-tauri/src/mesh_llm/catalog.rs +++ b/desktop/src-tauri/src/mesh_llm/catalog.rs @@ -19,12 +19,14 @@ use mesh_llm_system::vram::{format_rated_capacity, rated_capacity_gb}; /// The large pick is resolved through mesh-llm's remote catalog /// (huggingface.co/datasets/meshllm/catalog), so it does not need to exist in /// the compiled `MODEL_CATALOG`; the entry is synthesized below. -const CURATED_LARGE: &str = "gemma-4-26B-A4B-it-UD-Q4_K_M"; +const CURATED_LARGE: &str = "unsloth/gemma-4-26B-A4B-it-GGUF:UD-Q4_K_M"; +const CURATED_LARGE_ALIAS: &str = "gemma-4-26B-A4B-it-UD-Q4_K_M"; const CURATED_LARGE_SIZE: &str = "17GB"; const CURATED_LARGE_FILE: &str = "gemma-4-26B-A4B-it-UD-Q4_K_M.gguf"; const CURATED_LARGE_DESCRIPTION: &str = "Gemma 4 26B MoE (4B active) — Buzz default for 64GB+ machines"; -const CURATED_SMALL: &str = "Gemma-4-E4B-it-Q4_K_M"; +const CURATED_SMALL: &str = "unsloth/gemma-4-E4B-it-GGUF:Q4_K_M"; +const CURATED_SMALL_ALIAS: &str = "Gemma-4-E4B-it-Q4_K_M"; /// Rated-capacity boundary between the two curated tiers, in GB (marketing /// capacity — a "64GB" Mac rates as 64 even though usable AI memory is less). const CURATED_LARGE_MIN_RATED_GB: u64 = 64; @@ -37,6 +39,16 @@ fn buzz_recommended_model(rated_gb: Option) -> &'static str { } } +/// Convert Buzz's pre-0.74 curated package aliases into the canonical model +/// ids advertised and accepted by Mesh's OpenAI ingress. +pub(crate) fn canonical_curated_model_id(model_id: &str) -> &str { + match model_id.trim() { + CURATED_SMALL_ALIAS => CURATED_SMALL, + CURATED_LARGE_ALIAS => CURATED_LARGE, + other => other, + } +} + /// How a model sits inside this machine's usable AI memory. /// Mirrors mesh-llm's private `fit_code_for_size_label` thresholds. #[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)] @@ -146,12 +158,13 @@ fn build_catalog( .filter(|m| !is_draft_only(&m.name)) .map(|m| { let size_gb = parse_size_gb(&m.size); + let name = canonical_curated_model_id(&m.name).to_string(); MeshCatalogEntry { fit: fit_code(size_gb, vram_gb), - installed: is_installed(&m.file, &m.name), + installed: is_installed(&m.file, &name) || is_installed(&m.file, &m.name), recommended: false, curated: false, - name: m.name.clone(), + name, size: m.size.clone(), size_gb, description: m.description.clone(), @@ -166,7 +179,8 @@ fn build_catalog( let size_gb = parse_size_gb(CURATED_LARGE_SIZE); entries.push(MeshCatalogEntry { fit: fit_code(size_gb, vram_gb), - installed: is_installed(CURATED_LARGE_FILE, CURATED_LARGE), + installed: is_installed(CURATED_LARGE_FILE, CURATED_LARGE) + || is_installed(CURATED_LARGE_FILE, CURATED_LARGE_ALIAS), recommended: false, curated: false, name: CURATED_LARGE.to_string(), @@ -256,6 +270,8 @@ mod tests { #[test] fn recommendation_follows_buzz_curated_tiers() { + assert_eq!(CURATED_SMALL, "unsloth/gemma-4-E4B-it-GGUF:Q4_K_M"); + assert_eq!(CURATED_LARGE, "unsloth/gemma-4-26B-A4B-it-GGUF:UD-Q4_K_M"); // 64GB+ rated machines get the large curated pick. let large = build_catalog(None, 64_000_000_000, 64.0, &[]); assert_eq!(large.recommended.as_deref(), Some(CURATED_LARGE)); @@ -269,6 +285,22 @@ mod tests { assert_eq!(tiny.recommended.as_deref(), Some(CURATED_SMALL)); } + #[test] + fn curated_package_aliases_migrate_to_openai_model_ids() { + assert_eq!( + canonical_curated_model_id(CURATED_SMALL_ALIAS), + CURATED_SMALL + ); + assert_eq!( + canonical_curated_model_id(CURATED_LARGE_ALIAS), + CURATED_LARGE + ); + assert_eq!( + canonical_curated_model_id("other/model:Q4"), + "other/model:Q4" + ); + } + #[test] fn curated_picks_lead_the_catalog() { let catalog = build_catalog(None, 96_000_000_000, 96.0, &[]); diff --git a/desktop/src-tauri/src/mesh_llm/coordinator.rs b/desktop/src-tauri/src/mesh_llm/coordinator.rs index 1e279353b62..066fa463730 100644 --- a/desktop/src-tauri/src/mesh_llm/coordinator.rs +++ b/desktop/src-tauri/src/mesh_llm/coordinator.rs @@ -132,7 +132,7 @@ pub async fn start_coordinator(app: AppHandle) { /// MeshLLM establishes the encrypted peer transport itself. async fn reconcile_buzz_mesh_join(app: &AppHandle) -> Result<(), String> { let state = app.state::(); - let peer_ids = { + let (peer_ids, relay_url) = { let runtime = state.mesh_llm_runtime.lock().await; let Some(runtime) = runtime.as_ref() else { return Ok(()); @@ -141,10 +141,16 @@ async fn reconcile_buzz_mesh_join(app: &AppHandle) -> Result<(), String> { .status_report_payload() .await .map_err(|error| error.to_string())?; - visible_peer_ids(&payload) + let relay_url = runtime + .start_request() + .relay_url + .clone() + .unwrap_or_else(|| crate::relay::relay_ws_url_with_override(&state)); + (visible_peer_ids(&payload), relay_url) }; - let targets = crate::commands::mesh_llm::resolve_buzz_mesh_join_targets(&state).await?; + let targets = + crate::commands::mesh_llm::resolve_buzz_mesh_join_targets_at(&state, &relay_url).await?; let Some(target) = targets .into_iter() .find(|target| !target_is_visible(target, &peer_ids)) @@ -201,8 +207,13 @@ fn target_is_visible(target: &crate::mesh_llm::MeshServeTarget, peer_ids: &[Stri enum RosterReconcileAction { /// Keep the running allowlist untouched (no-op, or a failure we ride out). Keep, - /// Restart the node with a freshly resolved roster. - Restart(Vec), + /// Restart Buzz so MeshLLM is rebuilt with a freshly resolved roster. + /// + /// MeshLLM's native listeners are process-owned in practice: stopping and + /// starting the embedded runtime in one process can terminate Buzz or race + /// ports 9337/3131. The process boundary is therefore part of the safety + /// contract, not an implementation detail. + RestartProcess, /// Observed a *shrink* (or empty) once. Hold the current allowlist and /// require the same reduced roster on the next poll before tearing down, /// so a single transient short-read never drops a member mid-inference. @@ -224,9 +235,9 @@ fn roster_shrinks(current: &[String], fresh: &[String]) -> bool { /// Rules: /// - query failed (`Err`) → `Keep` (never de-admit on a relay blip) /// - resolved roster == current → `Keep` (no-op) -/// - grows (only additions) → `Restart` immediately (fast admission) +/// - grows (only additions) → `RestartProcess` immediately (fast admission) /// - shrinks/empties, first observation → `AwaitConfirm` (hold, re-check next poll) -/// - shrinks/empties, confirmed → `Restart` (same reduced roster twice) +/// - shrinks/empties, confirmed → `RestartProcess` (same reduced roster twice) fn roster_reconcile_action( current_owners: &[String], pending_shrink: Option<&[String]>, @@ -248,13 +259,13 @@ fn roster_reconcile_action( // Growth (pure additions) is safe to apply immediately. if !roster_shrinks(current_owners, &fresh) { - return RosterReconcileAction::Restart(fresh); + return RosterReconcileAction::RestartProcess; } // A shrink (including down to empty) must be confirmed across two // consecutive polls with the *same* reduced roster before we tear down. match pending_shrink { - Some(pending) if pending == fresh => RosterReconcileAction::Restart(fresh), + Some(pending) if pending == fresh => RosterReconcileAction::RestartProcess, _ => RosterReconcileAction::AwaitConfirm(fresh), } } @@ -283,8 +294,13 @@ async fn reconcile_roster( // other member on a transient relay blip (the flapping restart loop). Keep // the current allowlist and try again on the next poll. A shrink is held // for one extra poll (hysteresis) so a single short-read never tears down. - let query = crate::commands::mesh_llm::resolve_trusted_owner_ids(&state).await; - let fresh = match roster_reconcile_action(current_owners, pending_shrink.as_deref(), query) { + let relay_url = current_request + .relay_url + .as_deref() + .map(str::to_owned) + .unwrap_or_else(|| crate::relay::relay_ws_url_with_override(&state)); + let query = crate::commands::mesh_llm::resolve_trusted_owner_ids_at(&state, &relay_url).await; + match roster_reconcile_action(current_owners, pending_shrink.as_deref(), query) { RosterReconcileAction::Keep => { *pending_shrink = None; return Ok(()); @@ -294,34 +310,12 @@ async fn reconcile_roster( *pending_shrink = Some(reduced); return Ok(()); } - RosterReconcileAction::Restart(fresh) => { + RosterReconcileAction::RestartProcess => { *pending_shrink = None; - fresh } - }; + } - let mut request = current_request.clone(); - request.trusted_owner_ids = Some(fresh); - // Bootstrap endpoints are live device state, not configuration. The - // endpoint used at the previous start may belong to the member that just - // left or to a device whose iroh identity rotated while offline. Resolve a - // fresh validated peer for this restart; starting isolated is safe because - // the join watcher will converge it when a member next publishes. - request.join_token = match crate::commands::mesh_llm::resolve_buzz_mesh_join_targets(&state) - .await - { - Ok(targets) => targets - .into_iter() - .next() - .map(|target| target.endpoint_addr), - Err(error) => { - eprintln!( - "buzz-mesh: could not refresh bootstrap endpoint for roster restart; starting isolated: {error}" - ); - None - } - }; - let mut guard = state.mesh_llm_runtime.lock().await; + let guard = state.mesh_llm_runtime.lock().await; let startup_pending = match guard.as_ref() { Some(runtime) => runtime.is_starting().await, None => false, @@ -342,24 +336,14 @@ async fn reconcile_roster( // snapshot. return Ok(()); } - let Some(running) = guard.take() else { + if guard.is_none() { return Ok(()); - }; - eprintln!("buzz-mesh: membership roster changed; restarting mesh node with fresh allowlist"); - if let Err(error) = running.stop().await { - drop(guard); - eprintln!( - "buzz-mesh: stopping mesh node for roster restart failed; restarting Buzz instead of racing the occupied ingress: {error}" - ); - app.request_restart(); - return Err(format!( - "mesh node shutdown failed during roster change: {error}" - )); } - let replacement = crate::mesh_llm::DesktopMeshRuntime::start(request) - .await - .map_err(|error| format!("mesh node restart after roster change failed: {error:#}"))?; - *guard = Some(replacement); + drop(guard); + eprintln!( + "buzz-mesh: membership roster changed; restarting Buzz to rebuild MeshLLM with the fresh community allowlist" + ); + app.request_restart(); Ok(()) } @@ -377,11 +361,15 @@ pub(crate) async fn publish_current_status_once(app: &AppHandle, reason: &str) { } } -pub(crate) async fn publish_stopped_status_once(app: &AppHandle, reason: &str) { +pub(crate) async fn publish_stopped_status_once_at( + app: &AppHandle, + relay_url: Option<&str>, + reason: &str, +) { let state = app.state::(); match tokio::time::timeout( STATUS_PUBLISH_TIMEOUT, - publish_stopped_status_for_state(&state), + publish_stopped_status_for_state(&state, relay_url), ) .await { @@ -396,26 +384,43 @@ pub(crate) async fn publish_stopped_status_once(app: &AppHandle, reason: &str) { async fn publish_current_status_for_state(state: &AppState) -> Result<(), String> { let identity = super::ensure_owner_identity() .map_err(|error| format!("failed to load mesh owner identity: {error}"))?; - let mut payload = { + let (mut payload, relay_url) = { let runtime = state.mesh_llm_runtime.lock().await; match runtime.as_ref() { - Some(runtime) => runtime - .status_report_payload() - .await - .map_err(|error| error.to_string())?, - None => stopped_status_payload(&identity), + Some(runtime) => { + let payload = runtime + .status_report_payload() + .await + .map_err(|error| error.to_string())?; + let relay_url = runtime + .start_request() + .relay_url + .clone() + .unwrap_or_else(|| crate::relay::relay_ws_url_with_override(state)); + (payload, relay_url) + } + None => ( + stopped_status_payload(&identity), + crate::relay::relay_ws_url_with_override(state), + ), } }; bind_payload_to_member(state, &identity, &mut payload)?; - publish_status_report(state, payload).await + publish_status_report_at(state, &relay_url, payload).await } -async fn publish_stopped_status_for_state(state: &AppState) -> Result<(), String> { +async fn publish_stopped_status_for_state( + state: &AppState, + relay_url: Option<&str>, +) -> Result<(), String> { let identity = super::ensure_owner_identity() .map_err(|error| format!("failed to load mesh owner identity: {error}"))?; let mut payload = stopped_status_payload(&identity); bind_payload_to_member(state, &identity, &mut payload)?; - publish_status_report(state, payload).await + let relay_url = relay_url + .map(str::to_owned) + .unwrap_or_else(|| crate::relay::relay_ws_url_with_override(state)); + publish_status_report_at(state, &relay_url, payload).await } fn stopped_status_payload(identity: &super::identity::OwnerIdentity) -> serde_json::Value { @@ -469,13 +474,21 @@ pub(crate) fn build_status_report_event( .tags([d, k])) } -pub(crate) async fn publish_status_report( +async fn publish_status_report_at( state: &AppState, + relay_url: &str, payload: serde_json::Value, ) -> Result<(), String> { - crate::relay::submit_event(build_status_report_event(payload)?, state) - .await - .map(|_| ()) + let api_base_url = crate::relay::relay_http_base_url(relay_url); + let keys = state.signing_keys()?; + crate::relay::submit_event_at_with_keys( + build_status_report_event(payload)?, + state, + &api_base_url, + &keys, + ) + .await + .map(|_| ()) } #[cfg(test)] @@ -554,11 +567,11 @@ mod tests { // Growth (pure additions) applies immediately — fast admission is fine. #[test] - fn roster_growth_restarts_immediately() { + fn roster_growth_requests_process_restart_immediately() { let current = vec!["owner-a".to_string()]; let fresh = vec!["owner-a".to_string(), "owner-c".to_string()]; - let action = roster_reconcile_action(¤t, None, Ok(fresh.clone())); - assert_eq!(action, RosterReconcileAction::Restart(fresh)); + let action = roster_reconcile_action(¤t, None, Ok(fresh)); + assert_eq!(action, RosterReconcileAction::RestartProcess); } // A shrink is NOT applied on first observation — it must be confirmed. @@ -572,11 +585,11 @@ mod tests { // The same reduced roster on two consecutive polls confirms the shrink. #[test] - fn roster_shrink_restarts_once_confirmed() { + fn roster_shrink_requests_process_restart_once_confirmed() { let current = vec!["owner-a".to_string(), "owner-b".to_string()]; let reduced = vec!["owner-a".to_string()]; let action = roster_reconcile_action(¤t, Some(&reduced), Ok(reduced.clone())); - assert_eq!(action, RosterReconcileAction::Restart(reduced)); + assert_eq!(action, RosterReconcileAction::RestartProcess); } // A shrink that changes between polls is not confirmed — it re-holds with @@ -600,7 +613,7 @@ mod tests { assert_eq!(first, RosterReconcileAction::AwaitConfirm(Vec::new())); let empty: Vec = Vec::new(); let confirmed = roster_reconcile_action(¤t, Some(&empty), Ok(Vec::new())); - assert_eq!(confirmed, RosterReconcileAction::Restart(Vec::new())); + assert_eq!(confirmed, RosterReconcileAction::RestartProcess); } // A shrink followed by recovery to the full roster cancels the teardown. diff --git a/desktop/src-tauri/src/mesh_llm/mod.rs b/desktop/src-tauri/src/mesh_llm/mod.rs index 6e3ab4b28b6..e206c53886a 100644 --- a/desktop/src-tauri/src/mesh_llm/mod.rs +++ b/desktop/src-tauri/src/mesh_llm/mod.rs @@ -1,7 +1,7 @@ use std::collections::BTreeMap; mod coordinator; -pub(crate) use coordinator::{publish_current_status_once, publish_stopped_status_once}; +pub(crate) use coordinator::{publish_current_status_once, publish_stopped_status_once_at}; pub use coordinator::{start_coordinator, MeshCoordinator, KIND_BUZZ_MESH_MEMBER_STATUS}; mod discovery; @@ -14,6 +14,7 @@ pub(crate) use discovery::{ use discovery::{device_name_from_status, endpoint_id_from_status, enrich_status_payload_identity}; mod catalog; +pub(crate) use catalog::canonical_curated_model_id; pub use catalog::{model_catalog, MeshModelCatalog}; mod identity; @@ -200,6 +201,11 @@ pub struct StartMeshNodeRequest { /// accepted from the frontend and contains no relay address. #[serde(default, skip_deserializing)] pub mesh_name: Option, + /// Relay this runtime's community membership and discovery are bound to. + /// Injected by the backend when sharing starts and retained across UI + /// workspace switches; moving a share requires an explicit stop/start. + #[serde(default, skip_deserializing)] + pub relay_url: Option, /// Mesh owner ids admitted to this node (the member roster from /// member-signed discovery notes). `None` = caller did not resolve a roster /// (tests, direct invocations): the node runs without allowlist @@ -308,17 +314,20 @@ pub const MESH_WORKER_STACK_SIZE: usize = 8 * 1024 * 1024; /// before the node starts. Without this the download happens *inside* /// `serve::start()` where the UI can only show a frozen "starting…" state. /// Already-installed models return immediately from the cache scan. -async fn ensure_model_downloaded(model: &str) -> anyhow::Result<()> { - let model_owned = model.to_string(); - let installed = tokio::task::spawn_blocking(move || { +async fn model_is_installed(model: &str) -> bool { + let model_owned = model.replace("@main", ""); + tokio::task::spawn_blocking(move || { let cache = mesh_llm_node::models::default_huggingface_cache_dir(); mesh_llm_node::models::scan_installed_models(cache) .iter() - .any(|m| m.model_ref.contains(&model_owned)) + .any(|m| m.model_ref.replace("@main", "").contains(&model_owned)) }) .await - .unwrap_or(false); - if installed { + .unwrap_or(false) +} + +async fn ensure_model_downloaded(model: &str) -> anyhow::Result<()> { + if model_is_installed(model).await { return Ok(()); } mesh_llm_host_runtime::models::download_model_ref_with_progress_details(model, true) diff --git a/desktop/src-tauri/src/mesh_llm/mod_tests.rs b/desktop/src-tauri/src/mesh_llm/mod_tests.rs index 0b726c264fa..557cd040fab 100644 --- a/desktop/src-tauri/src/mesh_llm/mod_tests.rs +++ b/desktop/src-tauri/src/mesh_llm/mod_tests.rs @@ -12,6 +12,7 @@ fn pending_client_runtime( max_vram_gb: None, join_token: Some("initial-token".to_string()), mesh_name: None, + relay_url: None, trusted_owner_ids: None, }; super::DesktopMeshRuntime { diff --git a/desktop/src-tauri/src/mesh_llm/recovery.rs b/desktop/src-tauri/src/mesh_llm/recovery.rs index 809fab89933..89ca6396e9f 100644 --- a/desktop/src-tauri/src/mesh_llm/recovery.rs +++ b/desktop/src-tauri/src/mesh_llm/recovery.rs @@ -153,6 +153,13 @@ fn should_evict_after_probe( || consecutive >= DEAD_PROBE_EVICT_THRESHOLD } +fn requires_process_restart( + mode: crate::mesh_llm::MeshNodeMode, + startup_in_progress: bool, +) -> bool { + startup_in_progress || mode == crate::mesh_llm::MeshNodeMode::Serve +} + /// Probe and, when justified, remove one stale runtime. A closed port is /// decisive for a foreground agent start; watchdog and ambiguous/unhealthy /// ports require consecutive failures to avoid restarting on a transient load @@ -161,22 +168,23 @@ pub(crate) async fn recover_stale_mesh_runtime( state: &AppState, urgency: MeshRecoveryUrgency, ) -> MeshRuntimeRecovery { - let (candidate_id, startup_in_progress) = match state.mesh_llm_runtime.lock().await.as_ref() { - Some(runtime) => (runtime.id(), runtime.is_starting().await), - None => { - state.mesh_recovery.reset_probe_streak(); - // A cancelled SDK startup can outlive its Buzz-side task briefly - // because the embedded runtime runs on its own thread. Never start - // a replacement merely because the tracked handle is gone: first - // prove the old ingress is either still useful or has released the - // port. This closes the port-conflict loop in #2304. - return match probe_mesh_ingress().await { - MeshIngressProbe::Live => MeshRuntimeRecovery::Live, - MeshIngressProbe::PortClosed => MeshRuntimeRecovery::Absent, - MeshIngressProbe::Unhealthy => MeshRuntimeRecovery::ReleasePending, - }; - } - }; + let (candidate_id, startup_in_progress, candidate_mode) = + match state.mesh_llm_runtime.lock().await.as_ref() { + Some(runtime) => (runtime.id(), runtime.is_starting().await, runtime.mode()), + None => { + state.mesh_recovery.reset_probe_streak(); + // A cancelled SDK startup can outlive its Buzz-side task briefly + // because the embedded runtime runs on its own thread. Never start + // a replacement merely because the tracked handle is gone: first + // prove the old ingress is either still useful or has released the + // port. This closes the port-conflict loop in #2304. + return match probe_mesh_ingress().await { + MeshIngressProbe::Live => MeshRuntimeRecovery::Live, + MeshIngressProbe::PortClosed => MeshRuntimeRecovery::Absent, + MeshIngressProbe::Unhealthy => MeshRuntimeRecovery::ReleasePending, + }; + } + }; let probe = probe_mesh_ingress().await; if probe == MeshIngressProbe::Live { state.mesh_recovery.reset_probe_streak(); @@ -196,12 +204,13 @@ pub(crate) async fn recover_stale_mesh_runtime( return MeshRuntimeRecovery::Debouncing; } - // The pinned SDK does not yield its control handle until the management - // API is ready. Dropping its still-pending start future would detach the - // embedded runtime thread without sending a shutdown request, so Buzz must - // not evict it and race a replacement onto the same ports. A controlled - // app relaunch is the only process-owned cleanup boundary in this state. - if startup_in_progress { + // Never replace a serving runtime in-process. Its native listeners and + // model host are process-owned; stopping it here and then cold-starting a + // client silently disables Share Compute and can race ports 9337/3131. + // Pending client startups have the same ownership problem because the SDK + // has not yielded a shutdown handle yet. In both cases, process restart is + // the only boundary that preserves the configured role safely. + if requires_process_restart(candidate_mode, startup_in_progress) { state.mesh_recovery.reset_probe_streak(); return MeshRuntimeRecovery::RestartRequired; } @@ -241,6 +250,12 @@ pub(crate) async fn recover_stale_mesh_runtime( pub(crate) async fn rearm_relay_mesh_for_running_agents(app: &AppHandle) -> Result<(), String> { let state = app.state::(); let _rearm_guard = state.mesh_recovery.rearm_lock.lock().await; + let runtime_mode = state + .mesh_llm_runtime + .lock() + .await + .as_ref() + .map(|runtime| runtime.mode()); let recovery = recover_stale_mesh_runtime(&state, MeshRecoveryUrgency::Watchdog).await; let active_pubkeys = active_managed_agent_pubkeys(&state); // Mesh participation is resolved through the same definition-authoritative @@ -254,6 +269,13 @@ pub(crate) async fn rearm_relay_mesh_for_running_agents(app: &AppHandle) -> Resu | MeshRuntimeRecovery::Debouncing | MeshRuntimeRecovery::Replaced => return Ok(()), MeshRuntimeRecovery::RestartRequired => { + if runtime_mode == Some(crate::mesh_llm::MeshNodeMode::Serve) { + eprintln!( + "buzz-mesh: serving ingress failed; restarting Buzz to restore Share Compute without changing roles" + ); + app.request_restart(); + return Ok(()); + } let records = crate::managed_agents::load_managed_agents(app).unwrap_or_default(); if !records.iter().any(|record| { running_relay_mesh_model_id(record, &active_pubkeys, &personas, &global).is_some() @@ -410,6 +432,7 @@ mod tests { name_pool: Vec::new(), is_builtin: false, is_active: true, + shared: false, source_team: None, source_team_persona_slug: None, catalog_source: None, @@ -481,6 +504,22 @@ mod tests { assert!(STALE_STOP_TIMEOUT <= Duration::from_secs(15)); } + #[test] + fn failed_serving_runtime_requires_process_restart_instead_of_client_fallback() { + assert!(requires_process_restart( + crate::mesh_llm::MeshNodeMode::Serve, + false + )); + assert!(requires_process_restart( + crate::mesh_llm::MeshNodeMode::Client, + true + )); + assert!(!requires_process_restart( + crate::mesh_llm::MeshNodeMode::Client, + false + )); + } + #[test] fn only_running_relay_mesh_agents_trigger_rearm() { let personas: Vec = Vec::new(); diff --git a/desktop/src-tauri/src/tray_menu.rs b/desktop/src-tauri/src/tray_menu.rs new file mode 100644 index 00000000000..d733cd1f13d --- /dev/null +++ b/desktop/src-tauri/src/tray_menu.rs @@ -0,0 +1,640 @@ +//! Native system-tray menu for the desktop app. +//! +//! The webview owns the live agent-turn state. It sends the small display +//! projection here so the native menu can remain useful while Buzz is hidden. + +use std::{ + sync::{Mutex, OnceLock}, + time::{Duration, Instant}, +}; + +#[cfg(target_os = "macos")] +use objc2::MainThreadMarker; +#[cfg(target_os = "macos")] +use objc2_foundation::{NSProcessInfo, NSString}; +use serde::{Deserialize, Serialize}; +use tauri::{ + image::Image, + menu::{Menu, MenuItem, PredefinedMenuItem}, + tray::{TrayIcon, TrayIconBuilder}, + AppHandle, Emitter, Manager, Runtime, +}; + +const TRAY_ID: &str = "buzz-tray"; +const OPEN_BUZZ_ID: &str = "tray-open-buzz"; +const NEW_CHANNEL_ID: &str = "tray-new-channel"; +const QUIT_ID: &str = "tray-quit"; +const OPEN_CHANNEL_PREFIX: &str = "tray-open-channel:"; +const OPEN_CHANNEL_ACTIVITY_SEPARATOR: char = '|'; +#[cfg(target_os = "macos")] +const TRAY_MENU_MINIMUM_WIDTH: f64 = 320.0; + +static PREVIEW_STARTED_AT: OnceLock = OnceLock::new(); + +/// A local-only menu preview for demonstrating the working-agent section +/// without connecting to a relay. It is deliberately unavailable in release +/// builds and must be explicitly enabled when launching the debug app. +fn preview_activities() -> Option> { + if !cfg!(debug_assertions) || std::env::var("BUZZ_TRAY_MENU_DEMO").ok().as_deref() != Some("1") + { + return None; + } + + let preview_elapsed = PREVIEW_STARTED_AT.get_or_init(Instant::now).elapsed(); + + Some(vec![ + TrayAgentActivity { + activity_id: "tray-preview-planning-scout".into(), + agent_name: "Scout".into(), + channel_id: "tray-preview-planning".into(), + channel_name: "planning".into(), + elapsed: format_elapsed(Duration::from_secs(192) + preview_elapsed), + }, + TrayAgentActivity { + activity_id: "tray-preview-planning-builder".into(), + agent_name: "Builder".into(), + channel_id: "tray-preview-planning".into(), + channel_name: "planning".into(), + elapsed: format_elapsed(Duration::from_secs(68) + preview_elapsed), + }, + TrayAgentActivity { + activity_id: "tray-preview-mobile-reviewer".into(), + agent_name: "Reviewer".into(), + channel_id: "tray-preview-mobile".into(), + channel_name: "mobile".into(), + elapsed: format_elapsed(Duration::from_secs(31) + preview_elapsed), + }, + ]) +} + +fn preview_recent_activities() -> Option> { + if !cfg!(debug_assertions) || std::env::var("BUZZ_TRAY_MENU_DEMO").ok().as_deref() != Some("1") + { + return None; + } + + Some(vec![TrayAgentActivity { + activity_id: "recent:tray-preview-design-architect".into(), + agent_name: "Architect".into(), + channel_id: "tray-preview-design".into(), + channel_name: "design".into(), + elapsed: "4m 25s".into(), + }]) +} + +fn format_elapsed(elapsed: Duration) -> String { + let total_seconds = elapsed.as_secs(); + if total_seconds < 60 { + return format!("{total_seconds}s"); + } + + let seconds = total_seconds % 60; + let total_minutes = total_seconds / 60; + if total_minutes < 60 { + return format!("{total_minutes}m {seconds}s"); + } + + let minutes = total_minutes % 60; + let hours = total_minutes / 60; + format!("{hours}h {minutes}m {seconds}s") +} + +/// Builds the standalone Buzz bee as a transparent, macOS template image. +/// +/// The app icon includes a rounded square, which is useful for the Dock but +/// looks out of place beside the monochrome menu-bar icons. Keeping this +/// vector-derived mask here also lets macOS tint it correctly in light and +/// dark menu bars without a separate bitmap asset. +fn tray_bee_icon() -> Image<'static> { + const WIDTH: u32 = 64; + const HEIGHT: u32 = 43; + const SAMPLES_PER_AXIS: u32 = 4; + const BEE_WIDTH: f32 = 466.0; + const BEE_HEIGHT: f32 = 309.0; + + fn circle_contains(x: f32, y: f32, center_x: f32, center_y: f32, radius: f32) -> bool { + let delta_x = x - center_x; + let delta_y = y - center_y; + delta_x * delta_x + delta_y * delta_y <= radius * radius + } + + fn rounded_rect_contains( + x: f32, + y: f32, + left: f32, + top: f32, + width: f32, + height: f32, + radius: f32, + ) -> bool { + let right = left + width; + let bottom = top + height; + let closest_x = x.clamp(left + radius, right - radius); + let closest_y = y.clamp(top + radius, bottom - radius); + let delta_x = x - closest_x; + let delta_y = y - closest_y; + delta_x * delta_x + delta_y * delta_y <= radius * radius + } + + fn bee_contains(x: f32, y: f32) -> bool { + let silhouette = circle_contains(x, y, 91.7, 154.5, 91.7) + || circle_contains(x, y, 374.3, 154.5, 91.7) + || rounded_rect_contains(x, y, 128.0, 0.0, 210.0, 309.0, 34.0); + let cutout = circle_contains(x, y, 193.3, 84.4, 27.0) + || circle_contains(x, y, 276.0, 84.4, 27.0) + || rounded_rect_contains(x, y, 166.3, 157.2, 136.9, 38.3, 5.0) + || rounded_rect_contains(x, y, 166.9, 235.1, 136.2, 37.6, 5.0); + + silhouette && !cutout + } + + let mut rgba = vec![0; (WIDTH * HEIGHT * 4) as usize]; + let samples = SAMPLES_PER_AXIS * SAMPLES_PER_AXIS; + + for pixel_y in 0..HEIGHT { + for pixel_x in 0..WIDTH { + let mut covered_samples = 0; + for sample_y in 0..SAMPLES_PER_AXIS { + for sample_x in 0..SAMPLES_PER_AXIS { + let x = (pixel_x as f32 + (sample_x as f32 + 0.5) / SAMPLES_PER_AXIS as f32) + / WIDTH as f32 + * BEE_WIDTH; + let y = (pixel_y as f32 + (sample_y as f32 + 0.5) / SAMPLES_PER_AXIS as f32) + / HEIGHT as f32 + * BEE_HEIGHT; + if bee_contains(x, y) { + covered_samples += 1; + } + } + } + + let index = ((pixel_y * WIDTH + pixel_x) * 4) as usize; + rgba[index + 3] = (covered_samples * u8::MAX as u32 / samples) as u8; + } + } + + Image::new_owned(rgba, WIDTH, HEIGHT) +} + +/// A running agent and its current channel. +#[derive(Debug, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct TrayAgentActivity { + activity_id: String, + agent_name: String, + channel_id: String, + channel_name: String, + elapsed: String, +} + +struct TrayActivityMenuItem { + activity_id: String, + channel_id: String, + agent_item: MenuItem, +} + +struct TrayActionQueue { + community_generation: u64, + pending_actions: Vec, +} + +struct TrayMenuState { + activity_items: Mutex>>, + action_queue: Mutex, +} + +#[derive(Debug, Deserialize, Serialize, PartialEq, Eq)] +#[serde(rename_all = "camelCase", tag = "kind")] +pub enum TrayAction { + NewChannel, + OpenChannel { + channel_id: String, + community_generation: u64, + }, +} + +pub(crate) fn show_main_window(app: &AppHandle) { + let Some(window) = app.get_webview_window("main") else { + return; + }; + if let Err(error) = window.unminimize() { + eprintln!("buzz-desktop: failed to restore main window from tray: {error}"); + return; + } + if let Err(error) = window.show() { + eprintln!("buzz-desktop: failed to show main window from tray: {error}"); + return; + } + if let Err(error) = window.set_focus() { + eprintln!("buzz-desktop: failed to focus main window from tray: {error}"); + } +} + +fn queue_tray_action(app: &AppHandle, mut action: TrayAction) { + let state = app.state::>(); + let Ok(mut queue) = state.action_queue.lock() else { + eprintln!("buzz-desktop: tray action queue is unavailable"); + return; + }; + if let TrayAction::OpenChannel { + community_generation, + .. + } = &mut action + { + *community_generation = queue.community_generation; + } + queue.pending_actions.push(action); + drop(queue); + + if let Err(error) = app.emit("tray-action-available", ()) { + eprintln!("buzz-desktop: failed to notify frontend of tray action: {error}"); + } +} + +fn append_separator(app: &AppHandle, menu: &Menu) -> tauri::Result<()> { + menu.append(&PredefinedMenuItem::separator(app)?) +} + +fn agent_item_label(activity: &TrayAgentActivity) -> String { + let primary = format!("{} · {}", activity.agent_name, activity.elapsed); + + #[cfg(target_os = "macos")] + { + if supports_menu_item_subtitles() { + primary + } else { + format!("{primary} — #{}", activity.channel_name) + } + } + + #[cfg(not(target_os = "macos"))] + { + format!("{primary} — #{}", activity.channel_name) + } +} + +#[cfg(target_os = "macos")] +fn supports_menu_item_subtitles() -> bool { + static SUPPORTS_SUBTITLES: OnceLock = OnceLock::new(); + *SUPPORTS_SUBTITLES.get_or_init(|| { + NSProcessInfo::processInfo() + .operatingSystemVersion() + .majorVersion + >= 14 + }) +} + +fn channel_item_id(activity: &TrayAgentActivity) -> String { + format!( + "{OPEN_CHANNEL_PREFIX}{}{OPEN_CHANNEL_ACTIVITY_SEPARATOR}{}", + activity.channel_id, activity.activity_id + ) +} + +fn build_menu( + app: &AppHandle, + activities: &[TrayAgentActivity], + recent_activities: &[TrayAgentActivity], +) -> tauri::Result<(Menu, Vec>)> { + let menu = Menu::new(app)?; + let mut activity_items = + Vec::with_capacity(activities.len().saturating_add(recent_activities.len())); + + let running = MenuItem::new(app, "Running", false, None::<&str>)?; + menu.append(&running)?; + + if activities.is_empty() { + let empty = MenuItem::new(app, "No agents are running", false, None::<&str>)?; + menu.append(&empty)?; + } else { + append_activity_items(app, &menu, activities, &mut activity_items)?; + } + + if !recent_activities.is_empty() { + append_separator(app, &menu)?; + let recent = MenuItem::new(app, "Recent", false, None::<&str>)?; + menu.append(&recent)?; + append_activity_items(app, &menu, recent_activities, &mut activity_items)?; + } + + append_separator(app, &menu)?; + menu.append(&MenuItem::with_id( + app, + NEW_CHANNEL_ID, + "New Channel", + true, + None::<&str>, + )?)?; + append_separator(app, &menu)?; + menu.append(&MenuItem::with_id( + app, + OPEN_BUZZ_ID, + "Open Buzz", + true, + None::<&str>, + )?)?; + append_separator(app, &menu)?; + menu.append(&MenuItem::with_id( + app, + QUIT_ID, + "Quit Buzz", + true, + None::<&str>, + )?)?; + + Ok((menu, activity_items)) +} + +fn append_activity_items( + app: &AppHandle, + menu: &Menu, + activities: &[TrayAgentActivity], + activity_items: &mut Vec>, +) -> tauri::Result<()> { + for activity in activities { + let agent_item = MenuItem::with_id( + app, + channel_item_id(activity), + agent_item_label(activity), + true, + None::<&str>, + )?; + menu.append(&agent_item)?; + activity_items.push(TrayActivityMenuItem { + activity_id: activity.activity_id.clone(), + channel_id: activity.channel_id.clone(), + agent_item, + }); + } + + Ok(()) +} + +#[cfg(target_os = "macos")] +fn apply_activity_presentation( + tray: &TrayIcon, + activities: &[TrayAgentActivity], + recent_activities: &[TrayAgentActivity], +) -> Result<(), String> { + if !supports_menu_item_subtitles() { + return Ok(()); + } + + let subtitles = activities + .iter() + .chain(recent_activities) + .map(|activity| format!("#{}", activity.channel_name)) + .collect::>(); + let running_count = activities.len(); + let recent_count = recent_activities.len(); + + tray.with_inner_tray_icon(move |inner| { + let Some(status_item) = inner.ns_status_item() else { + return; + }; + let Some(main_thread) = MainThreadMarker::new() else { + return; + }; + let Some(menu) = status_item.menu(main_thread) else { + return; + }; + menu.setMinimumWidth(TRAY_MENU_MINIMUM_WIDTH); + + let mut item_index = 1; + for subtitle in subtitles.iter().take(running_count) { + if let Some(item) = menu.itemAtIndex(item_index) { + let subtitle = NSString::from_str(subtitle); + item.setSubtitle(Some(&subtitle)); + } + item_index += 1; + } + + if running_count == 0 { + item_index += 1; + } + + if recent_count > 0 { + // The separator and Recent heading precede the completed rows. + item_index += 2; + for subtitle in subtitles.iter().skip(running_count) { + if let Some(item) = menu.itemAtIndex(item_index) { + let subtitle = NSString::from_str(subtitle); + item.setSubtitle(Some(&subtitle)); + } + item_index += 1; + } + } + }) + .map_err(|error| error.to_string()) +} + +#[cfg(not(target_os = "macos"))] +fn apply_activity_presentation( + _tray: &TrayIcon, + _activities: &[TrayAgentActivity], + _recent_activities: &[TrayAgentActivity], +) -> Result<(), String> { + Ok(()) +} + +fn handle_menu_event(app: &AppHandle, id: &str) { + match id { + OPEN_BUZZ_ID => show_main_window(app), + NEW_CHANNEL_ID => { + show_main_window(app); + queue_tray_action(app, TrayAction::NewChannel); + } + QUIT_ID => app.exit(0), + _ => { + let Some(channel_id) = id.strip_prefix(OPEN_CHANNEL_PREFIX) else { + return; + }; + show_main_window(app); + let channel_id = channel_id + .split_once(OPEN_CHANNEL_ACTIVITY_SEPARATOR) + .map(|(channel_id, _)| channel_id) + .unwrap_or(channel_id); + queue_tray_action( + app, + TrayAction::OpenChannel { + channel_id: channel_id.into(), + community_generation: 0, + }, + ); + } + } +} + +/// Installs the persistent Buzz tray icon with the initial empty activity menu. +pub fn init(app: &AppHandle) -> tauri::Result<()> { + let preview_activities = preview_activities(); + let preview_recent_activities = preview_recent_activities(); + let activities = preview_activities.as_deref().unwrap_or(&[]); + let recent_activities = preview_recent_activities.as_deref().unwrap_or(&[]); + let (menu, activity_items) = build_menu(app, activities, recent_activities)?; + app.manage(TrayMenuState { + activity_items: Mutex::new(activity_items), + action_queue: Mutex::new(TrayActionQueue { + community_generation: 0, + pending_actions: Vec::new(), + }), + }); + let tray = TrayIconBuilder::with_id(TRAY_ID) + .menu(&menu) + .icon(tray_bee_icon()) + .icon_as_template(true) + .on_menu_event(|app, event| handle_menu_event(app, event.id.as_ref())) + .build(app)?; + if let Err(error) = apply_activity_presentation(&tray, activities, recent_activities) { + eprintln!("buzz-desktop: failed to apply tray menu presentation: {error}"); + } + Ok(()) +} + +/// Drains actions selected from the tray while the frontend was unavailable. +#[tauri::command] +pub fn take_tray_actions(app: AppHandle) -> Result, String> { + let state = app.state::>(); + let mut queue = state + .action_queue + .lock() + .map_err(|_| "Buzz tray action queue is unavailable".to_string())?; + Ok(std::mem::take(&mut queue.pending_actions)) +} + +fn requeue_actions(queue: &mut TrayActionQueue, mut actions: Vec) { + actions.retain(|action| match action { + TrayAction::NewChannel => true, + TrayAction::OpenChannel { + community_generation, + .. + } => *community_generation == queue.community_generation, + }); + actions.append(&mut queue.pending_actions); + queue.pending_actions = actions; +} + +/// Restores actions that were drained as the frontend unmounted. Channel +/// actions from a previous community generation are discarded. +#[tauri::command] +pub fn requeue_tray_actions( + app: AppHandle, + actions: Vec, +) -> Result<(), String> { + let state = app.state::>(); + let mut queue = state + .action_queue + .lock() + .map_err(|_| "Buzz tray action queue is unavailable".to_string())?; + requeue_actions(&mut queue, actions); + drop(queue); + app.emit("tray-action-available", ()) + .map_err(|error| error.to_string()) +} + +/// Clears community-scoped agent activity and queued channel navigation from +/// the native tray menu. +#[tauri::command] +pub fn clear_tray_agent_activity(app: AppHandle) -> Result<(), String> { + let state = app.state::>(); + let mut queue = state + .action_queue + .lock() + .map_err(|_| "Buzz tray action queue is unavailable".to_string())?; + queue.community_generation = queue.community_generation.wrapping_add(1); + queue + .pending_actions + .retain(|action| matches!(action, TrayAction::NewChannel)); + drop(queue); + + update_tray_agent_activity(app, Vec::new(), Vec::new()) +} + +/// Replaces the native menu's activity section with the current live work. +#[tauri::command] +pub fn update_tray_agent_activity( + app: AppHandle, + activities: Vec, + recent_activities: Vec, +) -> Result<(), String> { + let preview_activities = preview_activities(); + let preview_recent_activities = preview_recent_activities(); + let activities = preview_activities.as_deref().unwrap_or(&activities); + let recent_activities = preview_recent_activities + .as_deref() + .unwrap_or(&recent_activities); + let state = app.state::>(); + let mut activity_items = state + .activity_items + .lock() + .map_err(|_| "Buzz tray menu state is unavailable".to_string())?; + + if activity_items.len() == activities.len().saturating_add(recent_activities.len()) + && activity_items + .iter() + .zip(activities.iter().chain(recent_activities)) + .all(|(item, activity)| { + item.activity_id == activity.activity_id && item.channel_id == activity.channel_id + }) + { + for (item, activity) in activity_items + .iter() + .zip(activities.iter().chain(recent_activities)) + { + item.agent_item + .set_text(agent_item_label(activity)) + .map_err(|error| error.to_string())?; + } + let tray = app + .tray_by_id(TRAY_ID) + .ok_or_else(|| "Buzz tray icon is not available".to_string())?; + apply_activity_presentation(&tray, activities, recent_activities)?; + return Ok(()); + } + + let (menu, next_activity_items) = + build_menu(&app, activities, recent_activities).map_err(|error| error.to_string())?; + let tray = app + .tray_by_id(TRAY_ID) + .ok_or_else(|| "Buzz tray icon is not available".to_string())?; + tray.set_menu(Some(menu)) + .map_err(|error| error.to_string())?; + apply_activity_presentation(&tray, activities, recent_activities)?; + *activity_items = next_activity_items; + Ok(()) +} + +#[cfg(test)] +mod tests { + use super::{requeue_actions, TrayAction, TrayActionQueue}; + + #[test] + fn stale_channel_actions_are_not_requeued_after_community_change() { + let mut queue = TrayActionQueue { + community_generation: 2, + pending_actions: Vec::new(), + }; + + requeue_actions( + &mut queue, + vec![TrayAction::OpenChannel { + channel_id: "old-channel".into(), + community_generation: 1, + }], + ); + + assert!(queue.pending_actions.is_empty()); + } + + #[test] + fn new_channel_actions_survive_community_change() { + let mut queue = TrayActionQueue { + community_generation: 2, + pending_actions: Vec::new(), + }; + + requeue_actions(&mut queue, vec![TrayAction::NewChannel]); + + assert_eq!(queue.pending_actions, vec![TrayAction::NewChannel]); + } +} diff --git a/desktop/src/app/AppShell.tsx b/desktop/src/app/AppShell.tsx index abbbf296108..b856434e616 100644 --- a/desktop/src/app/AppShell.tsx +++ b/desktop/src/app/AppShell.tsx @@ -96,6 +96,7 @@ import { useMessageDeepLinks } from "@/shared/useMessageDeepLinks"; import { SidebarInset, SidebarProvider } from "@/shared/ui/sidebar"; import { RelayConnectionOverlay } from "@/app/RelayConnectionOverlay"; import { useSidebarRelayConnectionCard } from "@/features/sidebar/ui/useSidebarRelayConnectionCard"; +import { AppShellTrayMenu } from "@/app/useAppShellTrayMenu"; const LazySettingsScreen = React.lazy(async () => { const module = await import("@/features/settings/ui/SettingsScreen"); @@ -614,16 +615,12 @@ export function AppShell() { }, [openSearchHit], ); - useAppShellLifecycleEffects({ homeBadgeCountExcludingHighPriority, unreadChannelIds, unreadChannelNotificationCount, }); - - // Dispatch `buzz://message` deep links into the router. useMessageDeepLinks(); - const handleOpenNewDm = React.useCallback( () => void goNewMessage(), [goNewMessage], @@ -707,9 +704,13 @@ export function AppShell() { markChannelRead, selectedView, }); - return ( + Promise; + openCreateChannel: () => void; +}) { + if (!isMacPlatform()) return null; + return ( + + ); +} + +function MacAppShellTrayMenu({ + channels, + goChannel, + openCreateChannel, +}: { + channels: Channel[]; + goChannel: (channelId: string) => Promise; + openCreateChannel: () => void; +}): null { + useTrayMenu({ + channels, + goChannel, + openCreateChannel, + }); + return null; +} diff --git a/desktop/src/app/useTrayMenu.ts b/desktop/src/app/useTrayMenu.ts new file mode 100644 index 00000000000..355c8e5d4f2 --- /dev/null +++ b/desktop/src/app/useTrayMenu.ts @@ -0,0 +1,160 @@ +import * as React from "react"; +import { isTauri, invoke } from "@tauri-apps/api/core"; +import { listen } from "@tauri-apps/api/event"; + +import { + getActiveTurnsForAgent, + useActiveAgentTurnsByChannel, +} from "@/features/agents/activeAgentTurnsStore"; +import { + useManagedAgentsQuery, + useRelayAgentsQuery, +} from "@/features/agents/hooks"; +import { normalizePubkey, truncatePubkey } from "@/shared/lib/pubkey"; +import { useNow } from "@/shared/lib/useNow"; +import { formatElapsed } from "@/features/agents/ui/agentSessionUtils"; +import type { Channel } from "@/shared/api/types"; + +type TrayAgentActivity = { + activityId: string; + agentName: string; + channelId: string; + channelName: string; + elapsed: string; +}; + +type TrayAction = + | { kind: "newChannel" } + | { kind: "openChannel"; channelId: string }; + +const MAX_RECENT_TRAY_ACTIVITIES = 5; + +/** + * Keeps Buzz's native tray menu synchronized with active agent turns and + * forwards its navigation actions into the React app. + */ +export function useTrayMenu({ + channels, + goChannel, + openCreateChannel, +}: { + channels: Channel[]; + goChannel: (channelId: string) => Promise; + openCreateChannel: () => void; +}): void { + const activeTurns = useActiveAgentTurnsByChannel(); + const now = useNow(1000); + const managedAgents = useManagedAgentsQuery().data; + const relayAgents = useRelayAgentsQuery().data; + const previousActivitiesRef = React.useRef( + new Map(), + ); + const [recentActivities, setRecentActivities] = React.useState< + TrayAgentActivity[] + >([]); + + const activities = React.useMemo(() => { + const channelNames = new Map( + channels.map((channel) => [channel.id, channel.name]), + ); + const agentNames = new Map(); + for (const agent of [...(managedAgents ?? []), ...(relayAgents ?? [])]) { + agentNames.set(normalizePubkey(agent.pubkey), agent.name); + } + + return activeTurns.flatMap((channelTurn) => + channelTurn.agentPubkeys.map((pubkey) => { + const agentTurn = getActiveTurnsForAgent(pubkey).find( + (turn) => turn.channelId === channelTurn.channelId, + ); + + return { + activityId: `${channelTurn.channelId}:${normalizePubkey(pubkey)}`, + agentName: + agentNames.get(normalizePubkey(pubkey)) ?? + `Agent ${truncatePubkey(pubkey)}`, + channelId: channelTurn.channelId, + channelName: + channelNames.get(channelTurn.channelId) ?? "Unknown channel", + elapsed: formatElapsed( + now - (agentTurn?.anchorAt ?? channelTurn.anchorAt), + ), + }; + }), + ); + }, [activeTurns, channels, managedAgents, now, relayAgents]); + + React.useEffect(() => { + const currentActivities = new Map( + activities.map((activity) => [activity.activityId, activity]), + ); + const completedActivities = [...previousActivitiesRef.current.entries()] + .filter(([activityId]) => !currentActivities.has(activityId)) + .map(([, activity]) => ({ + ...activity, + activityId: `recent:${activity.activityId}:${Date.now()}`, + })); + + if (completedActivities.length > 0) { + setRecentActivities((current) => + [...completedActivities, ...current].slice( + 0, + MAX_RECENT_TRAY_ACTIVITIES, + ), + ); + } + previousActivitiesRef.current = currentActivities; + }, [activities]); + + React.useEffect(() => { + if (!isTauri()) return; + void invoke("update_tray_agent_activity", { + activities, + recentActivities, + }).catch((error) => { + console.error("Failed to update the macOS tray menu", error); + }); + }, [activities, recentActivities]); + + React.useEffect(() => { + if (!isTauri()) return; + + let disposed = false; + let unlisten: (() => void) | undefined; + + const handlePendingActions = async () => { + if (disposed) return; + const actions = await invoke("take_tray_actions"); + if (disposed) { + if (actions.length > 0) { + await invoke("requeue_tray_actions", { actions }); + } + return; + } + for (const action of actions) { + if (action.kind === "newChannel") { + openCreateChannel(); + } else { + void goChannel(action.channelId); + } + } + }; + + void (async () => { + const nextUnlisten = await listen("tray-action-available", () => { + void handlePendingActions(); + }); + if (disposed) { + nextUnlisten(); + return; + } + unlisten = nextUnlisten; + await handlePendingActions(); + })(); + + return () => { + disposed = true; + unlisten?.(); + }; + }, [goChannel, openCreateChannel]); +} diff --git a/desktop/src/features/agents/AGENTS.md b/desktop/src/features/agents/AGENTS.md index 35ad4a63af5..d9222c70329 100644 --- a/desktop/src/features/agents/AGENTS.md +++ b/desktop/src/features/agents/AGENTS.md @@ -114,6 +114,39 @@ with a TypeScript lookup table or an id comparison in a component. published or removed. A queued update must stay visibly queued, and the catalog itself must render only relay-confirmed publications — never an optimistic local persona. +11. **Shared agent access names the consequence where it is selected.** The + shared respond-to field shows a persistent warning whenever `anyone` **or** + `allowlist` is selected — both hand the host's access to someone other than + the owner, so both disclose it and only the audience phrase differs. This + covers persona-backed create and edit surfaces. Keep that disclosure in + the shared field instead of adding surface-specific flags. It renders + directly below the selector for `anyone` but *after* the people picker for + `allowlist`, so it never sits between the user and the selection they came + to make. The copy leads with the audience ("Anyone can use this agent to + access…") so it reads as a warning rather than an explanation, and stays one + sentence — don't split the mechanism into a second sentence. Both the machine + and the stakes it names come from `lib/agentAccessWarning.ts`, keyed on an + optional `runLocation`: instance surfaces resolve it from + `ManagedAgent.backend` via `runLocationForBackend`, and the create flow from + `WhereToRunDraft.runOn` via `runLocationForRunOn`. `AgentDialog` is the one + place that resolves it for dialog surfaces and publishes it through + `ui/AgentRunLocationContext.tsx`; the field reads that context and lets an + explicit `runLocation` prop win. Do **not** thread the value as a prop + through `AgentDefinitionDialog` / `AgentInstanceEditDialog` — both are + already over the 1000-line ceiling, and neither uses the value itself. + Surfaces rendered outside `AgentDialog` (e.g. `EditRespondToDialog`) pass the + prop directly. Local names "your + computer, including files, accounts, and connected tools"; remote names "the + server it runs on, including any accounts and tools available there" — + deliberately *not* the owner's files, which aren't theirs to describe on a + host they don't own. **An unknown location falls back to the local wording — + never hedge with "computer or server".** A remote host requires an + installed `buzz-backend-*` provider, and without one `WhereToRunSection` + never renders, so "server" would name a concept the owner has never been + shown; when it *is* remote they picked that host from the selector + themselves. Never synthesize a run location a surface doesn't have. Don't + expose `respond-to`, `allowlist`, Nostr, or harness jargon in primary UI + copy. ## The tests that enforce this @@ -128,6 +161,12 @@ with a TypeScript lookup table or an id comparison in a component. `isCacheableDiscoveryResponse`, `deriveModelDiscoveryPending`, `isSuccessfulEmptyDiscovery`. If the "reopen to retry" copy becomes inert again, these tests will catch it. +- `ui/respondToFieldContract.test.mjs` — plain-language mode labels, the + persistent warning contract for shared agent access, and its two render + positions (after the people picker for `allowlist`). +- `lib/agentAccessWarning.test.mjs` — every mode × run-location copy variant + plus both resolvers, including unknown-reads-as-local and + blank-`runOn`-is-not-a-provider. - `desktop/tests/e2e/onboarding-agent-defaults.spec.ts` — onboarding behavior acceptance coverage for readiness, failure states, defaults, navigation, successful-empty vs failed optional-model discovery, and persistence races. diff --git a/desktop/src/features/agents/lib/agentAccessWarning.test.mjs b/desktop/src/features/agents/lib/agentAccessWarning.test.mjs new file mode 100644 index 00000000000..0a3d13ce7b2 --- /dev/null +++ b/desktop/src/features/agents/lib/agentAccessWarning.test.mjs @@ -0,0 +1,89 @@ +import assert from "node:assert/strict"; +import test from "node:test"; + +import { + agentAccessWarningText, + runLocationForBackend, + runLocationForRunOn, +} from "./agentAccessWarning.ts"; + +test("only the modes that share access warn", () => { + assert.equal(agentAccessWarningText("owner-only", "local"), null); + assert.ok(agentAccessWarningText("anyone", "local")); + assert.ok(agentAccessWarningText("allowlist", "local")); +}); + +test("a local agent names this computer and what is reachable on it", () => { + assert.equal( + agentAccessWarningText("anyone", "local"), + "Anyone can use this agent to access your computer, including files, accounts, and connected tools.", + ); + assert.equal( + agentAccessWarningText("allowlist", "local"), + "Selected people can use this agent to access your computer, including files, accounts, and connected tools.", + ); +}); + +test("a provider-backed agent names the server, and not the owner's files", () => { + // A remote host's files aren't the owner's to describe, so the tail narrows + // to the accounts and tools provisioned there. + assert.equal( + agentAccessWarningText("anyone", "remote"), + "Anyone can use this agent to access the server it runs on, including any accounts and tools available there.", + ); + assert.equal( + agentAccessWarningText("allowlist", "remote"), + "Selected people can use this agent to access the server it runs on, including any accounts and tools available there.", + ); + assert.doesNotMatch( + agentAccessWarningText("anyone", "remote"), + /your computer/, + ); +}); + +test("an unknown run location reads as local, not as a hedge", () => { + // "computer or server" names a concept most owners have never been shown: + // the Run on selector only renders when a buzz-backend-* provider exists. + for (const unknown of [undefined, null]) { + assert.equal( + agentAccessWarningText("anyone", unknown), + "Anyone can use this agent to access your computer, including files, accounts, and connected tools.", + ); + } +}); + +test("every variant leads with the audience and stays jargon-free", () => { + for (const mode of ["anyone", "allowlist"]) { + for (const runLocation of [null, "local", "remote"]) { + const text = agentAccessWarningText(mode, runLocation); + assert.match( + text, + /^(Anyone|Selected people) can use this agent to access/, + ); + assert.doesNotMatch(text, /respond-to|allowlist|pubkey|Nostr|harness/i); + } + } +}); + +test("runLocationForBackend maps the backend union", () => { + assert.equal(runLocationForBackend({ type: "local" }), "local"); + assert.equal( + runLocationForBackend({ type: "provider", id: "blox", config: {} }), + "remote", + ); + assert.equal(runLocationForBackend(null), null); + assert.equal(runLocationForBackend(undefined), null); +}); + +test("runLocationForRunOn treats a provider id as remote", () => { + assert.equal(runLocationForRunOn("local"), "local"); + assert.equal(runLocationForRunOn("blox"), "remote"); +}); + +test("runLocationForRunOn treats a blank value as unknown", () => { + // `runOn` is typed `"local" | string`, so a blank must not read as a + // provider id and produce the server wording. + assert.equal(runLocationForRunOn(""), null); + assert.equal(runLocationForRunOn(null), null); + assert.equal(runLocationForRunOn(undefined), null); +}); diff --git a/desktop/src/features/agents/lib/agentAccessWarning.ts b/desktop/src/features/agents/lib/agentAccessWarning.ts new file mode 100644 index 00000000000..d98058f5bf3 --- /dev/null +++ b/desktop/src/features/agents/lib/agentAccessWarning.ts @@ -0,0 +1,63 @@ +import type { ManagedAgentBackend, RespondToMode } from "@/shared/api/types"; + +/** + * Where an agent's process runs, as far as the calling surface can tell. + * + * Deliberately coarser than `ManagedAgentBackend`: the warning copy only needs + * to know "this machine" vs "somewhere else", so surfaces resolve their own + * backend shape down to this before handing it over. `null` means the surface + * genuinely cannot tell — see `agentAccessWarningText` for how that is + * treated. + */ +export type AgentRunLocation = "local" | "remote"; + +/** Resolve a running agent's backend record. `null` when the backend is unknown. */ +export function runLocationForBackend( + backend: ManagedAgentBackend | null | undefined, +): AgentRunLocation | null { + if (!backend) return null; + return backend.type === "local" ? "local" : "remote"; +} + +/** + * Resolve the create flow's `WhereToRunDraft.runOn`, which is `"local"` or a + * discovered provider id. An empty string is treated as unknown rather than as + * a provider, since `runOn` is typed `"local" | string`. + */ +export function runLocationForRunOn( + runOn: string | null | undefined, +): AgentRunLocation | null { + if (!runOn) return null; + return runOn === "local" ? "local" : "remote"; +} + +/** + * Copy for the shared-access warning in the respond-to field, or `null` for + * modes that share nothing. + * + * Both `anyone` and `allowlist` hand the host's access to someone other than + * the owner, so both warn; only the audience phrase differs. + * + * An unknown run location falls back to the same "your computer" wording as + * `local` rather than hedging with "computer or server". A remote host is only + * reachable when a `buzz-backend-*` provider binary is installed — without one + * `WhereToRunSection`'s "Run on" selector never renders and every agent is + * local — so hedging would name a concept most owners have never been shown. + * When it *is* remote the owner picked that host from the selector + * deliberately, so naming a server is meaningful there. + */ +export function agentAccessWarningText( + mode: RespondToMode, + runLocation?: AgentRunLocation | null, +): string | null { + if (mode !== "anyone" && mode !== "allowlist") return null; + const audience = mode === "anyone" ? "Anyone" : "Selected people"; + // The two locations differ in more than the noun: a local agent reaches the + // owner's own files, while a remote host's files aren't theirs to describe — + // only the accounts and tools provisioned there. + const target = + runLocation === "remote" + ? "the server it runs on, including any accounts and tools available there" + : "your computer, including files, accounts, and connected tools"; + return `${audience} can use this agent to access ${target}.`; +} diff --git a/desktop/src/features/agents/ui/AgentDialog.tsx b/desktop/src/features/agents/ui/AgentDialog.tsx index f5be3cc7e87..dc608da4890 100644 --- a/desktop/src/features/agents/ui/AgentDialog.tsx +++ b/desktop/src/features/agents/ui/AgentDialog.tsx @@ -6,6 +6,11 @@ import type { ManagedAgent, UpdatePersonaInput, } from "@/shared/api/types"; +import { + runLocationForBackend, + runLocationForRunOn, +} from "../lib/agentAccessWarning"; +import { AgentRunLocationProvider } from "./AgentRunLocationContext"; import type { BackendIntent } from "../lib/instanceInputForDefinition"; import type { AgentCreateIntent } from "./agentCreateIntent"; import type { EditAgentFocusTarget } from "@/features/agents/openEditAgentEvent"; @@ -89,17 +94,25 @@ type AgentDialogProps = export function AgentDialog(props: AgentDialogProps) { if (props.mode === "instance-edit") { return ( - + // A running instance knows its own backend, so the respond-to warning can + // name the machine it will actually run on. + + + ); } if (props.mode === "definition-edit") { + // A definition has no instance and no run draft, so the run location stays + // unknown and the warning uses its local-wording fallback. const { mode: _mode, ...definitionProps } = props; return ; } @@ -124,35 +137,39 @@ function AgentCreateDialogRouter({ const copy = createPersonaDialogState(); return ( - - } - createSubmitBlocked={!canSubmitWhereToRun(runDraft)} - description={copy.description} - error={definitionError} - initialValues={initialValues} - isPending={isDefinitionPending} - onOpenChange={onOpenChange} - onSubmit={async (input) => { - const submitted = await onSubmitDefinition( - input, - "definition_start", - resolveBackendIntent(runDraft), - ); - if (submitted) { - onOpenChange(false); + // The create flow is the one surface that knows where the agent will run, + // because it owns the "Run on" draft. + + } - }} - open - runtimes={runtimes} - runtimesLoading={runtimesLoading} - submitLabel={copy.submitLabel} - title={copy.title} - /> + createSubmitBlocked={!canSubmitWhereToRun(runDraft)} + description={copy.description} + error={definitionError} + initialValues={initialValues} + isPending={isDefinitionPending} + onOpenChange={onOpenChange} + onSubmit={async (input) => { + const submitted = await onSubmitDefinition( + input, + "definition_start", + resolveBackendIntent(runDraft), + ); + if (submitted) { + onOpenChange(false); + } + }} + open + runtimes={runtimes} + runtimesLoading={runtimesLoading} + submitLabel={copy.submitLabel} + title={copy.title} + /> + ); } diff --git a/desktop/src/features/agents/ui/AgentInstanceEditDialog.tsx b/desktop/src/features/agents/ui/AgentInstanceEditDialog.tsx index f3c410e2ff2..79d1e9a7907 100644 --- a/desktop/src/features/agents/ui/AgentInstanceEditDialog.tsx +++ b/desktop/src/features/agents/ui/AgentInstanceEditDialog.tsx @@ -936,7 +936,7 @@ export function AgentInstanceEditDialog({ - {/* Who can talk to this agent */} + {/* Who can send instructions */} ( + null, +); + +export function AgentRunLocationProvider({ + children, + runLocation, +}: { + children: React.ReactNode; + runLocation: AgentRunLocation | null; +}) { + return ( + + {children} + + ); +} + +export function useAgentRunLocation(): AgentRunLocation | null { + return React.useContext(AgentRunLocationContext); +} diff --git a/desktop/src/features/agents/ui/AgentsView.tsx b/desktop/src/features/agents/ui/AgentsView.tsx index f24a3c06d7f..3d1673c365c 100644 --- a/desktop/src/features/agents/ui/AgentsView.tsx +++ b/desktop/src/features/agents/ui/AgentsView.tsx @@ -1,5 +1,5 @@ import * as React from "react"; -import { OctagonX, Settings2 } from "lucide-react"; +import { EllipsisVertical, OctagonX, Settings2 } from "lucide-react"; import { consumePendingSnapshotImport, subscribeSnapshotImport, @@ -20,10 +20,7 @@ import { SecretRevealDialog } from "./SecretRevealDialog"; import { TeamDeleteDialog } from "./TeamDeleteDialog"; import { TeamDialog } from "./TeamDialog"; import { TeamsSection } from "./TeamsSection"; -import { - AGENT_CARD_GRID_COLUMNS_CLASS, - UnifiedAgentsSection, -} from "./UnifiedAgentsSection"; +import { UnifiedAgentsSection } from "./UnifiedAgentsSection"; import { useManagedAgentActions } from "./useManagedAgentActions"; import { usePersonaActions } from "./usePersonaActions"; import { useTeamActions } from "./useTeamActions"; @@ -32,6 +29,12 @@ import { useBakedBuildEnvQuery } from "@/features/agents/hooks"; import { isManagedAgentActive } from "@/features/agents/lib/managedAgentControlActions"; import { useGlobalAgentConfig } from "@/features/agents/useGlobalAgentConfig"; import { Button } from "@/shared/ui/button"; +import { + DropdownMenu, + DropdownMenuContent, + DropdownMenuItem, + DropdownMenuTrigger, +} from "@/shared/ui/dropdown-menu"; import { PageHeader } from "@/shared/ui/PageHeader"; import { getInheritedAgentDefaults } from "./bakedEnvHelpers"; @@ -44,6 +47,8 @@ export function AgentsView() { const personas = usePersonaActions(); const teamImportInputRef = React.useRef(null); const aiDefaultsTriggerRef = React.useRef(null); + const fullAiDefaultsTriggerRef = React.useRef(null); + const compactActionsTriggerRef = React.useRef(null); const [isAiDefaultsOpen, setIsAiDefaultsOpen] = React.useState(false); // Exclusivity: create never sets `personaDialogState` (edit/dup/import do), // so the create-mode and definition-edit AgentDialog mounts never coexist. @@ -53,6 +58,22 @@ export function AgentsView() { personas.prepareCreate(); setIsCreateDialogOpen(true); } + + function openAiDefaults(trigger: HTMLButtonElement | null) { + aiDefaultsTriggerRef.current = trigger; + setIsAiDefaultsOpen(true); + } + + function setAiDefaultsDialogOpen(open: boolean) { + if (!open) { + aiDefaultsTriggerRef.current = + fullAiDefaultsTriggerRef.current?.offsetParent !== null + ? fullAiDefaultsTriggerRef.current + : compactActionsTriggerRef.current; + } + setIsAiDefaultsOpen(open); + } + const teamActions = useTeamActions( { setActionNoticeMessage: agents.setActionNoticeMessage, @@ -113,43 +134,84 @@ export function AgentsView() { <>
- - {runningAgentCount > 0 ? ( + <> +
- ) : null} -
+ {runningAgentCount > 0 ? ( + + ) : null} +
+ + + + + + + { + openAiDefaults(compactActionsTriggerRef.current); + }} + > + + {hasSavedAgentDefaults + ? "Agent defaults" + : "Set agent defaults"} + + {runningAgentCount > 0 ? ( + { + void agents.handleBulkStopRunning(); + }} + > + + Stop running agents + + ) : null} + + + } description="Set up and manage your agents." title="Agents" /> -
+
diff --git a/desktop/src/features/agents/ui/PersonaCatalogDialog.tsx b/desktop/src/features/agents/ui/PersonaCatalogDialog.tsx index ba76d6e4edb..e1ec9460920 100644 --- a/desktop/src/features/agents/ui/PersonaCatalogDialog.tsx +++ b/desktop/src/features/agents/ui/PersonaCatalogDialog.tsx @@ -2,6 +2,7 @@ import * as React from "react"; import { isCatalogPersonaSelected } from "@/features/agents/lib/catalog"; import { isCatalogPersona } from "@/features/agents/lib/personaCatalogRelay"; +import { useUsersBatchQuery } from "@/features/profile/hooks"; import { ProfileAvatar } from "@/features/profile/ui/ProfileAvatar"; import type { AgentPersona } from "@/shared/api/types"; import { useFeedbackToasts } from "@/shared/hooks/useToastEffect"; @@ -276,7 +277,42 @@ function PersonaCatalogChooser({ ); } +/** + * Derives the "Added by" label for a catalog entry from a resolved profile + * summary. Prefers `displayName`, falls back to `name`, then to the default + * "Community member" string when both are absent, null, or whitespace-only. + */ +export function resolveCatalogOwnerLabel( + summary: + | { displayName?: string | null; name?: string | null } + | null + | undefined, +): string { + return ( + summary?.displayName?.trim() || summary?.name?.trim() || "Community member" + ); +} + function PersonaCatalogDetail({ persona }: { persona: AgentPersona }) { + const isCommunityEntry = + isCatalogPersona(persona) && !persona.catalogSource.isOwn; + const ownerPubkey = isCommunityEntry + ? persona.catalogSource.ownerPubkey + : undefined; + const ownerBatchQuery = useUsersBatchQuery(ownerPubkey ? [ownerPubkey] : [], { + enabled: !!ownerPubkey, + }); + + let addedByLabel: string; + if (!isCommunityEntry) { + addedByLabel = "You"; + } else { + const summary = ownerPubkey + ? ownerBatchQuery.data?.profiles[ownerPubkey.toLowerCase()] + : undefined; + addedByLabel = resolveCatalogOwnerLabel(summary); + } + return (
@@ -290,14 +326,7 @@ function PersonaCatalogDetail({ persona }: { persona: AgentPersona }) { {persona.displayName} {persona.isBuiltIn ? null : ( - + )}
diff --git a/desktop/src/features/agents/ui/PersonaShareDialog.tsx b/desktop/src/features/agents/ui/PersonaShareDialog.tsx index c641de9c709..5cf4f9ea3ba 100644 --- a/desktop/src/features/agents/ui/PersonaShareDialog.tsx +++ b/desktop/src/features/agents/ui/PersonaShareDialog.tsx @@ -37,10 +37,13 @@ import { Dialog, DialogClose, DialogContent, + DialogDescription, DialogHeader, DialogTitle, } from "@/shared/ui/dialog"; +import { Separator } from "@/shared/ui/separator"; import { Spinner } from "@/shared/ui/spinner"; +import { Switch } from "@/shared/ui/switch"; import { formatShareRecipientName, @@ -63,7 +66,7 @@ type PersonaShareDialogProps = { }; type SnapshotShareDialogProps = { - afterLink?: React.ReactNode; + beforeExport?: React.ReactNode; displayName: string; encodeSnapshot: ( memoryLevel: SnapshotMemoryLevel, @@ -198,7 +201,6 @@ function MemoryShareConfirmation({ function ShareLevelControl({ ariaLabel, disabled, - hasMemoryOptions, testId, value, options, @@ -206,27 +208,11 @@ function ShareLevelControl({ }: { ariaLabel: string; disabled: boolean; - hasMemoryOptions: boolean; testId: string; value: SnapshotMemoryLevel; options: { value: SnapshotMemoryLevel; label: string }[]; onChange: (level: SnapshotMemoryLevel) => void; }) { - if (!hasMemoryOptions) { - // Nothing to choose from, so there is no dropdown to open. State the - // outcome rather than naming the sole option: the memory-level labels - // ("Agent only", "+ core memory", …) are comparative and only make sense - // when the alternatives are actually offered. - return ( - - No memories included - - ); - } - return ( - + Share {displayName} + + Anyone you share this {itemLabel} with will receive a copy they + can add and use. Changes you make later won’t sync. +
-

- They’ll receive a copy they can add and use. Changes you make - later won’t sync. -

+ {hasMemoryOptions ? ( +
+

+ Share settings +

+
+

+ What’s included +

+ +
+
+ ) : null} + + +
- - - -
-

Share with a link

-

- Anyone with the link can add and use a copy. -

-
-
-

- What’s included -

- -
- {showMemoryWarning ? ( ) : null} - - {afterLink}
+ {beforeExport} diff --git a/desktop/src/features/agents/ui/TeamsSection.tsx b/desktop/src/features/agents/ui/TeamsSection.tsx index f974081b7db..c5a7a078b3f 100644 --- a/desktop/src/features/agents/ui/TeamsSection.tsx +++ b/desktop/src/features/agents/ui/TeamsSection.tsx @@ -20,9 +20,9 @@ import { IdentityCardSkeleton } from "@/shared/ui/identity-card-skeleton"; import { SectionHeader } from "@/shared/ui/PageHeader"; import { CreateIdentityCard } from "./CreateIdentityCard"; import { TeamIdentityCard } from "./TeamIdentityCard"; +import { IDENTITY_CARD_GRID_CLASS } from "./UnifiedAgentsSection"; const TEAM_CARD_COLUMN_CLASS = "w-full"; -const TEAM_CARD_GRID_CLASS = `${TEAM_CARD_COLUMN_CLASS} mx-auto grid max-w-[996px] grid-cols-[repeat(auto-fill,minmax(220px,240px))] justify-center gap-3`; type TeamsSectionProps = { teams: AgentTeam[]; @@ -63,7 +63,7 @@ export function TeamsSection({ {isLoading ? ( -
+
+
{teams.map((team) => { const resolution = resolveTeamPersonas(team, personas); const missingPersonaCount = resolution.missingPersonaCount; diff --git a/desktop/src/features/agents/ui/UnifiedAgentsSection.tsx b/desktop/src/features/agents/ui/UnifiedAgentsSection.tsx index 9bbe3feef79..19a5ef1171f 100644 --- a/desktop/src/features/agents/ui/UnifiedAgentsSection.tsx +++ b/desktop/src/features/agents/ui/UnifiedAgentsSection.tsx @@ -68,7 +68,7 @@ type UnifiedAgentsSectionProps = { const AGENT_CARD_COLUMN_CLASS = "w-full"; export const AGENT_CARD_GRID_COLUMNS_CLASS = "grid-cols-[repeat(auto-fill,minmax(220px,240px))]"; -const AGENT_CARD_GRID_CLASS = `${AGENT_CARD_COLUMN_CLASS} ${AGENT_CARD_GRID_COLUMNS_CLASS} grid justify-start gap-3`; +export const IDENTITY_CARD_GRID_CLASS = `${AGENT_CARD_COLUMN_CLASS} ${AGENT_CARD_GRID_COLUMNS_CLASS} grid justify-start gap-3 [@container(max-width:40rem)]:justify-center`; export function UnifiedAgentsSection(props: UnifiedAgentsSectionProps) { const { @@ -153,7 +153,7 @@ export function UnifiedAgentsSection(props: UnifiedAgentsSectionProps) { {!isLoading ? (
-
+
{groups.map((group) => { const profileAgent = pickProfileAgent(group.agents); return ( @@ -479,7 +479,7 @@ function NewAgentCard({ function LoadingSkeleton() { return ( -
+
({agents.length}) {!isCollapsed ? ( -
+
{agents.map((agent) => ( { + const routeWithBackend = (backend) => + AgentDialog({ + mode: "instance-edit", + agent: { pubkey: "abc", name: "test-agent", backend }, + onOpenChange: noop, + onUpdated: noop, + open: true, + }).props.runLocation; + + assert.equal(routeWithBackend({ type: "local" }), "local"); + assert.equal( + routeWithBackend({ type: "provider", id: "blox", config: {} }), + "remote", + ); + // An agent with no backend record has an unknown location — never a guess. + assert.equal(routeWithBackend(undefined), null); +}); + test("create mode routes to the internal create router, not a form directly", () => { const element = AgentDialog({ mode: "definition", diff --git a/desktop/src/features/agents/ui/personaCatalogOwnerLabel.test.mjs b/desktop/src/features/agents/ui/personaCatalogOwnerLabel.test.mjs new file mode 100644 index 00000000000..7ad726352ff --- /dev/null +++ b/desktop/src/features/agents/ui/personaCatalogOwnerLabel.test.mjs @@ -0,0 +1,77 @@ +import assert from "node:assert/strict"; +import test from "node:test"; + +import { resolveCatalogOwnerLabel } from "./PersonaCatalogDialog.tsx"; + +// ── null / undefined summary ────────────────────────────────────────────────── + +test("test_null_summary_returns_community_member", () => { + assert.equal(resolveCatalogOwnerLabel(null), "Community member"); +}); + +test("test_undefined_summary_returns_community_member", () => { + assert.equal(resolveCatalogOwnerLabel(undefined), "Community member"); +}); + +// ── populated displayName ───────────────────────────────────────────────────── + +test("test_display_name_present_returns_display_name", () => { + assert.equal( + resolveCatalogOwnerLabel({ displayName: "Alice", name: "alice" }), + "Alice", + ); +}); + +test("test_display_name_present_without_name_returns_display_name", () => { + assert.equal(resolveCatalogOwnerLabel({ displayName: "Alice" }), "Alice"); +}); + +// ── empty / whitespace displayName with valid name ──────────────────────────── + +test("test_empty_display_name_falls_through_to_name", () => { + assert.equal( + resolveCatalogOwnerLabel({ displayName: "", name: "alice" }), + "alice", + ); +}); + +test("test_whitespace_only_display_name_falls_through_to_name", () => { + assert.equal( + resolveCatalogOwnerLabel({ displayName: " ", name: "alice" }), + "alice", + ); +}); + +// ── both candidates absent / empty ──────────────────────────────────────────── + +test("test_both_null_returns_community_member", () => { + assert.equal( + resolveCatalogOwnerLabel({ displayName: null, name: null }), + "Community member", + ); +}); + +test("test_both_empty_returns_community_member", () => { + assert.equal( + resolveCatalogOwnerLabel({ displayName: "", name: "" }), + "Community member", + ); +}); + +test("test_both_whitespace_returns_community_member", () => { + assert.equal( + resolveCatalogOwnerLabel({ displayName: " ", name: "\t" }), + "Community member", + ); +}); + +test("test_display_name_absent_name_present_returns_name", () => { + assert.equal(resolveCatalogOwnerLabel({ name: "alice" }), "alice"); +}); + +test("test_display_name_null_name_present_returns_name", () => { + assert.equal( + resolveCatalogOwnerLabel({ displayName: null, name: "alice" }), + "alice", + ); +}); diff --git a/desktop/src/features/agents/ui/respondToFieldContract.test.mjs b/desktop/src/features/agents/ui/respondToFieldContract.test.mjs new file mode 100644 index 00000000000..c3efd34650e --- /dev/null +++ b/desktop/src/features/agents/ui/respondToFieldContract.test.mjs @@ -0,0 +1,67 @@ +import assert from "node:assert/strict"; +import { readFile } from "node:fs/promises"; +import test from "node:test"; + +const respondToFieldSource = await readFile( + new URL("./RespondToField.tsx", import.meta.url), + "utf8", +); + +/** + * Copy assertions run against this rather than the raw source: JSX text wraps + * wherever the formatter decides, and a sentence split across lines should not + * fail a copy test. + */ +const collapsedSource = respondToFieldSource.replace(/\s+/g, " "); + +for (const label of ["Only me (default)", "Selected people", "Anyone"]) { + test(`respond-to control uses the plain-language label: ${label}`, () => { + assert.ok(respondToFieldSource.includes(`label: "${label}"`)); + }); +} + +test("native and persona controls share one option list", () => { + assert.match( + respondToFieldSource, + / \([\s\S]*
@@ -217,12 +247,41 @@ export function ChannelMemberInviteCard({ ) : null} {deferredInviteQuery.length > 0 ? (
- {userSearchQuery.isLoading ? ( + {userSearchQuery.isLoading && !directInvitee ? (

Searching…

- ) : inviteSearchResults.length > 0 ? ( + ) : inviteSearchResults.length > 0 || directInvitee ? (
+ {directInvitee ? ( + + ) : null} {inviteSearchResults.map((result) => (
diff --git a/desktop/src/features/channels/ui/MembersSidebarMemberCard.tsx b/desktop/src/features/channels/ui/MembersSidebarMemberCard.tsx index a332cb8500b..b375649292d 100644 --- a/desktop/src/features/channels/ui/MembersSidebarMemberCard.tsx +++ b/desktop/src/features/channels/ui/MembersSidebarMemberCard.tsx @@ -109,9 +109,9 @@ function formatRespondToLabel(agent: ManagedAgent) { case "anyone": return "Anyone"; case "allowlist": - return `Allowlist (${agent.respondToAllowlist.length})`; + return `Selected people (${agent.respondToAllowlist.length})`; default: - return "Owner only"; + return "Only me"; } } @@ -379,7 +379,7 @@ function MemberActionsMenu({ onClick={() => onEditRespondTo(managedAgent)} > - Edit respond-to... + Manage agent access... ) : null} {canRemoveMember || showChangeRole ? ( diff --git a/desktop/src/features/communities/useCommunityInit.ts b/desktop/src/features/communities/useCommunityInit.ts index abb49485d23..afa69f913f6 100644 --- a/desktop/src/features/communities/useCommunityInit.ts +++ b/desktop/src/features/communities/useCommunityInit.ts @@ -1,4 +1,6 @@ import { useEffect, useRef, useState } from "react"; +import { isTauri } from "@tauri-apps/api/core"; +import { isMacPlatform } from "@/shared/lib/platform"; import { relayClient } from "@/shared/api/relayClient"; import { resetRateLimitGate } from "@/shared/api/relayRateLimitGate"; @@ -8,6 +10,7 @@ import { getDefaultRelayUrl, } from "@/shared/api/tauri"; import { getIdentity } from "@/shared/api/tauriIdentity"; +import { clearTrayAgentActivity } from "@/shared/api/trayMenu"; import { getOverrides } from "@/shared/features"; import { resetMediaCaches } from "@/shared/lib/mediaUrl"; import { clearSearchHitEventCache } from "@/app/navigation/searchHitEventCache"; @@ -53,6 +56,9 @@ function resetCommunityState({ resetAgentObserverStore(); resetActiveAgentTurnsStore(); resetAgentWorkingSignal(); + if (isTauri() && isMacPlatform()) { + void clearTrayAgentActivity(); + } if (resetAvatarState) { resetAvatarProfileSync(); resetAvatarPresentations(); diff --git a/desktop/src/features/community-members/ui/AddMemberDialog.tsx b/desktop/src/features/community-members/ui/AddMemberDialog.tsx index 73e5c31b712..76f28e96ddd 100644 --- a/desktop/src/features/community-members/ui/AddMemberDialog.tsx +++ b/desktop/src/features/community-members/ui/AddMemberDialog.tsx @@ -1,3 +1,5 @@ +import { ChevronDown, Search } from "lucide-react"; +import { AnimatePresence, motion, useReducedMotion } from "motion/react"; import * as React from "react"; import { toast } from "sonner"; @@ -5,8 +7,13 @@ import { useAddRelayMemberMutation, useRelayMembersQuery, } from "@/features/community-members/hooks"; -import type { RelayMemberRole } from "@/shared/api/types"; -import { cn } from "@/shared/lib/cn"; +import { useIsArchivedPredicate } from "@/features/identity-archive/hooks"; +import { useUserSearchQuery } from "@/features/profile/hooks"; +import { ProfileAvatar } from "@/features/profile/ui/ProfileAvatar"; +import { SelectedRecipientChip } from "@/features/profile/ui/SelectedRecipientChip"; +import type { RelayMemberRole, UserSearchResult } from "@/shared/api/types"; +import { parsePubkeyInput } from "@/shared/lib/nostrUtils"; +import { truncatePubkey } from "@/shared/lib/pubkey"; import { Button } from "@/shared/ui/button"; import { Dialog, @@ -15,67 +22,449 @@ import { DialogHeader, DialogTitle, } from "@/shared/ui/dialog"; +import { + DropdownMenu, + DropdownMenuContent, + DropdownMenuRadioGroup, + DropdownMenuRadioItem, + DropdownMenuTrigger, +} from "@/shared/ui/dropdown-menu"; import { Input } from "@/shared/ui/input"; +import { Popover, PopoverAnchor, PopoverContent } from "@/shared/ui/popover"; -const PUBKEY_REGEX = /^[0-9a-f]{64}$/; - -const ROLE_OPTIONS: Array<{ value: RelayMemberRole; label: string }> = [ - { value: "member", label: "Member" }, - { value: "admin", label: "Admin" }, +const ROLE_OPTIONS: Array<{ + value: RelayMemberRole; + label: string; +}> = [ + { + value: "member", + label: "Member", + }, + { + value: "admin", + label: "Admin", + }, ]; -export function AddMemberDialog({ +function formatSearchUserName(user: UserSearchResult) { + return ( + user.displayName?.trim() || + user.nip05Handle?.trim() || + truncatePubkey(user.pubkey) + ); +} + +export function DirectAddMemberForm({ isOwner, - open, - onOpenChange, + onAdded, + showLabel = true, + submitLabel = "Add member", }: { isOwner: boolean; - open: boolean; - onOpenChange: (open: boolean) => void; + onAdded?: () => void; + showLabel?: boolean; + submitLabel?: string; }) { const addMutation = useAddRelayMemberMutation(); const membersQuery = useRelayMembersQuery(); - const [pubkey, setPubkey] = React.useState(""); + const [query, setQuery] = React.useState(""); + const [selectedUsers, setSelectedUsers] = React.useState( + [], + ); const [role, setRole] = React.useState("member"); + const [isPickerOpen, setIsPickerOpen] = React.useState(false); + const searchInputRef = React.useRef(null); + const shouldReduceMotion = useReducedMotion(); - const normalizedPubkey = pubkey.trim().toLowerCase(); - const isValidPubkey = PUBKEY_REGEX.test(normalizedPubkey); + const deferredQuery = React.useDeferredValue(query.trim()); + const parsedPubkey = parsePubkeyInput(deferredQuery); + const userSearchQuery = useUserSearchQuery(deferredQuery, { + enabled: deferredQuery.length > 0, + limit: 8, + }); + const isArchived = useIsArchivedPredicate(); + const selectedPubkeys = React.useMemo( + () => new Set(selectedUsers.map((user) => user.pubkey.toLowerCase())), + [selectedUsers], + ); const isAlreadyMember = - isValidPubkey && - !addMutation.isPending && + parsedPubkey !== null && (membersQuery.data ?? []).some( - (m) => m.pubkey.toLowerCase() === normalizedPubkey, + (m) => m.pubkey.toLowerCase() === parsedPubkey.toLowerCase(), ); - const canAdd = isValidPubkey && !isAlreadyMember && !addMutation.isPending; + const canAdd = selectedUsers.length > 0 && !addMutation.isPending; + const searchResults = React.useMemo( + () => + (userSearchQuery.data ?? []).filter( + (user) => + !isArchived(user.pubkey) && + !selectedPubkeys.has(user.pubkey.toLowerCase()) && + !(membersQuery.data ?? []).some( + (member) => + member.pubkey.toLowerCase() === user.pubkey.toLowerCase(), + ), + ), + [isArchived, membersQuery.data, selectedPubkeys, userSearchQuery.data], + ); + const directResult = React.useMemo(() => { + if ( + parsedPubkey === null || + isAlreadyMember || + selectedPubkeys.has(parsedPubkey.toLowerCase()) || + searchResults.some( + (user) => user.pubkey.toLowerCase() === parsedPubkey.toLowerCase(), + ) + ) { + return null; + } + return { + pubkey: parsedPubkey, + displayName: null, + avatarUrl: null, + nip05Handle: null, + ownerPubkey: null, + isAgent: false, + }; + }, [isAlreadyMember, parsedPubkey, searchResults, selectedPubkeys]); + const roleOptions = React.useMemo( + () => ROLE_OPTIONS.filter((option) => isOwner || option.value === "member"), + [isOwner], + ); + const selectedRoleLabel = + roleOptions.find((option) => option.value === role)?.label ?? "Member"; + const actionTransition = shouldReduceMotion + ? { duration: 0 } + : { duration: 0.18, ease: [0.23, 1, 0.32, 1] as const }; function reset() { - setPubkey(""); + setQuery(""); + setSelectedUsers([]); setRole("member"); + setIsPickerOpen(false); addMutation.reset(); } - function handleOpenChange(next: boolean) { - if (!next) { - reset(); - } - onOpenChange(next); + function selectUser(user: UserSearchResult) { + setSelectedUsers((currentUsers) => + currentUsers.some( + (currentUser) => + currentUser.pubkey.toLowerCase() === user.pubkey.toLowerCase(), + ) + ? currentUsers + : [...currentUsers, user], + ); + setQuery(""); + setIsPickerOpen(true); + window.requestAnimationFrame(() => { + searchInputRef.current?.focus({ preventScroll: true }); + }); } - function handleAdd() { - if (!canAdd) return; - addMutation.mutate( - { pubkey: normalizedPubkey, role }, - { - onSuccess: () => { - toast.success("Member added"); - handleOpenChange(false); - }, - }, + function removeUser(pubkey: string) { + setSelectedUsers((currentUsers) => + currentUsers.filter( + (user) => user.pubkey.toLowerCase() !== pubkey.toLowerCase(), + ), ); + searchInputRef.current?.focus({ preventScroll: true }); + } + + async function handleAdd() { + if (!canAdd) return; + + try { + for (const user of selectedUsers) { + await addMutation.mutateAsync({ pubkey: user.pubkey, role }); + } + toast.success( + selectedUsers.length === 1 + ? role === "admin" + ? "Admin added" + : "Member added" + : role === "admin" + ? "Admins added" + : "Members added", + ); + reset(); + onAdded?.(); + } catch { + // The mutation exposes the API error below the field. + } } return ( - +
{ + event.preventDefault(); + handleAdd(); + }} + > +
+ {showLabel ? ( + + ) : null} +
+ 0} + > + +
+
1 ? "items-start" : "items-center"}`} + > +
+ {selectedUsers.length === 0 ? ( + + ) : null} + {selectedUsers.map((user) => ( + + removeUser(user.pubkey)} + poofOnRemove={false} + testIds={{ + chip: `member-search-selection-remove-${user.pubkey}`, + }} + user={user} + /> + + ))} + { + setQuery(event.target.value); + setIsPickerOpen(true); + }} + onFocus={() => setIsPickerOpen(true)} + onKeyDown={(event) => { + if ( + event.key === "Backspace" && + query.length === 0 && + selectedUsers.length > 0 + ) { + event.preventDefault(); + const lastUser = selectedUsers.at(-1); + if (lastUser) removeUser(lastUser.pubkey); + } + }} + placeholder={ + selectedUsers.length === 0 + ? "Search people or paste an npub" + : "" + } + ref={searchInputRef} + role="combobox" + spellCheck={false} + value={query} + /> +
+ + {selectedUsers.length > 0 ? ( + + + + + + event.preventDefault()} + sideOffset={4} + style={{ minWidth: "13rem" }} + > + + setRole(value as RelayMemberRole) + } + value={role} + > + {roleOptions.map((option) => ( + + {option.label} + + ))} + + + + + ) : null} + +
+
+
+ event.preventDefault()} + onOpenAutoFocus={(event) => event.preventDefault()} + sideOffset={6} + > +
+ {userSearchQuery.isLoading ? ( +

+ Searching… +

+ ) : searchResults.length > 0 || directResult ? ( + <> + {directResult ? ( + selectUser(directResult)} + user={directResult} + /> + ) : null} + {searchResults.map((user) => ( + selectUser(user)} + user={user} + /> + ))} + + ) : ( +

+ No people found. Paste a full npub or hex public key to add + someone directly. +

+ )} +
+
+
+ + {selectedUsers.length > 0 ? ( + + + + ) : null} + +
+ {isAlreadyMember ? ( +

+ This person is already a community member. +

+ ) : null} + {userSearchQuery.error instanceof Error ? ( +

+ {userSearchQuery.error.message} +

+ ) : null} +
+ + {addMutation.error instanceof Error ? ( +

+ {addMutation.error.message} +

+ ) : null} +
+ ); +} + +function SearchResult({ + onSelect, + user, +}: { + onSelect: () => void; + user: UserSearchResult; +}) { + const name = formatSearchUserName(user); + const isDirectPubkey = user.displayName === null && user.nip05Handle === null; + + return ( + + ); +} + +export function AddMemberDialog({ + isOwner, + open, + onOpenChange, +}: { + isOwner: boolean; + open: boolean; + onOpenChange: (open: boolean) => void; +}) { + return ( + Add member - Add a user to this relay by their public key. + Add a person to this community by their public key. - -
{ - e.preventDefault(); - handleAdd(); - }} - > -
-
-
- - setPubkey(e.target.value)} - placeholder="64-character hex pubkey" - spellCheck={false} - value={pubkey} - /> - {pubkey.trim().length > 0 && !isValidPubkey ? ( -

- Must be exactly 64 lowercase hex characters. -

- ) : null} - {isAlreadyMember ? ( -

- This pubkey is already a relay member. -

- ) : null} -
- -
-

Role

-
- {ROLE_OPTIONS.filter( - (opt) => isOwner || opt.value === "member", - ).map((opt) => ( - - ))} -
-
- - {addMutation.error instanceof Error ? ( -

- {addMutation.error.message} -

- ) : null} -
-
- -
- - -
-
+
+ onOpenChange(false)} + /> +
diff --git a/desktop/src/features/community-members/ui/CommunityInviteDialog.tsx b/desktop/src/features/community-members/ui/CommunityInviteDialog.tsx index 9daca590f47..c5cabc26a67 100644 --- a/desktop/src/features/community-members/ui/CommunityInviteDialog.tsx +++ b/desktop/src/features/community-members/ui/CommunityInviteDialog.tsx @@ -7,20 +7,21 @@ import { DialogHeader, DialogTitle, } from "@/shared/ui/dialog"; +import { DirectAddMemberForm } from "./AddMemberDialog"; import { DEFAULT_INVITE_TTL_SECS, InviteLinkSection, } from "./InviteLinkSection"; export function CommunityInviteDialog({ + isOwner, onOpenChange, open, }: { + isOwner: boolean; onOpenChange: (open: boolean) => void; open: boolean; }) { - // Email delivery is not available yet, so the modal only mints shareable - // invite links through the relay's existing invite flow. const [ttlSecs, setTtlSecs] = React.useState(DEFAULT_INVITE_TTL_SECS); React.useEffect(() => { @@ -36,11 +37,24 @@ export function CommunityInviteDialog({ Invite to community - Anyone with this link can join this community. + Add someone directly or share a link they can use to join. - +
+ +
+ +
+

+ Link settings +

+ +
); diff --git a/desktop/src/features/community-members/ui/CommunityMembersSettingsCard.tsx b/desktop/src/features/community-members/ui/CommunityMembersSettingsCard.tsx index 9097f35387f..9a24171316c 100644 --- a/desktop/src/features/community-members/ui/CommunityMembersSettingsCard.tsx +++ b/desktop/src/features/community-members/ui/CommunityMembersSettingsCard.tsx @@ -370,6 +370,7 @@ export function CommunityMembersSettingsCard({
diff --git a/desktop/src/features/community-members/ui/InviteLinkSection.tsx b/desktop/src/features/community-members/ui/InviteLinkSection.tsx index dc0735c85e0..05b46872897 100644 --- a/desktop/src/features/community-members/ui/InviteLinkSection.tsx +++ b/desktop/src/features/community-members/ui/InviteLinkSection.tsx @@ -84,8 +84,8 @@ export function InviteLinkSection({ } return ( -
-
+
+
Expires after diff --git a/desktop/src/features/mesh-compute/ui/MeshComputeSettingsCard.tsx b/desktop/src/features/mesh-compute/ui/MeshComputeSettingsCard.tsx index 76f86f80543..fd7550eff05 100644 --- a/desktop/src/features/mesh-compute/ui/MeshComputeSettingsCard.tsx +++ b/desktop/src/features/mesh-compute/ui/MeshComputeSettingsCard.tsx @@ -107,7 +107,9 @@ export function MeshComputeSettingsCard() { // One-shot hardware-aware catalog fetch. Purely additive: when it fails // (stub build, survey error) the card falls back to the free-text field. - // Keep an empty draft empty so the UI can explicitly ask the member to choose. + // When there is no saved choice, make the curated recommendation the actual + // default so a new member can turn Share Compute on directly. An explicit + // saved draft always wins. React.useEffect(() => { let cancelled = false; (async () => { @@ -115,6 +117,11 @@ export function MeshComputeSettingsCard() { const value = await meshModelCatalog(); if (cancelled) return; setCatalog(value); + setModelInput((current) => { + if (current.trim() !== "" || !value.recommended) return current; + writeDraft(MODEL_DRAFT_STORAGE_KEY, value.recommended); + return value.recommended; + }); } catch { // Non-fatal — picker just doesn't render. } diff --git a/desktop/src/features/messages/lib/timelineItems.test.mjs b/desktop/src/features/messages/lib/timelineItems.test.mjs index cdc40b875e0..4677fe7b49f 100644 --- a/desktop/src/features/messages/lib/timelineItems.test.mjs +++ b/desktop/src/features/messages/lib/timelineItems.test.mjs @@ -245,6 +245,36 @@ test("buildTimelineItems: consecutive same-author messages within the window are ); }); +test("buildTimelineItems: pending messages remain standalone until acknowledged", () => { + const entries = [ + entry({ id: "a", pubkey: "author-a", createdAt: dayAt(2026, 6, 14) }), + entry({ + id: "b", + pubkey: "author-a", + createdAt: dayAt(2026, 6, 14, 12, 2), + pending: true, + }), + entry({ + id: "c", + pubkey: "author-a", + createdAt: dayAt(2026, 6, 14, 12, 3), + }), + ]; + + const messageItems = buildTimelineItems(entries, null).items.filter( + (item) => item.kind === "message", + ); + + assert.deepEqual( + messageItems.map((item) => item.isContinuation), + [false, false, false], + ); + assert.deepEqual( + messageItems.map((item) => item.isFollowedByContinuation), + [false, false, false], + ); +}); + test("buildTimelineItems: same-author messages past the window start a new group", () => { const author = "author-a"; const entries = [ diff --git a/desktop/src/features/messages/lib/timelineItems.ts b/desktop/src/features/messages/lib/timelineItems.ts index 007d77c0203..72b83f0a07f 100644 --- a/desktop/src/features/messages/lib/timelineItems.ts +++ b/desktop/src/features/messages/lib/timelineItems.ts @@ -232,8 +232,13 @@ export function buildTimelineItems( continue; } + // Pending rows render with their own header so the send status can sit + // beside the timestamp. Keep the timeline spacing and row estimate in + // that same standalone state until the send acknowledgement arrives. const isContinuation = + !message.pending && previousGroupEntry !== null && + !previousGroupEntry.message.pending && hasSameMessageAuthor(previousGroupEntry.message, message) && isWithinGroupingWindow( previousGroupEntry.message.createdAt, diff --git a/desktop/src/features/messages/ui/MessageRow.tsx b/desktop/src/features/messages/ui/MessageRow.tsx index afcb3e863c8..069232fde4b 100644 --- a/desktop/src/features/messages/ui/MessageRow.tsx +++ b/desktop/src/features/messages/ui/MessageRow.tsx @@ -1,4 +1,5 @@ import * as React from "react"; +import { AlertTriangle } from "lucide-react"; import { depthGuideActionsEqual, @@ -142,6 +143,9 @@ export const MessageRow = React.memo( showDepthGuides?: boolean; videoReviewContext?: VideoReviewContext; }) { + // Keep the transient send state with its timestamp rather than collapsing + // it into a grouped message row with no header. + const isDisplayedAsContinuation = isContinuation && !message.pending; const [expandedDiffId, setExpandedDiffId] = React.useState( null, ); @@ -383,12 +387,8 @@ export const MessageRow = React.memo( const guideBleedRem = isThreadReplyLayout ? 0.25 : 0; const avatarButtonRadiusClass = "rounded-full"; - const respondToDotColor = - message.respondTo === "anyone" - ? "bg-emerald-500" - : message.respondTo === "allowlist" - ? "bg-amber-500" - : null; + const showRespondToIndicator = + message.respondTo === "anyone" || message.respondTo === "allowlist"; const avatarNode = (
@@ -399,18 +399,31 @@ export const MessageRow = React.memo( displayName={message.author} testId="message-avatar" /> - {respondToDotColor && !isThreadReplyLayout ? ( + {showRespondToIndicator && !isThreadReplyLayout ? ( - + {message.respondTo === "anyone" ? ( +
@@ -433,7 +446,7 @@ export const MessageRow = React.memo(
); - const avatarGutterNode = isContinuation ? ( + const avatarGutterNode = isDisplayedAsContinuation ? ( continuationTimestampGutter ) : message.pubkey ? ( {message.pending ? ( -

Sending

+

+ Sending… +

) : null} {message.edited ? ( @@ -526,13 +544,13 @@ export const MessageRow = React.memo( ); const continuationMetadataNode = - isContinuation && statusMetadataNode ? ( + isDisplayedAsContinuation && statusMetadataNode ? (
{statusMetadataNode}
) : null; - const headerNode = isContinuation ? null : ( + const headerNode = isDisplayedAsContinuation ? null : ( {message.pubkey ? ( ); - const bodyContainerClass = isContinuation ? "mt-0" : bodyOffsetClass; + const bodyContainerClass = isDisplayedAsContinuation + ? "mt-0" + : bodyOffsetClass; const messageBodyNode = ( <> @@ -778,7 +798,7 @@ export const MessageRow = React.memo( ? "mx-1 px-2" : "px-2", "flex gap-2.5", - isContinuation ? "items-center" : "items-start", + isDisplayedAsContinuation ? "items-center" : "items-start", hasActiveReminder ? "bg-blue-500/10" : "", highlighted ? "-mx-4 rounded-none px-6 before:absolute before:-inset-y-1.5 before:inset-x-0 before:animate-[route-target-highlight-fade_2s_ease-out_forwards] before:bg-primary/10 before:content-[''] motion-reduce:before:animate-none sm:-mx-6 sm:px-8" diff --git a/desktop/src/features/profile/ui/SelectedRecipientChip.tsx b/desktop/src/features/profile/ui/SelectedRecipientChip.tsx index 18bf6d3b8b2..bfc2f431674 100644 --- a/desktop/src/features/profile/ui/SelectedRecipientChip.tsx +++ b/desktop/src/features/profile/ui/SelectedRecipientChip.tsx @@ -46,7 +46,7 @@ export function SelectedRecipientChip({ user: UserSearchResult; }) { return ( -
+