Files
buzz/desktop/src/features/agents/managedAgentRuntimeHooks.test.mjs
Will Pfleger 83aab8cb5c feat(desktop): remove communities locally and stop their agent pairs (#7997)
🤖 Leave contacts the relay before it removes anything locally: it checks
the relay's `/info` for NIP-43 membership support, then waits for the
relay to accept a signed leave request. When a relay has been torn down,
that check fails, Leave throws, and the community stays in the rail.
Removing a community also left its relay's managed agent pairs running,
and they kept reconnecting to it until the app was quit.

**Remove from this device**
- A new community action, **Remove from this device**, sits under
**Leave community** in the profile menu's community actions. It never
contacts the relay. A confirm dialog explains that relay membership
isn't revoked.
- `useCommunityNavigationTransitions` splits the old `removeCommunity`
into `removeCommunityFromDevice` (local-only cleanup and navigation to a
fallback community or the discovery screen) and
`leaveAndRemoveCommunity` (calls `leaveCommunity`, then runs the same
cleanup). Leave's flow hasn't changed.
- When Leave fails, the error now adds: "If the community no longer
exists, use Remove from this device." The error shown when community
discovery state can't be saved no longer says "Membership was removed",
so its wording fits both actions.

**Agent pairs on a removed relay**
- Once the local removal completes, the shared cleanup stops every live
agent pair on that relay, including manually started ones. It matches
relays with `canonicalRelayUrl`. Stopping is best-effort: failures are
logged and the removal still completes. Pairs on other relays aren't
touched, and nothing is stopped if another community still uses the same
relay.
- Both reconcile call sites (`useManagedAgentRuntimeReconciliation` and
`bootstrapManagedAgentRuntimePairs`) now go through
`reconcileConfiguredManagedAgentRuntimes`. A reconcile that is already
running in Rust can't be cancelled, so after it resolves, this helper
stops any pair it started whose relay is no longer in the saved
community list.
- Launch restore runs in the background after `apply_workspace` and can
finish after its community is removed. `apply_workspace` takes a restore
ticket (the current `launch_restore_generation` in `AppState`) before
handing its lock to the restore task. Removing the active community
calls the new `invalidate_launch_restore` command, which bumps that
generation while holding the runtime transition lock.
`restore_managed_agents_on_launch` re-checks its ticket under the same
lock and spawns nothing if it changed. If restore takes the lock first,
its pairs are registered before invalidation returns, and the removal
stop then finds them. Removal never changes `relay_url_override`: the
outgoing relay stays applied until the next `apply_workspace`, exactly
as on `main`, so in-flight work never falls back to the default relay.
Invalidation never takes `workspace_apply_lock`, which restore holds
while waiting on the transition lock, so lock order is unchanged.
- With no relay applied, backend readers fall back to the default relay,
the same state as launch before the first `apply_workspace`. A normal
quit and relaunch doesn't bring a pair back on a removed relay: restore
targets the applied workspace, and the legacy per-record relay pin is
ignored.

**Tests**
- A `community-rail` e2e case makes the mocked relay's membership check
fail, the way an unreachable relay does. It checks that Leave shows the
error and keeps the community, and that Remove from this device then
removes it, switches to the fallback, stops the agent pair on the
removed relay, and leaves the pair on the other relay running.
- Unit tests in `managedAgentRelayCleanup.test.mjs` cover relay
matching, a stop or listing failure not throwing, and the reconcile
fence stopping a pair that started on a relay removed mid-flight.

---------

Signed-off-by: Will Pfleger <pfleger.will@gmail.com>
Co-authored-by: Duncan <dcfd242e557282d7a1e2cf2e6877522682f1e5c6156dc92ca7d90eaedd3b0f95@buzz.block.builderlab.xyz>
2026-10-01 18:43:21 +00:00

143 lines
4.1 KiB
JavaScript

import assert from "node:assert/strict";
import test from "node:test";
import { restartManagedAgentPair } from "./managedAgentRuntimeHooks.ts";
// ---------------------------------------------------------------------------
// restartManagedAgentPair: discriminating regression tests for the pair
// restart lifecycle boundary (stop → relay-scoped clear → start).
//
// These tests exercise the exact function called by useManagedAgentRuntimeAction's
// mutationFn restart branch, so reverting to the old combined Rust command
// (which cleared only in onSuccess, after the new process was already running)
// would make tests (a) and (c) fail.
// ---------------------------------------------------------------------------
const PUBKEY = "deadbeef".repeat(8);
const RELAY = "wss://relay.example";
/** Returns a resolved-status stub sufficient for the return-type assertion. */
function makeStatus() {
return {
pubkey: PUBKEY,
relayUrl: RELAY,
localSetup: true,
lifecycle: "running",
};
}
test("test_pair_restart_stop_success_start_failure_clear_still_ran", async () => {
// Stop succeeds, start throws. The clear must have fired — badge is gone
// regardless of the start failure. On the old combined-command approach,
// a rejected command meant onSuccess never ran and the badge survived.
let clearFired = false;
await assert.rejects(
restartManagedAgentPair(
PUBKEY,
RELAY,
async () => makeStatus(), // stop succeeds
(_pubkey, _relayUrl) => {
clearFired = true;
},
async () => {
throw new Error("start failed");
},
),
/start failed/,
);
assert.ok(
clearFired,
"clear must fire at stop-success boundary even when start subsequently fails",
);
});
test("test_pair_restart_stop_failure_neither_clear_nor_start_called", async () => {
// Stop throws. Neither clear nor start should run — clearing on a failed
// stop would remove a badge that is still legitimately active.
let clearFired = false;
let startCalled = false;
await assert.rejects(
restartManagedAgentPair(
PUBKEY,
RELAY,
async () => {
throw new Error("stop failed");
},
(_pubkey, _relayUrl) => {
clearFired = true;
},
async () => {
startCalled = true;
return makeStatus();
},
),
/stop failed/,
);
assert.ok(!clearFired, "clear must NOT fire when stop itself fails");
assert.ok(!startCalled, "start must NOT be called when stop fails");
});
test("test_pair_restart_strict_stop_clear_start_ordering", async () => {
// Verify the operations fire in the guaranteed order: stop → clear → start.
// A clear that fires after start begins can tombstone genuine new turns.
const events = [];
await restartManagedAgentPair(
PUBKEY,
RELAY,
async () => {
events.push("stop");
return makeStatus();
},
(_pubkey, _relayUrl) => {
events.push("clear");
},
async () => {
events.push("start");
return makeStatus();
},
);
assert.deepEqual(
events,
["stop", "clear", "start"],
"operations must fire in stop → clear → start order",
);
});
test("a pair restart whose relay is removed during its stop never starts, even after a re-add", async () => {
const { markRelayRemoved } = await import("./managedAgentRelayCleanup.ts");
const relay = "wss://removed-during-restart.example";
let releaseStop;
let started = 0;
const run = () =>
restartManagedAgentPair(
PUBKEY,
relay,
() =>
new Promise((resolve) => (releaseStop = () => resolve(makeStatus()))),
() => {},
async () => {
started += 1;
return makeStatus();
},
);
const stale = run();
// Remove, then re-add: the re-add never resets the removal counter.
markRelayRemoved(relay);
releaseStop();
await assert.rejects(stale, /relay was removed from this device/);
assert.equal(started, 0);
// Positive control: a restart begun after the re-add starts.
const fresh = run();
releaseStop();
await fresh;
assert.equal(started, 1);
});