Files
buzz/desktop/src/features/agents/useKnownAgentPubkeys.tsx
Logan Johnson 5073e075d7 fix(desktop): unify owned-agent cloud provenance markers (#7129)
Unify presentation-only cloud provenance across agent identity surfaces. Keep successful local-inventory and verified-ownership gates; preserve main availability and mention spacing behavior.

Co-authored-by: Larry <627498bd4bd1f281a16431e3c6cce3b5c25b6692798c78672298aefbf2f8f8b5@buzz.block.builderlab.xyz>
Signed-off-by: Logan Johnson <loganj@squareup.com>
2026-09-03 02:35:37 +00:00

148 lines
5.5 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

import * as React from "react";
import {
useManagedAgentsQuery,
useRelayAgentsQuery,
} from "@/features/agents/hooks";
import { mergeKnownAgentPubkeys } from "@/features/agents/knownAgentPubkeys";
import { useStableMap, useStableSet } from "@/shared/hooks/useStableReference";
import { useIdentityQuery } from "@/shared/api/hooks";
import { normalizePubkey } from "@/shared/lib/pubkey";
import { isAgentDirectoryReady } from "./lib/agentAutocompleteEligibility";
import { isOwnedAgentNotManagedOnDevice } from "./lib/otherSetupAgent";
const EMPTY_KNOWN_AGENT_PUBKEYS: ReadonlySet<string> = new Set();
const AgentManagementContext = React.createContext<{
currentPubkey?: string;
localInventoryReady: boolean;
localPubkeys: ReadonlySet<string>;
relayOwners: ReadonlyMap<string, string | null>;
}>({
localInventoryReady: false,
localPubkeys: new Set(),
relayOwners: new Map(),
});
const KnownAgentPubkeysContext = React.createContext<ReadonlySet<string>>(
EMPTY_KNOWN_AGENT_PUBKEYS,
);
/**
* Owns the app's only React Query subscription to the known-agent source
* queries and publishes the merged set over context.
*
* The subscription lives here — not in `useKnownAgentPubkeys` — on purpose.
* Consumers include every mounted `MessageRow`; if each consumer held its own
* query observers, every batch of row mounts (channel switch, thread panel
* open, load-older) would find short-staleTime data stale and re-trigger
* fetches via `refetchOnMount`, including the deliberately relaxed
* whole-profile-set `listRelayAgents` relay query. And each source-query data
* churn (managed agents poll at 5s while an agent runs) would re-render every
* row before `useStableSet` could bail. With the single subscription here,
* query churn re-renders only this provider — `children` is referentially
* stable, so nothing cascades — and context consumers re-render only when the
* published set's identity changes, which `useStableSet` restricts to actual
* membership change.
*
* Mounted once per community inside `AppReady` (under the community-keyed
* `CommunityQueryProvider` remount boundary), so the observers tear down and
* re-create on community switch without a `resetCommunityState()` entry.
*/
export function KnownAgentPubkeysProvider({
children,
}: {
children: React.ReactNode;
}) {
const managedQuery = useManagedAgentsQuery();
const relayQuery = useRelayAgentsQuery();
const currentPubkey = useIdentityQuery().data?.pubkey;
const managedAgents = managedQuery.data;
const relayAgents = relayQuery.data;
const localPubkeys = useStableSet(
new Set(
(managedAgents ?? []).map((agent) => normalizePubkey(agent.pubkey)),
),
);
const relayOwners = useStableMap(
new Map(
isAgentDirectoryReady(relayQuery)
? (relayAgents ?? []).map((agent) => [
normalizePubkey(agent.pubkey),
agent.ownerPubkey,
])
: [],
),
);
const localInventoryReady = isAgentDirectoryReady(managedQuery);
const management = React.useMemo(
() => ({
currentPubkey,
localInventoryReady,
localPubkeys,
relayOwners,
}),
[currentPubkey, localInventoryReady, localPubkeys, relayOwners],
);
const merged = React.useMemo(
() => mergeKnownAgentPubkeys(managedAgents, relayAgents),
[managedAgents, relayAgents],
);
const stable = useStableSet(merged);
return (
<KnownAgentPubkeysContext.Provider value={stable}>
<AgentManagementContext.Provider value={management}>
{children}
</AgentManagementContext.Provider>
</KnownAgentPubkeysContext.Provider>
);
}
/**
* The community-scoped "known agent pubkeys" baseline: locally managed agents
* ∪ relay-registered agents, normalised via `normalizePubkey`. Home-feed agent
* activity is intentionally excluded: it is a display category, not an
* authenticated agent-identity source.
*
* Every surface that decides whether a pubkey belongs to an agent — the
* config-nudge trust gate, bot avatars/popovers, agent mention pills — must
* share this baseline. Surfaces previously derived their own sets from
* different source subsets, so the same event could pass the trust gate on
* one screen and fail it on another.
*
* Surface-local signals stay additive on top: merge channel-member roles or
* a profile lookup's `isAgent` flags at the call site (or check
* `profiles[normalizePubkey(pk)]?.isAgent` per pubkey). They can only widen
* the baseline, never diverge from it.
*
* Reads content-stable context published by `KnownAgentPubkeysProvider` —
* consumers add no query observers and re-render only when membership
* actually changes, so the set is safe as a memo/comparator dependency in
* render-hot consumers. Outside the provider (unit tests, stray surfaces)
* this degrades gracefully to the empty set; surfaces still fold in their
* local `isAgent` profile flags.
*/
export function useKnownAgentPubkeys(): ReadonlySet<string> {
return React.useContext(KnownAgentPubkeysContext);
}
/** Shared provenance without per-row query observers; exact keys, never personas. */
export function useIsOtherSetupAgent(
pubkey?: string | null,
profileOwnerPubkey?: string | null,
): boolean {
const state = React.useContext(AgentManagementContext);
const key = normalizePubkey(pubkey ?? "");
return (
Boolean(key) &&
isOwnedAgentNotManagedOnDevice({
currentPubkey: state.currentPubkey,
ownerPubkey: profileOwnerPubkey ?? state.relayOwners.get(key),
localInventoryReady: state.localInventoryReady,
isLocallyManaged: state.localPubkeys.has(key),
})
);
}