fix(desktop): centralize known-agent trust set in useKnownAgentPubkeys (#1703)

Signed-off-by: Matt Toohey <contact@matttoohey.com>
Signed-off-by: npub12gtutshhh76rx0jx697f32f9tffd4hhp3hx58fp4x6u4uemkm7sqf8f757 <5217c5c2f7bfb4333e46d17c98a9255a52dadee18dcd43a43536b95e6776dfa0@sprout-oss.stage.blox.sqprod.co>
Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
Co-authored-by: npub12gtutshhh76rx0jx697f32f9tffd4hhp3hx58fp4x6u4uemkm7sqf8f757 <5217c5c2f7bfb4333e46d17c98a9255a52dadee18dcd43a43536b95e6776dfa0@sprout-oss.stage.blox.sqprod.co>
This commit is contained in:
Matt Toohey
2026-07-14 01:01:46 +10:00
committed by GitHub
parent 5050bb0f7e
commit 095f3c7280
22 changed files with 655 additions and 135 deletions

View File

@@ -325,7 +325,11 @@ const overrides = new Map([
// (reply-inclusive; would clear unread state early). The file was already
// at the 1000 ceiling; comment-only overage, not code growth. Queued to
// split with the rest of this list.
["src/features/channels/ui/ChannelScreen.tsx", 1002],
// member-agent-flags: messageProfiles merge + ref stabilisation split out to
// useMessageProfiles.ts, ratcheting 1002 -> 972 (under the 1000 default;
// entry kept as a ratchet). +7 rebase onto main (#1698 timeline-window
// growth), 972 -> 979.
["src/features/channels/ui/ChannelScreen.tsx", 979],
// forced-unread persistence: markChannelUnread now writes through to
// forcedUnreadStore (localStorage) so the sidebar badge survives reload and
// the rail observer can read it. Three clear points added (markChannelRead,

View File

@@ -15,6 +15,7 @@ import {
import { router } from "@/app/router";
import { ThemeGrainientBackground } from "@/app/ThemeGrainientBackground";
import { useReloadShortcut } from "@/app/useReloadShortcut";
import { KnownAgentPubkeysProvider } from "@/features/agents/useKnownAgentPubkeys";
import { useAppOnboardingState } from "@/features/onboarding/hooks";
import { OnboardingSlideTransition } from "@/features/onboarding/ui/OnboardingSlideTransition";
import { OnboardingFlow } from "@/features/onboarding/ui/OnboardingFlow";
@@ -327,7 +328,11 @@ function AppReady({
return isWorkspaceSwitch ? <WorkspaceSwitchGate /> : <AppLoadingGate />;
}
return <RouterProvider router={router} />;
return (
<KnownAgentPubkeysProvider>
<RouterProvider router={router} />
</KnownAgentPubkeysProvider>
);
}
export function App() {

View File

@@ -0,0 +1,36 @@
import assert from "node:assert/strict";
import test from "node:test";
import { mergeKnownAgentPubkeys } from "./knownAgentPubkeys.ts";
const MANAGED =
"1111111111111111111111111111111111111111111111111111111111111111";
const RELAY =
"2222222222222222222222222222222222222222222222222222222222222222";
test("mergesTrustedSources", () => {
const merged = mergeKnownAgentPubkeys(
[{ pubkey: MANAGED }],
[{ pubkey: RELAY }],
);
assert.deepEqual([...merged].sort(), [MANAGED, RELAY].sort());
});
test("undefinedSources_yieldEmptySet", () => {
const merged = mergeKnownAgentPubkeys(undefined, undefined);
assert.equal(merged.size, 0);
});
test("normalisesCaseAndWhitespace_dedupingAcrossSources", () => {
// The same agent appearing in multiple sources with different casing /
// stray whitespace must collapse to one normalised entry, so membership
// checks against normalizePubkey output always hit.
const merged = mergeKnownAgentPubkeys(
[{ pubkey: MANAGED.toUpperCase() }],
[{ pubkey: ` ${MANAGED}` }],
);
assert.deepEqual([...merged], [MANAGED]);
});

View File

@@ -0,0 +1,23 @@
import { normalizePubkey } from "@/shared/lib/pubkey";
/**
* Pure merge behind `useKnownAgentPubkeys`: managed agents ∪ relay agents,
* normalised via `normalizePubkey` so membership checks work against
* normalised pubkeys.
*
* Structurally typed on `{ pubkey }` so node unit tests don't need to build
* full `ManagedAgent`/`RelayAgent` values.
*/
export function mergeKnownAgentPubkeys(
managedAgents: readonly { pubkey: string }[] | undefined,
relayAgents: readonly { pubkey: string }[] | undefined,
): ReadonlySet<string> {
const pubkeys = new Set<string>();
for (const agent of managedAgents ?? []) {
pubkeys.add(normalizePubkey(agent.pubkey));
}
for (const agent of relayAgents ?? []) {
pubkeys.add(normalizePubkey(agent.pubkey));
}
return pubkeys;
}

View File

@@ -0,0 +1,84 @@
import * as React from "react";
import {
useManagedAgentsQuery,
useRelayAgentsQuery,
} from "@/features/agents/hooks";
import { mergeKnownAgentPubkeys } from "@/features/agents/knownAgentPubkeys";
import { useStableSet } from "@/shared/hooks/useStableReference";
const EMPTY_KNOWN_AGENT_PUBKEYS: ReadonlySet<string> = new Set();
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 workspace inside `AppReady` (under the workspace-keyed
* `WorkspaceQueryProvider` remount boundary), so the observers tear down and
* re-create on workspace switch without a `resetWorkspaceState()` entry.
*/
export function KnownAgentPubkeysProvider({
children,
}: {
children: React.ReactNode;
}) {
const managedAgents = useManagedAgentsQuery().data;
const relayAgents = useRelayAgentsQuery().data;
const merged = React.useMemo(
() => mergeKnownAgentPubkeys(managedAgents, relayAgents),
[managedAgents, relayAgents],
);
const stable = useStableSet(merged);
return (
<KnownAgentPubkeysContext.Provider value={stable}>
{children}
</KnownAgentPubkeysContext.Provider>
);
}
/**
* The workspace-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);
}

View File

@@ -609,7 +609,6 @@ export const ChannelPane = React.memo(function ChannelPane({
) : null}
<MessageTimeline
ref={messageTimelineRef}
agentPubkeys={agentPubkeys}
channelId={activeChannel?.id}
channelIntro={channelIntro}
directMessageIntro={directMessageIntro}
@@ -795,7 +794,6 @@ export const ChannelPane = React.memo(function ChannelPane({
(() => {
const panel = (
<MessageThreadPanel
agentPubkeys={agentPubkeys}
channel={activeChannel}
channelId={activeChannel?.id ?? null}
channelName={activeChannel?.name ?? "channel"}

View File

@@ -22,6 +22,7 @@ import {
usePersonasQuery,
useRelayAgentsQuery,
} from "@/features/agents/hooks";
import { useKnownAgentPubkeys } from "@/features/agents/useKnownAgentPubkeys";
import {
mergeMessages,
useChannelMessagesQuery,
@@ -54,10 +55,6 @@ import { useThreadReplies } from "@/features/messages/useThreadReplies";
import { useChannelTyping } from "@/features/messages/useChannelTyping";
import type { TimelineMessage } from "@/features/messages/types";
import { useUsersBatchQuery } from "@/features/profile/hooks";
import {
mergeCurrentProfileIntoLookup,
profileLookupsEqual,
} from "@/features/profile/lib/identity";
import type { RelayEvent, RespondToMode, SearchHit } from "@/shared/api/types";
import { useChannelFind } from "@/features/search/useChannelFind";
import { ViewLoadingFallback } from "@/shared/ui/ViewLoadingFallback";
@@ -70,11 +67,9 @@ import { useElementWidth } from "@/shared/hooks/use-mobile";
import { useThreadPanelWidth } from "@/shared/hooks/useThreadPanelWidth";
import { AUXILIARY_PANEL_SINGLE_COLUMN_BREAKPOINT_PX } from "@/shared/layout/AuxiliaryPanel";
import { normalizePubkey } from "@/shared/lib/pubkey";
import {
mergeAgentNamesIntoProfiles,
useChannelActivityTyping,
} from "./useChannelActivityTyping";
import { useChannelActivityTyping } from "./useChannelActivityTyping";
import { useChannelAgentSessions } from "./useChannelAgentSessions";
import { useMessageProfiles } from "./useMessageProfiles";
import { useChannelPanelHistoryState } from "./useChannelPanelHistoryState";
import { useChannelProfilePanel } from "./useChannelProfilePanel";
import { useChannelRouteTarget } from "./useChannelRouteTarget";
@@ -349,47 +344,29 @@ export function ChannelScreen({
// Observer ingestion (frame decryption + derived active-turn liveness) is
// owner-global — mounted once in AppShell via useAgentObserverIngestion —
// so this screen no longer mounts its own observer/turns bridges.
const messageProfilesRaw = React.useMemo(() => {
const base =
mergeCurrentProfileIntoLookup(
messageProfilesQuery.data?.profiles,
currentProfile,
) ?? {};
return mergeAgentNamesIntoProfiles(
base,
managedAgents,
relayAgents,
currentPubkey,
);
}, [
const messageProfiles = useMessageProfiles({
channelMembers,
currentProfile,
currentPubkey,
managedAgents,
messageProfilesQuery.data?.profiles,
profiles: messageProfilesQuery.data?.profiles,
relayAgents,
]);
// Stabilise the merged lookup's reference across renders when no profile
// value changed. `messageProfilesRaw` gets a fresh identity whenever the
// `users-batch` query re-keys — which typing churn triggers constantly — and
// that identity flows to MessageRow's `prev.profiles === next.profiles` memo
// check, so an unstable reference re-renders the whole timeline per keystroke.
const messageProfilesRef = React.useRef(messageProfilesRaw);
if (!profileLookupsEqual(messageProfilesRef.current, messageProfilesRaw)) {
messageProfilesRef.current = messageProfilesRaw;
}
const messageProfiles = messageProfilesRef.current;
// Derived from the stabilised lookup so this Set only churns when a profile
// value actually changed — MessageRow compares `agentPubkeys` by reference,
// and each row previously re-derived this same scan locally (removed).
});
// Agent set for ChannelPane's own consumers (DM huddle member resolution,
// the agents list): the workspace-scoped baseline shared by every surface,
// widened with channel-member roles and this screen's profile lookup.
// Message rows no longer take this — MessageRow derives agent-ness itself
// from useKnownAgentPubkeys + per-pubkey profile checks.
const workspaceAgentPubkeys = useKnownAgentPubkeys();
const agentPubkeys = React.useMemo(() => {
const pubkeys = new Set(knownAgentPubkeys);
const pubkeys = new Set([...workspaceAgentPubkeys, ...knownAgentPubkeys]);
for (const [pubkey, profile] of Object.entries(messageProfiles)) {
if (profile.isAgent) {
pubkeys.add(normalizePubkey(pubkey));
}
}
return pubkeys;
}, [knownAgentPubkeys, messageProfiles]);
}, [knownAgentPubkeys, messageProfiles, workspaceAgentPubkeys]);
const personasQuery = usePersonasQuery();
const { personaLookup, respondToLookup } = React.useMemo(() => {
const agents = managedAgentsQuery.data ?? [];

View File

@@ -8,7 +8,10 @@ import {
resetAgentWorkingSignal,
} from "../../agents/agentWorkingSignal.ts";
import { resetActiveAgentTurnsStore } from "../../agents/activeAgentTurnsStore.ts";
import { channelScopedBotTypingPubkeyKey } from "./useChannelActivityTyping.ts";
import {
channelScopedBotTypingPubkeyKey,
mergeMemberAgentFlagsIntoProfiles,
} from "./useChannelActivityTyping.ts";
const AGENT =
"abcd1234abcd1234abcd1234abcd1234abcd1234abcd1234abcd1234abcd1234";
@@ -73,3 +76,83 @@ describe("thread-only bot typing regression", () => {
assert.equal(state.source, "typing");
});
});
describe("mergeMemberAgentFlagsIntoProfiles", () => {
it("flags a role-only bot member (no isAgent) as an agent", () => {
const merged = mergeMemberAgentFlagsIntoProfiles({}, [
{ pubkey: AGENT, role: "bot", isAgent: false },
]);
assert.equal(merged[AGENT]?.isAgent, true);
assert.equal(merged[AGENT]?.displayName, null);
assert.equal(merged[AGENT]?.avatarUrl, null);
assert.equal(merged[AGENT]?.nip05Handle, null);
assert.equal(merged[AGENT]?.ownerPubkey, null);
});
it("flags an isAgent-only member (non-bot role) as an agent", () => {
const merged = mergeMemberAgentFlagsIntoProfiles({}, [
{ pubkey: AGENT, role: "member", isAgent: true },
]);
assert.equal(merged[AGENT]?.isAgent, true);
});
it("normalises member pubkeys so lookups by normalised key hit", () => {
const merged = mergeMemberAgentFlagsIntoProfiles({}, [
{ pubkey: ` ${AGENT.toUpperCase()}`, role: "bot", isAgent: false },
]);
assert.equal(merged[AGENT]?.isAgent, true);
});
it("returns the same reference when no member carries an agent flag", () => {
const profiles = {
[AGENT]: {
displayName: "Human",
avatarUrl: null,
nip05Handle: null,
ownerPubkey: null,
},
};
assert.equal(
mergeMemberAgentFlagsIntoProfiles(profiles, undefined),
profiles,
);
assert.equal(mergeMemberAgentFlagsIntoProfiles(profiles, []), profiles);
assert.equal(
mergeMemberAgentFlagsIntoProfiles(profiles, [
{ pubkey: AGENT_2, role: "member", isAgent: false },
]),
profiles,
);
});
it("preserves existing profile fields and does not mutate the input", () => {
const profiles = {
[AGENT]: {
displayName: "Deploy Bot",
name: "deploybot",
avatarUrl: "https://example.com/a.png",
nip05Handle: "deploy@example.com",
ownerPubkey: AGENT_2,
},
};
const merged = mergeMemberAgentFlagsIntoProfiles(profiles, [
{ pubkey: AGENT, role: "bot", isAgent: false },
]);
assert.notEqual(merged, profiles);
assert.deepEqual(merged[AGENT], {
displayName: "Deploy Bot",
name: "deploybot",
avatarUrl: "https://example.com/a.png",
nip05Handle: "deploy@example.com",
ownerPubkey: AGENT_2,
isAgent: true,
});
assert.equal(profiles[AGENT].isAgent, undefined);
});
});

View File

@@ -159,3 +159,42 @@ export function mergeAgentNamesIntoProfiles(
}
return merged;
}
/**
* Fold channel-member agent flags (`role === "bot"` or `isAgent`) into a
* profile lookup as `isAgent: true` entries — the same pattern
* `mergeAgentNamesIntoProfiles` applies to managed/relay agents, extended to
* the membership signal. Per-pubkey `profiles[pk]?.isAgent` checks
* (MessageRow's agent predicate) then see member-only bots — agents known
* through channel membership alone, with no profile flag and no
* managed/relay/feed presence — without a separate agent-set prop.
*
* Returns the input lookup unchanged (same reference) when no member carries
* an agent flag.
*/
export function mergeMemberAgentFlagsIntoProfiles(
profiles: UserProfileLookup,
channelMembers:
| readonly Pick<ChannelMember, "pubkey" | "role" | "isAgent">[]
| undefined,
): UserProfileLookup {
const agentMembers = (channelMembers ?? []).filter(
(member) => member.role === "bot" || member.isAgent,
);
if (agentMembers.length === 0) {
return profiles;
}
const merged = { ...profiles };
for (const member of agentMembers) {
const key = normalizePubkey(member.pubkey);
merged[key] = {
...merged[key],
displayName: merged[key]?.displayName ?? null,
avatarUrl: merged[key]?.avatarUrl ?? null,
nip05Handle: merged[key]?.nip05Handle ?? null,
ownerPubkey: merged[key]?.ownerPubkey ?? null,
isAgent: true,
};
}
return merged;
}

View File

@@ -0,0 +1,78 @@
import * as React from "react";
import {
mergeCurrentProfileIntoLookup,
profileLookupsEqual,
type UserProfileLookup,
} from "@/features/profile/lib/identity";
import type {
ChannelMember,
ManagedAgent,
Profile,
RelayAgent,
} from "@/shared/api/types";
import {
mergeAgentNamesIntoProfiles,
mergeMemberAgentFlagsIntoProfiles,
} from "./useChannelActivityTyping";
/**
* The channel screen's message-row profile lookup: the `users-batch` query
* profiles overlaid with the current profile, managed/relay agent names, and
* channel-member agent flags.
*
* Member agent flags (`role === "bot"` or `isAgent`) ride along in the lookup
* so a member-only bot — known through channel membership alone, with no
* profile `isAgent` flag and no managed/relay/feed presence — still passes
* MessageRow's per-pubkey `profiles[pk]?.isAgent` check; rows no longer see
* a member-derived agent set.
*
* The returned reference is stabilised across renders when no profile value
* changed: the raw merge gets a fresh identity whenever the `users-batch`
* query re-keys — which typing churn triggers constantly — and that identity
* flows to MessageRow's `prev.profiles === next.profiles` memo check, so an
* unstable reference re-renders the whole timeline per keystroke. Consumers
* read profiles by pubkey value only, never treating identity as a change
* signal, so returning the stale-but-value-identical reference is safe.
*/
export function useMessageProfiles({
channelMembers,
currentProfile,
currentPubkey,
managedAgents,
profiles,
relayAgents,
}: {
channelMembers: ChannelMember[] | undefined;
currentProfile: Profile | undefined;
currentPubkey: string | undefined;
managedAgents: ManagedAgent[];
profiles: UserProfileLookup | undefined;
relayAgents: RelayAgent[];
}): UserProfileLookup {
const raw = React.useMemo(() => {
const base = mergeCurrentProfileIntoLookup(profiles, currentProfile) ?? {};
return mergeMemberAgentFlagsIntoProfiles(
mergeAgentNamesIntoProfiles(
base,
managedAgents,
relayAgents,
currentPubkey,
),
channelMembers,
);
}, [
channelMembers,
currentProfile,
currentPubkey,
managedAgents,
profiles,
relayAgents,
]);
const ref = React.useRef(raw);
if (!profileLookupsEqual(ref.current, raw)) {
ref.current = raw;
}
return ref.current;
}

View File

@@ -66,9 +66,17 @@ export type InboxReply = {
depth?: number;
fullTimestampLabel: string;
id: string;
/** Raw event kind — input to the config-nudge trust gate. */
kind?: number;
parentId?: string | null;
reactions?: TimelineReaction[];
rootId?: string | null;
/**
* Raw event signer, NOT the tag-attributed display author
* (`authorPubkey`). The config-nudge trust gate authenticates against
* this field so `actor`/`p`-tag spoofing can't enable the card.
*/
signerPubkey?: string;
tags?: string[][];
timeLabel?: string;
};

View File

@@ -1,11 +1,15 @@
import assert from "node:assert/strict";
import test from "node:test";
import { formatTimelineMessages } from "../../messages/lib/formatTimelineMessages.ts";
import { getConfigNudgeAuthorPubkey } from "../../messages/ui/configNudgeAuthPubkey.ts";
import {
getContextMessageDepth,
getReactionTargetId,
isInboxThreadContextEvent,
matchesInboxFilter,
toInboxContextMessage,
toTimelineMessage,
} from "./inboxViewHelpers.ts";
// --- matchesInboxFilter ---
@@ -256,3 +260,92 @@ test("isInboxThreadContextEvent keeps selected thread root, parent, selected eve
true,
);
});
// --- config-nudge pipeline: toInboxContextMessage → toTimelineMessage ---
//
// The inbox detail pane renders messages through two mappings that a real
// event's `kind` and `signerPubkey` must survive: HomeView's
// toInboxContextMessage and InboxMessageRow's toTimelineMessage. An earlier
// version of the HomeView mapping dropped both fields, structurally
// disabling the config-nudge card on the inbox surface (the raw
// ```buzz:config-nudge fence rendered instead). These tests run a real event
// through formatTimelineMessages and both mappings, then assert against the
// same gate helper InboxMessageRow calls.
const NUDGE_CHANNEL_ID = "aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa";
const NUDGE_AGENT_SIGNER =
"2222222222222222222222222222222222222222222222222222222222222222";
const NUDGE_HUMAN_SIGNER =
"1111111111111111111111111111111111111111111111111111111111111111";
function makeNudgeEvent(overrides = {}) {
return {
id: "eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee",
pubkey: NUDGE_AGENT_SIGNER,
kind: 9,
created_at: 1_700_000_000,
content: "**Fizz** needs configuration.\n\n```buzz:config-nudge\n{}\n```",
tags: [["h", NUDGE_CHANNEL_ID]],
sig: "sig",
...overrides,
};
}
function mapThroughInboxPipeline(event) {
const [formatted] = formatTimelineMessages([event], null, undefined, null);
const contextMessage = toInboxContextMessage(formatted, {
eventById: new Map([[event.id, event]]),
fallbackAuthorPubkey: event.pubkey,
profiles: undefined,
selectedItemId: event.id,
});
return toTimelineMessage(contextMessage);
}
test("inbox mappings preserve kind and signerPubkey so the nudge gate can pass", () => {
const message = mapThroughInboxPipeline(makeNudgeEvent());
assert.equal(message.kind, 9);
assert.equal(message.signerPubkey, NUDGE_AGENT_SIGNER);
assert.equal(message.createdAt, 1_700_000_000);
assert.equal(
getConfigNudgeAuthorPubkey(
message,
(pubkey) => pubkey === NUDGE_AGENT_SIGNER,
),
NUDGE_AGENT_SIGNER,
);
});
test("inbox mappings keep the raw signer distinct from a spoofed actor tag", () => {
const message = mapThroughInboxPipeline(
makeNudgeEvent({
pubkey: NUDGE_HUMAN_SIGNER,
tags: [
["h", NUDGE_CHANNEL_ID],
["actor", NUDGE_AGENT_SIGNER],
],
}),
);
// The attributed display author resolves to the agent (actor tag), but the
// signer stays human — the gate must reject.
assert.equal(message.pubkey?.toLowerCase(), NUDGE_AGENT_SIGNER);
assert.equal(message.signerPubkey, NUDGE_HUMAN_SIGNER);
assert.equal(
getConfigNudgeAuthorPubkey(
message,
(pubkey) => pubkey === NUDGE_AGENT_SIGNER,
),
undefined,
);
});
test("inbox mappings: unknown signer never enables the card", () => {
const message = mapThroughInboxPipeline(makeNudgeEvent());
assert.equal(
getConfigNudgeAuthorPubkey(message, () => false),
undefined,
);
});

View File

@@ -1,10 +1,20 @@
import type { InboxFilter } from "@/features/home/lib/inbox";
import {
formatInboxFullTimestamp,
type InboxContextMessage,
type InboxFilter,
} from "@/features/home/lib/inbox";
import {
getChannelIdFromTags,
getThreadReference,
isBroadcastReply,
} from "@/features/messages/lib/threading";
import type { FeedItem, RelayEvent } from "@/shared/api/types";
import type { TimelineMessage } from "@/features/messages/types";
import type {
FeedItem,
RelayEvent,
UserProfileSummary,
} from "@/shared/api/types";
import { resolveMentionProps } from "@/shared/lib/resolveMentionNames";
function hasThreadReplyTags(tags: string[][]) {
const thread = getThreadReference(tags);
@@ -99,3 +109,75 @@ export function getReactionTargetId(tags: string[][]) {
return null;
}
/**
* Maps a formatted timeline message into the inbox detail pane's context
* message shape. Extracted from HomeView's `contextMessages` memo so the
* field selection is unit-testable: `kind` and `signerPubkey` must survive
* this mapping for the config-nudge trust gate
* (`getConfigNudgeAuthorPubkey`) to run in `InboxMessageRow` — an earlier
* version dropped them, structurally disabling the card on the inbox
* surface.
*/
export function toInboxContextMessage(
message: TimelineMessage,
context: {
eventById: ReadonlyMap<string, RelayEvent>;
fallbackAuthorPubkey: string;
profiles: Record<string, UserProfileSummary> | undefined;
selectedItemId: string;
},
): InboxContextMessage {
const event = context.eventById.get(message.id);
const authorPubkey =
message.pubkey ?? event?.pubkey ?? context.fallbackAuthorPubkey;
const { mentionNames, mentionPubkeysByName } = resolveMentionProps(
message.tags ?? [],
context.profiles,
);
return {
id: message.id,
authorLabel: message.author,
authorPubkey,
avatarUrl: message.avatarUrl ?? null,
content: message.body,
createdAt: message.createdAt,
depth: event
? getContextMessageDepth(event, context.eventById)
: message.depth,
fullTimestampLabel: formatInboxFullTimestamp(message.createdAt),
isSelected: message.id === context.selectedItemId,
kind: message.kind,
mentionNames: mentionNames ?? [],
mentionPubkeysByName,
reactions: message.reactions,
signerPubkey: message.signerPubkey,
tags: message.tags,
timeLabel: message.time,
};
}
/**
* Converts an inbox context message back into the `TimelineMessage` shape
* the shared message components consume (action bar, reactions, and the
* config-nudge gate — `kind` and `signerPubkey` ride through for
* `getConfigNudgeAuthorPubkey`).
*/
export function toTimelineMessage(
message: InboxContextMessage,
): TimelineMessage {
return {
id: message.id,
author: message.authorLabel,
avatarUrl: message.avatarUrl,
body: message.content,
createdAt: message.createdAt,
depth: message.depth,
kind: message.kind,
pubkey: message.authorPubkey,
reactions: message.reactions ?? [],
signerPubkey: message.signerPubkey,
tags: message.tags,
time: message.timeLabel ?? message.fullTimestampLabel,
};
}

View File

@@ -3,6 +3,7 @@ import { RefreshCcw } from "lucide-react";
import { useAppShell } from "@/app/AppShellContext";
import { useAppNavigation } from "@/app/navigation/useAppNavigation";
import { useKnownAgentPubkeys } from "@/features/agents/useKnownAgentPubkeys";
import { useChannelsQuery, useOpenDmMutation } from "@/features/channels/hooks";
import { RightAuxiliaryPane } from "@/features/channels/ui/RightAuxiliaryPane";
import { ChannelManagementSheet } from "@/features/channels/ui/ChannelManagementSheet";
@@ -17,9 +18,9 @@ import {
} from "@/features/home/lib/inbox";
import { useInboxSelectionAnchor } from "@/features/home/useInboxSelectionAnchor";
import {
getContextMessageDepth,
getReactionTargetId,
matchesInboxFilter,
toInboxContextMessage,
} from "@/features/home/lib/inboxViewHelpers";
import { useHomeInboxReadState } from "@/features/home/useHomeInboxReadState";
import { useInboxThreadContext } from "@/features/home/useInboxThreadContext";
@@ -65,7 +66,6 @@ import { KIND_REACTION } from "@/shared/constants/kinds";
import { topChromeInset } from "@/shared/layout/chromeLayout";
import { cn } from "@/shared/lib/cn";
import { normalizePubkey } from "@/shared/lib/pubkey";
import { resolveMentionProps } from "@/shared/lib/resolveMentionNames";
import { useElementWidth } from "@/shared/hooks/use-mobile";
import { useThreadPanelWidth } from "@/shared/hooks/useThreadPanelWidth";
import { AUXILIARY_PANEL_SINGLE_COLUMN_BREAKPOINT_PX } from "@/shared/layout/AuxiliaryPanel";
@@ -331,12 +331,11 @@ export function HomeView({
enabled: feedProfilePubkeys.length > 0,
});
const feedProfiles = feedProfilesQuery.data?.profiles;
// Agent set for the inbox list/detail bot badges: the workspace-scoped
// baseline widened with this surface's profile lookup.
const workspaceAgentPubkeys = useKnownAgentPubkeys();
const inboxAgentPubkeys = React.useMemo(() => {
const pubkeys = new Set<string>();
for (const item of feed?.feed.agentActivity ?? []) {
pubkeys.add(normalizePubkey(item.pubkey));
}
const pubkeys = new Set(workspaceAgentPubkeys);
for (const [pubkey, profile] of Object.entries(feedProfiles ?? {})) {
if (profile.isAgent) {
@@ -345,7 +344,7 @@ export function HomeView({
}
return pubkeys;
}, [feed?.feed.agentActivity, feedProfiles]);
}, [feedProfiles, workspaceAgentPubkeys]);
const inboxItems = React.useMemo(
() =>
buildInboxItems({
@@ -474,31 +473,14 @@ export function HomeView({
feedProfiles,
);
return timelineMessages.map((message) => {
const event = eventById.get(message.id);
const authorPubkey =
message.pubkey ?? event?.pubkey ?? selectedItem.item.pubkey;
const { mentionNames, mentionPubkeysByName } = resolveMentionProps(
message.tags ?? [],
feedProfiles,
);
return {
id: message.id,
authorLabel: message.author,
authorPubkey,
avatarUrl: message.avatarUrl ?? null,
content: message.body,
createdAt: message.createdAt,
depth: event ? getContextMessageDepth(event, eventById) : message.depth,
fullTimestampLabel: formatInboxFullTimestamp(message.createdAt),
isSelected: message.id === selectedEventId,
mentionNames: mentionNames ?? [],
mentionPubkeysByName,
reactions: message.reactions,
tags: message.tags,
timeLabel: message.time,
};
});
return timelineMessages.map((message) =>
toInboxContextMessage(message, {
eventById,
fallbackAuthorPubkey: selectedItem.item.pubkey,
profiles: feedProfiles,
selectedItemId: selectedEventId ?? selectedItem.id,
}),
);
}, [
channelMessages,
currentPubkey,

View File

@@ -1,8 +1,11 @@
import * as React from "react";
import { useKnownAgentPubkeys } from "@/features/agents/useKnownAgentPubkeys";
import type { InboxContextMessage } from "@/features/home/lib/inbox";
import { toTimelineMessage } from "@/features/home/lib/inboxViewHelpers";
import { formatTimeWithoutDayPeriod } from "@/features/messages/lib/dateFormatters";
import type { TimelineMessage } from "@/features/messages/types";
import { getConfigNudgeAuthorPubkey } from "@/features/messages/ui/configNudgeAuthPubkey";
import { MessageActionBar } from "@/features/messages/ui/MessageActionBar";
import { MessageReactions } from "@/features/messages/ui/MessageReactions";
import { useReactionHandler } from "@/features/messages/ui/useReactionHandler";
@@ -17,21 +20,6 @@ export type InboxDisplayMessage = InboxContextMessage & {
depth: number;
};
function toTimelineMessage(message: InboxDisplayMessage): TimelineMessage {
return {
id: message.id,
author: message.authorLabel,
avatarUrl: message.avatarUrl,
body: message.content,
createdAt: 0,
depth: message.depth,
pubkey: message.authorPubkey,
reactions: message.reactions ?? [],
tags: message.tags,
time: message.timeLabel ?? message.fullTimestampLabel,
};
}
type InboxMessageRowProps = {
agentPubkeys?: ReadonlySet<string>;
canReply: boolean;
@@ -76,8 +64,21 @@ export function InboxMessageRow({
errorMessage: reactionErrorMessage,
select: handleReactionSelect,
} = useReactionHandler(timelineMessage, onToggleReaction);
const isAuthorAgent =
agentPubkeys?.has(normalizePubkey(message.authorPubkey)) === true;
// "Is this pubkey an agent" = the workspace-scoped baseline every surface
// shares plus this surface's extras passed via `agentPubkeys` (HomeView
// folds feed-profile `isAgent` flags in). Mirrors MessageRow's predicate.
const knownAgentPubkeys = useKnownAgentPubkeys();
const isKnownAgentPubkey = React.useCallback(
(pubkey: string) => {
const normalized = normalizePubkey(pubkey);
return (
knownAgentPubkeys.has(normalized) ||
agentPubkeys?.has(normalized) === true
);
},
[agentPubkeys, knownAgentPubkeys],
);
const isAuthorAgent = isKnownAgentPubkey(message.authorPubkey);
const profileRole = isAuthorAgent ? "bot" : undefined;
const hoverTimestampLabel = formatTimeWithoutDayPeriod(
message.timeLabel ?? message.fullTimestampLabel,
@@ -183,6 +184,14 @@ export function InboxMessageRow({
emojiOnly &&
"text-4xl leading-tight [&_p]:leading-tight [&_img[data-custom-emoji]]:h-[1.45em] [&_img[data-custom-emoji]]:align-middle [&_button:has(img[data-custom-emoji])]:align-middle",
)}
// Only pass the author pubkey for agent-authored messages so
// config-nudge cards can authenticate the sender. Uses the
// raw event signer (signerPubkey) — not the tag-attributed
// display author — to prevent actor/p-tag spoofing.
configNudgeAuthorPubkey={getConfigNudgeAuthorPubkey(
timelineMessage,
isKnownAgentPubkey,
)}
content={message.content}
customEmoji={customEmoji}
mentionNames={message.mentionNames}

View File

@@ -7,6 +7,7 @@ import {
tagsEqual,
} from "@/features/messages/lib/messageRowEquality";
import type { TimelineMessage } from "@/features/messages/types";
import { useKnownAgentPubkeys } from "@/features/agents/useKnownAgentPubkeys";
import { HuddleAttachment } from "@/features/huddle/components/HuddleAttachment";
import { MessageReactions } from "@/features/messages/ui/MessageReactions";
import { useReactionHandler } from "@/features/messages/ui/useReactionHandler";
@@ -46,10 +47,6 @@ import { Tooltip, TooltipContent, TooltipTrigger } from "@/shared/ui/tooltip";
const DiffMessage = React.lazy(() => import("./DiffMessage"));
const DiffMessageExpanded = React.lazy(() => import("./DiffMessageExpanded"));
/** Stable empty fallback so rows without an agent-pubkey set keep a constant
* reference (a fresh `new Set()` per render would defeat downstream memos). */
const EMPTY_AGENT_PUBKEYS: ReadonlySet<string> = new Set();
export type ThreadDepthGuideAction = {
active?: boolean;
depth: number;
@@ -92,10 +89,8 @@ export const MessageRow = React.memo(
profiles,
searchQuery,
showDepthGuides = true,
agentPubkeys,
videoReviewContext,
}: {
agentPubkeys?: ReadonlySet<string>;
channelId?: string | null;
collapseDepthGuideActions?: ReadonlyArray<ThreadDepthGuideAction>;
connectDescendants?: boolean;
@@ -171,15 +166,24 @@ export const MessageRow = React.memo(
() => resolveMentionProps(message.tags, profiles),
[profiles, message.tags],
);
// The agent-pubkey set is computed once by the parent (ChannelScreen)
// from the same profile lookup and passed down already normalised — no
// per-row rescan of `profiles` (that duplicated the parent's work in every
// mounted row and re-ran on each profile-lookup change).
const resolvedAgentPubkeys = agentPubkeys ?? EMPTY_AGENT_PUBKEYS;
// "Is this pubkey an agent" = the workspace-scoped baseline every surface
// shares (managed ∪ relay) plus the pubkey's own profile `isAgent` flag from this surface's lookup. Both are per-pubkey
// O(1) checks — no per-row rescan of `profiles` (that duplicated parent
// work in every mounted row and re-ran on each profile-lookup change).
const knownAgentPubkeys = useKnownAgentPubkeys();
const isKnownAgentPubkey = React.useCallback(
(pubkey: string) => {
const normalized = normalizePubkey(pubkey);
return (
knownAgentPubkeys.has(normalized) ||
profiles?.[normalized]?.isAgent === true
);
},
[knownAgentPubkeys, profiles],
);
const profilePopoverRole =
message.role === "bot" ||
(message.pubkey &&
resolvedAgentPubkeys.has(normalizePubkey(message.pubkey)))
(message.pubkey && isKnownAgentPubkey(message.pubkey))
? "bot"
: message.role;
const agentMentionPubkeysByName = React.useMemo(() => {
@@ -189,13 +193,13 @@ export const MessageRow = React.memo(
const values: Record<string, string> = {};
for (const [name, pubkey] of Object.entries(mentionPubkeysByName)) {
if (resolvedAgentPubkeys.has(normalizePubkey(pubkey))) {
if (isKnownAgentPubkey(pubkey)) {
values[name] = pubkey;
}
}
return Object.keys(values).length > 0 ? values : undefined;
}, [resolvedAgentPubkeys, mentionPubkeysByName]);
}, [isKnownAgentPubkey, mentionPubkeysByName]);
const imetaByUrl = React.useMemo(
() => (message.tags ? parseImetaTags(message.tags) : undefined),
@@ -334,7 +338,7 @@ export const MessageRow = React.memo(
// display author — to prevent actor/p-tag spoofing.
configNudgeAuthorPubkey={getConfigNudgeAuthorPubkey(
message,
resolvedAgentPubkeys,
isKnownAgentPubkey,
)}
content={message.body}
customEmoji={customEmoji}
@@ -795,7 +799,6 @@ export const MessageRow = React.memo(
tagsEqual(prev.message.tags, next.message.tags) &&
prev.message.role === next.message.role &&
prev.message.personaDisplayName === next.message.personaDisplayName &&
prev.agentPubkeys === next.agentPubkeys &&
depthGuideActionsEqual(
prev.collapseDepthGuideActions,
next.collapseDepthGuideActions,

View File

@@ -38,7 +38,6 @@ import { useAnchoredScroll } from "./useAnchoredScroll";
import { selectDeferredListRenderState } from "@/features/messages/lib/timelineSnapshot";
type MessageThreadPanelProps = {
agentPubkeys?: ReadonlySet<string>;
channel: Channel | null;
channelId: string | null;
channelName: string;
@@ -296,7 +295,6 @@ export function MessageThreadPanelSkeleton({
}
export function MessageThreadPanel({
agentPubkeys,
channel,
channelId,
channelName,
@@ -618,7 +616,6 @@ export function MessageThreadPanel({
<div className="rounded-2xl">
<MessageRow
actionBarPlacement="inside"
agentPubkeys={agentPubkeys}
channelId={channelId}
huddleMemberPubkeys={huddleMemberPubkeys}
huddleMemberPubkeysPending={huddleMemberPubkeysPending}
@@ -736,7 +733,6 @@ export function MessageThreadPanel({
>
{showUnreadDivider ? <UnreadDivider /> : null}
<MessageRow
agentPubkeys={agentPubkeys}
channelId={channelId}
collapseDepthGuideActions={collapseDepthGuideActions}
collapseDescendantsLabel="Collapse replies"

View File

@@ -35,7 +35,6 @@ export type MessageTimelineHandle = {
};
type MessageTimelineProps = {
agentPubkeys?: ReadonlySet<string>;
channelId?: string | null;
channelIntro?: ChannelIntro | null;
channelName?: string;
@@ -160,7 +159,6 @@ const MessageTimelineBase = React.forwardRef<
MessageTimelineProps
>(function MessageTimeline(
{
agentPubkeys,
channelId,
channelIntro = null,
directMessageIntro = null,
@@ -677,7 +675,6 @@ const MessageTimelineBase = React.forwardRef<
const timelineList = showMessageList ? (
<TimelineMessageList
key={scrollContainerDomKey}
agentPubkeys={agentPubkeys}
channelId={channelId}
channelName={channelName}
channelType={channelType}

View File

@@ -49,7 +49,6 @@ export type TimelineVirtualizerApi = {
};
type TimelineMessageListProps = {
agentPubkeys?: ReadonlySet<string>;
channelId?: string | null;
channelName?: string;
channelType?: ChannelType | null;
@@ -118,7 +117,6 @@ type TimelineMessageListProps = {
};
export const TimelineMessageList = React.memo(function TimelineMessageList({
agentPubkeys,
channelId,
channelName,
channelType,
@@ -250,7 +248,6 @@ export const TimelineMessageList = React.memo(function TimelineMessageList({
case "message":
return (
<MessageRowItem
agentPubkeys={agentPubkeys}
channelId={channelId}
currentPubkey={currentPubkey}
entry={item.entry}
@@ -283,7 +280,6 @@ export const TimelineMessageList = React.memo(function TimelineMessageList({
}
},
[
agentPubkeys,
channelId,
currentPubkey,
followThreadById,
@@ -760,7 +756,6 @@ function SystemRow({
type MessageRowItemProps = Pick<
TimelineMessageListProps,
| "agentPubkeys"
| "channelId"
| "currentPubkey"
| "followThreadById"
@@ -790,7 +785,6 @@ type MessageRowItemProps = Pick<
};
function MessageRowItem({
agentPubkeys,
channelId,
currentPubkey,
entry,
@@ -837,7 +831,6 @@ function MessageRowItem({
)}
>
<MessageRow
agentPubkeys={agentPubkeys}
channelId={channelId}
highlighted={false}
hoverBackground={false}
@@ -894,7 +887,6 @@ function MessageRowItem({
)}
>
<MessageRow
agentPubkeys={agentPubkeys}
channelId={channelId}
highlighted={message.id === highlightedMessageId || isSearchActive}
huddleMemberPubkeys={huddleMemberPubkeys}

View File

@@ -27,7 +27,11 @@ const HUMAN_SIGNER =
const AGENT_PUBKEY =
"2222222222222222222222222222222222222222222222222222222222222222";
// MessageRow passes a predicate combining the workspace known-agent set with
// per-pubkey profile `isAgent` checks; the set-membership form is the minimal
// equivalent for exercising the signer-selection seam.
const AGENT_PUBKEYS = new Set([AGENT_PUBKEY]);
const isKnownAgentPubkey = (pubkey) => AGENT_PUBKEYS.has(pubkey);
function makeEvent(overrides = {}) {
return {
@@ -80,7 +84,7 @@ test("signerIsHuman_actorTagAttributedToAgent_returnsUndefined", () => {
// The guard must reject: signer is human, not in AGENT_PUBKEYS.
assert.equal(
getConfigNudgeAuthorPubkey(msg, AGENT_PUBKEYS),
getConfigNudgeAuthorPubkey(msg, isKnownAgentPubkey),
undefined,
"human signer with actor-tag attribution to agent must NOT enable the card",
);
@@ -103,7 +107,7 @@ test("signerIsAgent_genuine_returnsAgentPubkey", () => {
);
assert.equal(
getConfigNudgeAuthorPubkey(msg, AGENT_PUBKEYS),
getConfigNudgeAuthorPubkey(msg, isKnownAgentPubkey),
AGENT_PUBKEY,
"genuine agent-signed kind:9 must enable the card",
);
@@ -123,7 +127,7 @@ test("nonKind9_agentSigner_returnsUndefined", () => {
const [msg] = format(event);
assert.equal(
getConfigNudgeAuthorPubkey(msg, AGENT_PUBKEYS),
getConfigNudgeAuthorPubkey(msg, isKnownAgentPubkey),
undefined,
"non-kind:9 events must never enable the card even if signer is known agent",
);

View File

@@ -8,9 +8,12 @@ import type { TimelineMessage } from "@/features/messages/types";
* The card is enabled ONLY when:
* 1. `message.kind === KIND_STREAM_MESSAGE` — restricts to the setup-listener
* wire format.
* 2. `message.signerPubkey` is set and is a known agent — authenticates
* against the raw event signer (NOT `message.pubkey`, which is the
* tag-attributed display author and can be spoofed via `actor`/`p` tags).
* 2. `message.signerPubkey` is set and passes `isKnownAgentPubkey` —
* authenticates against the raw event signer (NOT `message.pubkey`,
* which is the tag-attributed display author and can be spoofed via
* `actor`/`p` tags). The caller's predicate combines the workspace-wide
* known-agent baseline (`useKnownAgentPubkeys`) with any surface-local
* signals such as the signer profile's `isAgent` flag.
*
* Extracting this predicate as a pure helper lets tests exercise the exact
* signer-vs-attributed-author distinction with a real `TimelineMessage` from
@@ -18,12 +21,12 @@ import type { TimelineMessage } from "@/features/messages/types";
*/
export function getConfigNudgeAuthorPubkey(
message: Pick<TimelineMessage, "kind" | "signerPubkey">,
resolvedAgentPubkeys: ReadonlySet<string>,
isKnownAgentPubkey: (pubkey: string) => boolean,
): string | undefined {
if (
message.kind === KIND_STREAM_MESSAGE &&
message.signerPubkey &&
resolvedAgentPubkeys.has(message.signerPubkey)
isKnownAgentPubkey(message.signerPubkey)
) {
return message.signerPubkey;
}

View File

@@ -52,3 +52,27 @@ function arraysShallowEqual(
}
return true;
}
/**
* Returns `next` but preserves the previous reference when the two Sets have
* identical membership. Same purpose as `useStableMap` for Set-valued derived
* state (e.g. pubkey sets rebuilt whenever a polling query re-materialises
* its data without changing which pubkeys are in it).
*/
export function useStableSet<T>(next: ReadonlySet<T>): ReadonlySet<T> {
const ref = React.useRef(next);
const prev = ref.current;
if (prev !== next && setsEqual(prev, next)) {
return prev;
}
ref.current = next;
return next;
}
function setsEqual<T>(a: ReadonlySet<T>, b: ReadonlySet<T>): boolean {
if (a.size !== b.size) return false;
for (const value of a) {
if (!b.has(value)) return false;
}
return true;
}