Skip to content

Commit 289ddd3

Browse files
matt2eclaude
andcommitted
feat(desktop): scope the agents UI per community
Filter every managed-agent surface to the active community's relay so concurrently running workspaces stop bleeding into each other's UI (Phase 3 of lazy multi-workspace agents, building on the Phase 1 relay pinning and Phase 2 lazy activation): - Add agentRelayScope helpers: a frontend mirror of the backend relay normalizer plus agentBelongsToRelay / partitionAgentsByRelay / hasRunningAgentInCommunity. A blank pin follows the active community (same defense-in-depth fallback as effective_agent_relay_url), and a missing provider/community degrades to unscoped rather than blanking every surface. - Scope the useManagedAgentActions list — and the bulk stop, start/ stop/delete lookups, and presence derived from it — to the active relay via a new lenient useActiveRelayUrl hook. Persona delete keeps counting instances against the unscoped record set since deleting a persona removes instances in every community. - Gate the 5s managed-agents liveness poll on a running agent in this community; agents running in other communities render no process state here, so they no longer keep the poll alive. - Hold auto-restart for agents pinned to other communities — their working/observer signals are read from the active relay only, so a pure workspace switch must never fire a restart — and re-check the pin in the pre-fire re-fetch so a rebind cannot restart a foreign agent. - Scope mergeKnownAgentPubkeys' managed-agent source to the active relay; the relay-agent (kind:10100) source stays unfiltered. - Surface an "N agents running in other communities" line in the agents header so concurrent background agents stay discoverable. Tested: desktop pnpm test (2939 passed, incl. new agentRelayScope, knownAgentPubkeys, and autoRestartPolicy unit tests), tsc --noEmit, biome check, Playwright smoke project (537 passed, 5 failed; 2 of the failures passed on rerun and the other 3 — channels intro-scroll, video review mode, shared-compute empty state — reproduce on baseline HEAD without this change, so all 5 are pre-existing flakes). Co-Authored-By: Claude Fable 5 <[email protected]> Signed-off-by: Matt Toohey <[email protected]>
1 parent a0dd28d commit 289ddd3

13 files changed

Lines changed: 417 additions & 13 deletions
Lines changed: 129 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,129 @@
1+
import assert from "node:assert/strict";
2+
import test from "node:test";
3+
4+
import {
5+
agentBelongsToRelay,
6+
hasRunningAgentInCommunity,
7+
normalizeRelayUrlForCompare,
8+
partitionAgentsByRelay,
9+
} from "./agentRelayScope.ts";
10+
11+
const RELAY_A = "ws://relay-a.example.com:3000";
12+
const RELAY_B = "wss://relay-b.example.com";
13+
14+
// ── normalizeRelayUrlForCompare ──────────────────────────────────────────────
15+
// Must agree with the Rust `normalize_relay_url` (desktop/src-tauri/src/relay.rs)
16+
// because record pins are stamped by the backend and compared here. These
17+
// vectors mirror the Rust unit tests.
18+
19+
test("normalize_stripsWhitespaceAndTrailingSlashes", () => {
20+
assert.equal(
21+
normalizeRelayUrlForCompare(" wss://relay.example.com// "),
22+
"wss://relay.example.com",
23+
);
24+
});
25+
26+
test("normalize_lowercasesSchemeAndAuthority_preservesPathCase", () => {
27+
assert.equal(
28+
normalizeRelayUrlForCompare("WSS://Relay.Example.COM:3000/Path"),
29+
"wss://relay.example.com:3000/Path",
30+
);
31+
});
32+
33+
test("normalize_schemelessInput_passesThroughTrimmed", () => {
34+
assert.equal(normalizeRelayUrlForCompare("not-a-url/"), "not-a-url");
35+
});
36+
37+
// ── agentBelongsToRelay ──────────────────────────────────────────────────────
38+
39+
test("belongs_exactMatch", () => {
40+
assert.equal(agentBelongsToRelay(RELAY_A, RELAY_A), true);
41+
});
42+
43+
test("belongs_cosmeticDifferences_stillMatch", () => {
44+
// Trailing slash and scheme/host case must not split an agent from its
45+
// community — this is exactly what the shared normalizer exists for.
46+
assert.equal(
47+
agentBelongsToRelay("WS://RELAY-A.example.com:3000/", RELAY_A),
48+
true,
49+
);
50+
});
51+
52+
test("belongs_differentRelay_doesNotMatch", () => {
53+
assert.equal(agentBelongsToRelay(RELAY_A, RELAY_B), false);
54+
});
55+
56+
test("belongs_blankPin_followsActiveCommunity", () => {
57+
// Defense-in-depth mirror of the backend's `effective_agent_relay_url`
58+
// blank fallback: a record that escaped stamping follows the visited
59+
// community instead of vanishing from every community.
60+
assert.equal(agentBelongsToRelay("", RELAY_A), true);
61+
assert.equal(agentBelongsToRelay(" ", RELAY_B), true);
62+
assert.equal(agentBelongsToRelay(undefined, RELAY_A), true);
63+
});
64+
65+
test("belongs_noActiveCommunityRelay_degradesToUnscoped", () => {
66+
assert.equal(agentBelongsToRelay(RELAY_A, null), true);
67+
assert.equal(agentBelongsToRelay(RELAY_A, ""), true);
68+
assert.equal(agentBelongsToRelay(RELAY_A, undefined), true);
69+
});
70+
71+
// ── partitionAgentsByRelay: the agent-list filter ────────────────────────────
72+
73+
test("partition_scopesListToActiveCommunity", () => {
74+
// Two communities' agents coexist after lazy activation; the list the
75+
// user sees in community A must contain only A's agents (plus blank-pin
76+
// strays), with B's surfaced only through the "other communities" count.
77+
const agents = [
78+
{ pubkey: "a1", relayUrl: RELAY_A },
79+
{ pubkey: "b1", relayUrl: RELAY_B },
80+
{ pubkey: "a2", relayUrl: `${RELAY_A}/` },
81+
{ pubkey: "stray", relayUrl: "" },
82+
];
83+
84+
const { inCommunity, other } = partitionAgentsByRelay(agents, RELAY_A);
85+
86+
assert.deepEqual(
87+
inCommunity.map((agent) => agent.pubkey),
88+
["a1", "a2", "stray"],
89+
);
90+
assert.deepEqual(
91+
other.map((agent) => agent.pubkey),
92+
["b1"],
93+
);
94+
});
95+
96+
test("partition_undefinedAgents_yieldsEmpty", () => {
97+
const { inCommunity, other } = partitionAgentsByRelay(undefined, RELAY_A);
98+
assert.deepEqual(inCommunity, []);
99+
assert.deepEqual(other, []);
100+
});
101+
102+
// ── hasRunningAgentInCommunity: the polling gate ─────────────────────────────
103+
104+
test("pollingGate_runningAgentInOtherCommunity_doesNotPoll", () => {
105+
// A workspace switch leaves the previous community's agents running; they
106+
// must not keep this community's 5s liveness poll alive.
107+
const agents = [
108+
{ relayUrl: RELAY_B, status: "running" },
109+
{ relayUrl: RELAY_A, status: "stopped" },
110+
];
111+
112+
assert.equal(hasRunningAgentInCommunity(agents, RELAY_A), false);
113+
});
114+
115+
test("pollingGate_runningAgentInThisCommunity_polls", () => {
116+
const agents = [
117+
{ relayUrl: RELAY_B, status: "running" },
118+
{ relayUrl: RELAY_A, status: "running" },
119+
];
120+
121+
assert.equal(hasRunningAgentInCommunity(agents, RELAY_A), true);
122+
});
123+
124+
test("pollingGate_blankPinRunningAgent_polls", () => {
125+
assert.equal(
126+
hasRunningAgentInCommunity([{ relayUrl: "", status: "running" }], RELAY_A),
127+
true,
128+
);
129+
});
Lines changed: 98 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,98 @@
1+
/**
2+
* Relay-scoping for managed agents. Every managed-agent record is pinned to
3+
* its home relay (`ManagedAgent.relayUrl`, stamped by the backend at create),
4+
* and the desktop UI presents agents per community — so every surface that
5+
* lists, counts, or acts on managed agents must scope to the active
6+
* community's relay through these helpers. Agents pinned to other relays
7+
* keep running in the background; they are just not "in" this community.
8+
*/
9+
10+
/**
11+
* Canonical form of a relay URL for identity comparisons — NOT for
12+
* connecting. Frontend mirror of `normalize_relay_url` in
13+
* `desktop/src-tauri/src/relay.rs`; the two must agree because record pins
14+
* are stamped by the backend and compared here: trim, strip trailing
15+
* slashes, lowercase scheme + authority (case-insensitive per RFC 3986),
16+
* preserve any path or query case-sensitively.
17+
*
18+
* Distinct from `normalizeRelayUrl` in `communityStorage.ts` (input
19+
* canonicalisation: prepends `wss://`) and in `selfProfileStorage.ts`
20+
* (storage keys: lowercases the whole URL, path included).
21+
*/
22+
export function normalizeRelayUrlForCompare(url: string): string {
23+
const trimmed = url.trim().replace(/\/+$/, "");
24+
const schemeEnd = trimmed.indexOf("://");
25+
if (schemeEnd === -1) {
26+
return trimmed;
27+
}
28+
const scheme = trimmed.slice(0, schemeEnd);
29+
const rest = trimmed.slice(schemeEnd + "://".length);
30+
const pathStart = rest.indexOf("/");
31+
const authority = pathStart === -1 ? rest : rest.slice(0, pathStart);
32+
const path = pathStart === -1 ? "" : rest.slice(pathStart);
33+
return `${scheme.toLowerCase()}://${authority.toLowerCase()}${path}`;
34+
}
35+
36+
/**
37+
* Whether an agent record belongs to the given community relay.
38+
*
39+
* A blank pin follows the active community — the same defense-in-depth
40+
* fallback as the backend's `effective_agent_relay_url` for records that
41+
* escaped stamping. A blank/absent community relay (no provider, no active
42+
* community yet) degrades to unscoped rather than blanking every surface.
43+
*/
44+
export function agentBelongsToRelay(
45+
agentRelayUrl: string | null | undefined,
46+
communityRelayUrl: string | null | undefined,
47+
): boolean {
48+
const community = communityRelayUrl?.trim() ?? "";
49+
if (community === "") {
50+
return true;
51+
}
52+
const pinned = agentRelayUrl?.trim() ?? "";
53+
if (pinned === "") {
54+
return true;
55+
}
56+
return (
57+
normalizeRelayUrlForCompare(pinned) ===
58+
normalizeRelayUrlForCompare(community)
59+
);
60+
}
61+
62+
/**
63+
* Split agents into those pinned to the active community's relay and the
64+
* rest. `inCommunity` drives the agents screen; `other` exists only for
65+
* cross-community affordances (the "running in other communities" count).
66+
*/
67+
export function partitionAgentsByRelay<T extends { relayUrl?: string | null }>(
68+
agents: readonly T[] | undefined,
69+
communityRelayUrl: string | null | undefined,
70+
): { inCommunity: T[]; other: T[] } {
71+
const inCommunity: T[] = [];
72+
const other: T[] = [];
73+
for (const agent of agents ?? []) {
74+
if (agentBelongsToRelay(agent.relayUrl, communityRelayUrl)) {
75+
inCommunity.push(agent);
76+
} else {
77+
other.push(agent);
78+
}
79+
}
80+
return { inCommunity, other };
81+
}
82+
83+
/**
84+
* The managed-agents polling gate: poll only while an agent *in this
85+
* community* is running. Agents running in other communities don't render
86+
* process state on this community's surfaces, so they must not keep its
87+
* 5s liveness poll alive.
88+
*/
89+
export function hasRunningAgentInCommunity(
90+
agents: readonly { relayUrl?: string | null; status: string }[] | undefined,
91+
communityRelayUrl: string | null | undefined,
92+
): boolean {
93+
return (agents ?? []).some(
94+
(agent) =>
95+
agent.status === "running" &&
96+
agentBelongsToRelay(agent.relayUrl, communityRelayUrl),
97+
);
98+
}

‎desktop/src/features/agents/hooks.ts‎

Lines changed: 8 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,12 +1,14 @@
11
import * as React from "react";
22
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
33

4+
import { hasRunningAgentInCommunity } from "@/features/agents/agentRelayScope";
45
import {
56
attachManagedAgentToChannel,
67
createChannelManagedAgents,
78
ensureChannelAgentPresetInChannel,
89
provisionChannelManagedAgent,
910
} from "@/features/agents/channelAgents";
11+
import { useActiveRelayUrl } from "@/features/communities/useCommunities";
1012
import { resolveSnapshotAvatarPng } from "@/features/agents/ui/snapshotAvatarPng";
1113
import {
1214
channelsQueryKey,
@@ -280,6 +282,7 @@ export function useRelayAgentsQuery(options?: { enabled?: boolean }) {
280282
}
281283

282284
export function useManagedAgentsQuery(options?: { enabled?: boolean }) {
285+
const activeRelayUrl = useActiveRelayUrl();
283286
return useQuery({
284287
enabled: options?.enabled ?? true,
285288
queryKey: managedAgentsQueryKey,
@@ -291,10 +294,11 @@ export function useManagedAgentsQuery(options?: { enabled?: boolean }) {
291294
// with no relay event to signal it, so this poll is the only liveness
292295
// path for them. When nothing is running there IS an event path —
293296
// `agents-data-changed` (control-plane changes) — so the idle branch
294-
// drops its poll entirely rather than falling back to 30s.
295-
return agents?.some((agent) => agent.status === "running")
296-
? 5_000
297-
: false;
297+
// drops its poll entirely rather than falling back to 30s. Scoped to
298+
// the active community's relay: agents left running in other
299+
// communities render no process state on this community's surfaces,
300+
// so they must not keep its poll alive.
301+
return hasRunningAgentInCommunity(agents, activeRelayUrl) ? 5_000 : false;
298302
},
299303
});
300304
}

‎desktop/src/features/agents/knownAgentPubkeys.test.mjs‎

Lines changed: 57 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -34,3 +34,60 @@ test("normalisesCaseAndWhitespace_dedupingAcrossSources", () => {
3434

3535
assert.deepEqual([...merged], [MANAGED]);
3636
});
37+
38+
// ── relay scoping ────────────────────────────────────────────────────────────
39+
40+
const RELAY_A = "ws://relay-a.example.com:3000";
41+
const RELAY_B = "wss://relay-b.example.com";
42+
43+
test("managedAgentPinnedToOtherRelay_excludedWhenScoped", () => {
44+
// With multiple communities' agents running concurrently, a managed agent
45+
// pinned to relay B is not an agent "in" community A — it must not enter
46+
// A's known-agent baseline just because it's locally managed.
47+
const merged = mergeKnownAgentPubkeys(
48+
[
49+
{ pubkey: MANAGED, relayUrl: RELAY_B },
50+
// Cosmetic URL differences must not split an agent from its community.
51+
{ pubkey: RELAY, relayUrl: `${RELAY_A}/` },
52+
],
53+
undefined,
54+
RELAY_A,
55+
);
56+
57+
assert.deepEqual([...merged], [RELAY]);
58+
});
59+
60+
test("blankPinnedRelay_followsActiveCommunity", () => {
61+
// Defense-in-depth mirror of the backend's blank-relay fallback: a record
62+
// that escaped stamping belongs to whichever community is visited.
63+
const merged = mergeKnownAgentPubkeys(
64+
[{ pubkey: MANAGED, relayUrl: "" }],
65+
undefined,
66+
RELAY_A,
67+
);
68+
69+
assert.deepEqual([...merged], [MANAGED]);
70+
});
71+
72+
test("relayAgents_neverRelayFiltered", () => {
73+
// Relay agents come from the active relay's own kind:10100 profiles —
74+
// already community-scoped at the source, so the merge must keep them
75+
// even when a managed-agent scope is in effect.
76+
const merged = mergeKnownAgentPubkeys(
77+
[{ pubkey: MANAGED, relayUrl: RELAY_B }],
78+
[{ pubkey: RELAY }],
79+
RELAY_A,
80+
);
81+
82+
assert.deepEqual([...merged], [RELAY]);
83+
});
84+
85+
test("noActiveRelay_degradesToUnscopedMerge", () => {
86+
const merged = mergeKnownAgentPubkeys(
87+
[{ pubkey: MANAGED, relayUrl: RELAY_B }],
88+
undefined,
89+
null,
90+
);
91+
92+
assert.deepEqual([...merged], [MANAGED]);
93+
});

‎desktop/src/features/agents/knownAgentPubkeys.ts‎

Lines changed: 16 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,19 +1,32 @@
1+
import { agentBelongsToRelay } from "@/features/agents/agentRelayScope";
12
import { normalizePubkey } from "@/shared/lib/pubkey";
23

34
/**
45
* Pure merge behind `useKnownAgentPubkeys`: managed agents ∪ relay agents,
56
* normalised via `normalizePubkey` so membership checks work against
67
* normalised pubkeys.
78
*
8-
* Structurally typed on `{ pubkey }` so node unit tests don't need to build
9-
* full `ManagedAgent`/`RelayAgent` values.
9+
* Managed agents are scoped to `activeRelayUrl` (the active community's
10+
* relay): the baseline answers "is this pubkey an agent *in this
11+
* community*", and a locally managed agent pinned to another community's
12+
* relay is not — it neither posts here nor appears in this community's
13+
* directory. An agent genuinely present on both relays is still covered by
14+
* the relay-agent source (kind:10100 from the active relay), which is never
15+
* relay-filtered. Omitting `activeRelayUrl` degrades to the unscoped merge.
16+
*
17+
* Structurally typed on `{ pubkey, relayUrl? }` so node unit tests don't
18+
* need to build full `ManagedAgent`/`RelayAgent` values.
1019
*/
1120
export function mergeKnownAgentPubkeys(
12-
managedAgents: readonly { pubkey: string }[] | undefined,
21+
managedAgents:
22+
| readonly { pubkey: string; relayUrl?: string | null }[]
23+
| undefined,
1324
relayAgents: readonly { pubkey: string }[] | undefined,
25+
activeRelayUrl?: string | null,
1426
): ReadonlySet<string> {
1527
const pubkeys = new Set<string>();
1628
for (const agent of managedAgents ?? []) {
29+
if (!agentBelongsToRelay(agent.relayUrl, activeRelayUrl)) continue;
1730
pubkeys.add(normalizePubkey(agent.pubkey));
1831
}
1932
for (const agent of relayAgents ?? []) {

0 commit comments

Comments
 (0)