Skip to content

Commit a497408

Browse files
matt2eclaude
andcommitted
fix(desktop): harden the relay-edit and repos-map concurrency edges
Resolve the review findings on the lazy multi-workspace agent stack (review of f3baa96) — four hardening fixes, no behavior change on the happy path: - Serialize apply_workspace's .repos-dirs.json upsert on managed_agents_store_lock. A community relay edit fires rebind_agent_relay (which moves map entries under that lock) nearly simultaneously with the reinit apply, and both are read-modify-writes of the same file — unserialized, one side's update could be lost. - Write .repos-dirs.json via temp file + rename. A crash mid-write left truncated JSON, which read_repos_dir_map degrades to an empty map — silently sending spawns back to the shared REPOS fallback, exactly the cross-workspace hazard the map exists to prevent. - Pin the Rust/TS relay-URL normalizers together with a shared fixture (desktop/fixtures/relay-url-normalization.json) consumed by both relay tests and agentRelayScope.test.mjs, so an edit that lands on only one side fails the other side's tests instead of shipping a scoping skew. Both normalizers' doc comments now point at it. - Sequence updateCommunity's state commit (and the reinit it triggers) after the rebindAgentRelay IPC settles. Fire-and-forget let apply_workspace(newUrl) race ahead of the rebind: activation ran while start-on-launch agents were still pinned to the old URL and marked the relay activated for the session, silently skipping them until app relaunch. A rebind failure still commits — pins stay recoverable by re-editing the community. The fifth finding (stale "running in other communities" count) was already resolved by the slow cross-community poll tier added in 0f8fa7e. Split relay.rs's inline test module into relay/tests.rs (file-size guard, mirroring repos/tests.rs). Tested: cargo test --manifest-path desktop/src-tauri/Cargo.toml (1435 passed, incl. the new temp-file and fixture-agreement tests), clippy --all-targets -D warnings, rustfmt, desktop pnpm test (2955 passed, incl. the new fixture-agreement test), tsc --noEmit, biome check, pnpm check:file-sizes. Co-Authored-By: Claude Fable 5 <[email protected]> Signed-off-by: Matt Toohey <[email protected]>
1 parent 0f8fa7e commit a497408

9 files changed

Lines changed: 527 additions & 368 deletions

File tree

Lines changed: 47 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,47 @@
1+
[
2+
{
3+
"input": "wss://relay.example.com",
4+
"canonical": "wss://relay.example.com",
5+
"note": "already canonical"
6+
},
7+
{
8+
"input": " wss://relay.example.com// ",
9+
"canonical": "wss://relay.example.com",
10+
"note": "surrounding whitespace and trailing slashes are cosmetic"
11+
},
12+
{
13+
"input": "WSS://Relay.Example.COM:3000/Path",
14+
"canonical": "wss://relay.example.com:3000/Path",
15+
"note": "scheme and authority are case-insensitive (RFC 3986); the path is not"
16+
},
17+
{
18+
"input": "WS://RELAY-A.example.com:3000/",
19+
"canonical": "ws://relay-a.example.com:3000",
20+
"note": "ws scheme and port survive; case and trailing slash fold away"
21+
},
22+
{
23+
"input": "wss://Relay.Example.com/Path?Query=Value",
24+
"canonical": "wss://relay.example.com/Path?Query=Value",
25+
"note": "path and query are preserved case-sensitively"
26+
},
27+
{
28+
"input": "wss://relay.example.com/path//",
29+
"canonical": "wss://relay.example.com/path",
30+
"note": "trailing slashes after a path are cosmetic too"
31+
},
32+
{
33+
"input": "not-a-url/",
34+
"canonical": "not-a-url",
35+
"note": "schemeless values pass through trim/slash cleanup only"
36+
},
37+
{
38+
"input": "",
39+
"canonical": "",
40+
"note": "empty stays empty"
41+
},
42+
{
43+
"input": " ",
44+
"canonical": "",
45+
"note": "whitespace-only trims to empty"
46+
}
47+
]

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

Lines changed: 18 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -187,11 +187,24 @@ pub async fn apply_workspace(
187187
// symlink re-point below when a later switch moves it. Must land
188188
// before the activation task spawned after this closure starts
189189
// this workspace's agents. A bad candidate clears the entry, same
190-
// as the dotfile above.
191-
if let Err(error) =
192-
persist_workspace_repos_dir(nest, &relay_url, effective_repos_dir.as_deref())
193-
{
194-
eprintln!("buzz-desktop: persist per-relay repos dir failed: {error}");
190+
// as the dotfile above. Serialized on the store lock: a community
191+
// relay edit fires rebind_agent_relay (which moves this map's
192+
// entries under that lock) nearly simultaneously with this apply,
193+
// and both are read-modify-writes of the same file — unserialized,
194+
// one side's update would be lost.
195+
match state.managed_agents_store_lock.lock() {
196+
Ok(_store_guard) => {
197+
if let Err(error) = persist_workspace_repos_dir(
198+
nest,
199+
&relay_url,
200+
effective_repos_dir.as_deref(),
201+
) {
202+
eprintln!("buzz-desktop: persist per-relay repos dir failed: {error}");
203+
}
204+
}
205+
Err(error) => {
206+
eprintln!("buzz-desktop: persist per-relay repos dir skipped: {error}");
207+
}
195208
}
196209
if let Err(error) = ensure_repos_symlink(nest, effective_repos_dir.as_deref()) {
197210
eprintln!("buzz-desktop: repos dir setup failed: {error}");

‎desktop/src-tauri/src/managed_agents/repos.rs‎

Lines changed: 10 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -273,6 +273,12 @@ fn read_repos_dir_map(nest_root: &Path) -> BTreeMap<String, String> {
273273

274274
/// Persist the per-relay `repos_dir` map, removing the file when empty
275275
/// (mirrors [`write_persisted_repos_dir`]'s clear-by-removal).
276+
///
277+
/// The write goes through a temp file + rename so a crash mid-write cannot
278+
/// leave truncated JSON behind: [`read_repos_dir_map`] degrades a malformed
279+
/// file to an *empty* map, which would silently send every workspace's spawn
280+
/// back to the shared `REPOS` fallback — exactly the cross-workspace hazard
281+
/// the map exists to prevent.
276282
fn write_repos_dir_map(nest_root: &Path, map: &BTreeMap<String, String>) -> Result<(), String> {
277283
let path = nest_root.join(REPOS_DIR_MAP_FILE);
278284
if map.is_empty() {
@@ -284,7 +290,10 @@ fn write_repos_dir_map(nest_root: &Path, map: &BTreeMap<String, String>) -> Resu
284290
}
285291
let json = serde_json::to_string_pretty(map)
286292
.map_err(|e| format!("serialize {REPOS_DIR_MAP_FILE}: {e}"))?;
287-
fs::write(&path, format!("{json}\n")).map_err(|e| format!("write {}: {e}", path.display()))
293+
let tmp = nest_root.join(format!("{REPOS_DIR_MAP_FILE}.tmp"));
294+
fs::write(&tmp, format!("{json}\n")).map_err(|e| format!("write {}: {e}", tmp.display()))?;
295+
fs::rename(&tmp, &path)
296+
.map_err(|e| format!("rename {} -> {}: {e}", tmp.display(), path.display()))
288297
}
289298

290299
/// Upsert (or clear, on `None`/empty) the applied workspace's `repos_dir` in

‎desktop/src-tauri/src/managed_agents/repos/tests.rs‎

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -498,6 +498,30 @@ fn repos_dir_map_rejects_empty_relay_and_survives_malformed_file() {
498498
);
499499
}
500500

501+
#[test]
502+
fn repos_dir_map_write_leaves_no_temp_file() {
503+
let tmp = tempfile::tempdir().unwrap();
504+
let root = tmp.path().join(".buzz");
505+
fs::create_dir_all(&root).unwrap();
506+
507+
// The map is written via temp file + rename so a crash mid-write can
508+
// never leave truncated JSON (read degrades malformed to an empty map,
509+
// silently dropping isolation). A stale temp file — e.g. from a crash
510+
// between write and rename — must be overwritten, and no temp file may
511+
// outlive a successful write.
512+
fs::write(root.join(".repos-dirs.json.tmp"), "half-written{").unwrap();
513+
persist_workspace_repos_dir(&root, "wss://relay-a.example", Some("/Users/me/DevA")).unwrap();
514+
515+
assert_eq!(
516+
workspace_repos_dir_for_relay(&root, "wss://relay-a.example").as_deref(),
517+
Some("/Users/me/DevA")
518+
);
519+
assert!(
520+
!root.join(".repos-dirs.json.tmp").exists(),
521+
"the temp file is renamed into place, not left behind"
522+
);
523+
}
524+
501525
#[test]
502526
fn rebind_workspace_repos_dir_moves_entry_to_new_relay() {
503527
let tmp = tempfile::tempdir().unwrap();

0 commit comments

Comments
 (0)