Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
58 changes: 58 additions & 0 deletions web/src/features/agents/lib/relay-agents.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,52 @@ function channel(): BuzzChannel {
}

describe("relayAgentsFromEvents", () => {
it("counts ordinary membership for known agents without discovering ordinary users", () => {
const ordinary = channel();
ordinary.members = [
{ pubkey: CONFIGURED, role: "member" },
{ pubkey: AGENT, role: "member" },
];
const agents = relayAgentsFromEvents({
events: [],
configuredAgents: [{ pubkey: CONFIGURED, name: "Assistant" }],
channels: [ordinary],
profiles: {},
presence: {},
});
expect(agents).toHaveLength(1);
expect(agents[0]).toMatchObject({
pubkey: CONFIGURED,
channelIds: [ordinary.id],
status: "offline",
startable: false,
});
});

it("ignores a blank display_name in favour of a real name", () => {
const agents = relayAgentsFromEvents({
events: [event(1, { display_name: " ", name: "Codex(remote)" })],
configuredAgents: [],
channels: [],
profiles: {},
presence: {},
});
expect(agents[0]?.name).toBe("Codex(remote)");
});

it("handles non-object agent metadata", () => {
const malformed = event(1, {});
malformed.content = "null";
expect(() =>
relayAgentsFromEvents({
events: [malformed],
configuredAgents: [],
channels: [],
profiles: {},
presence: {},
}),
).not.toThrow();
});
it("uses the latest agent profile and actual bot membership", () => {
const profiles: Record<string, UserProfile> = {
[AGENT]: {
Expand Down Expand Up @@ -91,6 +137,18 @@ describe("relayAgentsFromEvents", () => {
]);
});

it("labels an unnamed agent with the local readable fallback", () => {
const agents = relayAgentsFromEvents({
events: [event(1, {})],
configuredAgents: [],
channels: [channel()],
profiles: {},
presence: {},
});

expect(agents[0]?.name.startsWith("Agent ")).toBe(true);
});

it("deduplicates configured agents and bot memberships regardless of pubkey casing", () => {
const agents = relayAgentsFromEvents({
events: [],
Expand Down
31 changes: 18 additions & 13 deletions web/src/features/agents/lib/relay-agents.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import { metadataDisplayName, profileDisplayName } from "@/features/chat/lib/chat-model";
import type { BuzzChannel, UserProfile } from "@/features/chat/lib/chat-types";
import type { NostrEvent } from "@/shared/api/nostr-types";
import type { ConfiguredAgent } from "@/shared/config/runtime-config";
import { truncatePubkey } from "@/shared/lib/pubkey";

export type AgentRespondTo = "owner-only" | "allowlist" | "anyone";

Expand Down Expand Up @@ -61,33 +61,38 @@ export function relayAgentsFromEvents({
.map((member) => member.pubkey.toLowerCase()),
);
const pubkeys = new Set([...latest.keys(), ...configured.keys(), ...botPubkeys]);
const channelsByPubkey = new Map<string, string[]>();
for (const channel of channels) {
for (const member of channel.members) {
const pubkey = member.pubkey.toLowerCase();
const ids = channelsByPubkey.get(pubkey) ?? [];
ids.push(channel.id);
channelsByPubkey.set(pubkey, ids);
}
}

return [...pubkeys]
.map((pubkey): RelayAgent => {
const event = latest.get(pubkey);
let content: Record<string, unknown> = {};
try {
content = event ? (JSON.parse(event.content) as Record<string, unknown>) : {};
const parsed: unknown = event ? JSON.parse(event.content) : {};
content =
parsed && typeof parsed === "object" && !Array.isArray(parsed)
? (parsed as Record<string, unknown>)
: {};
} catch {
content = {};
}
const profile = profiles[pubkey];
const nameValue = content.display_name ?? content.name;
const profileChannelIds = stringArray(content.channel_ids);
const membershipChannelIds = channels
.filter((channel) =>
channel.members.some(
(member) => member.pubkey.toLowerCase() === pubkey && member.role === "bot",
),
)
.map((channel) => channel.id);
const membershipChannelIds = channelsByPubkey.get(pubkey) ?? [];
return {
pubkey,
name:
(typeof nameValue === "string" && nameValue.trim()) ||
metadataDisplayName(content) ||
configured.get(pubkey)?.name ||
profile?.name ||
truncatePubkey(pubkey),
profileDisplayName(profile, pubkey, true),
agentType:
typeof content.agent_type === "string" && content.agent_type.trim()
? content.agent_type.trim()
Expand Down
99 changes: 98 additions & 1 deletion web/src/features/chat/lib/chat-model.test.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { describe, expect, it } from "vitest";
import { describe, expect, it, vi } from "vitest";
import {
buildMessageTags,
buildTimeline,
Expand All @@ -7,9 +7,12 @@ import {
describeSystemMessage,
fallbackProfile,
mergeProfileMetadata,
mergeProfiles,
messageRecipientPubkeys,
parseCommunityRole,
parseSystemMessagePayload,
profileDisplayName,
profilesFromEvents,
resolveMentionPubkeys,
systemMessagePubkeys,
} from "@/features/chat/lib/chat-model";
Expand Down Expand Up @@ -249,6 +252,100 @@ describe("Buzz profile metadata", () => {
});
});

describe("Buzz profile hydration", () => {
const agents = new Set([AGENT]);

it("uses the first non-blank name field instead of letting an empty one mask it", () => {
const profiles = profilesFromEvents(
[
event(
"a",
0,
AGENT,
JSON.stringify({ display_name: " ", displayName: null, name: "Codex(remote)" }),
[],
5,
),
],
agents,
);

expect(profiles[AGENT]).toMatchObject({
pubkey: AGENT,
name: "Codex(remote)",
isAgent: true,
});
});

it("keeps the latest metadata and tolerates null, array, and malformed content", () => {
const profiles = profilesFromEvents(
[
event("b", 0, SELF, JSON.stringify({ name: "Old name" }), [], 10),
event("c", 0, SELF, JSON.stringify({ name: "New name" }), [], 11),
event("d", 0, RELAY, "null", [], 20),
event("e", 0, "44".repeat(32), "[]", [], 21),
event("f", 0, "55".repeat(32), "not-json", [], 22),
event("9", 0, "66".repeat(32), JSON.stringify({ name: "" }), [], 23),
],
new Set(),
);

expect(profiles[SELF].name).toBe("New name");
for (const pubkey of [RELAY, "44".repeat(32), "55".repeat(32), "66".repeat(32)]) {
expect(profiles[pubkey]).toMatchObject({ name: "", about: "", picture: null });
}
});

it("preserves known names and applies real names from newer metadata", () => {
const current = {
[SELF]: { ...fallbackProfile(SELF), name: "Alice", about: "old about" },
[AGENT]: fallbackProfile(AGENT, "Codex(remote)", true),
};
const incoming = profilesFromEvents(
[
event("1", 0, SELF, JSON.stringify({ display_name: "", name: "" }), [], 30),
event("2", 0, AGENT, JSON.stringify({ name: "Codex v2" }), [], 31),
event("3", 0, RELAY, JSON.stringify({ display_name: "Bob" }), [], 32),
],
agents,
);
const merged = mergeProfiles(current, incoming);

expect(merged[SELF].name).toBe("Alice");
expect(merged[AGENT]).toMatchObject({ name: "Codex v2", isAgent: true });
expect(merged[RELAY]).toMatchObject({ name: "Bob", isAgent: false });
});

it("labels nameless authors locally instead of presenting a fabricated public name", () => {
vi.stubGlobal("navigator", { languages: ["en"] });
try {
const merged = mergeProfiles(
{},
profilesFromEvents([event("4", 0, SELF, "null", [], 1)], new Set()),
);

expect(merged[SELF].name).toBe(fallbackProfile(SELF).name);
expect(merged[SELF].name.startsWith("Member ")).toBe(true);
expect(profileDisplayName({ ...fallbackProfile(SELF), name: "Alice" }, SELF)).toBe("Alice");
expect(profileDisplayName(undefined, AGENT, true)).toBe(
fallbackProfile(AGENT, undefined, true).name,
);
} finally {
vi.unstubAllGlobals();
}
});

it("localizes the local nameless placeholder", () => {
vi.stubGlobal("navigator", { languages: ["zh-CN"] });
try {
expect(fallbackProfile(SELF).name.startsWith("成员 ")).toBe(true);
expect(profileDisplayName(undefined, AGENT, true).startsWith("Agent ")).toBe(true);
} finally {
vi.unstubAllGlobals();
}
});
});

describe("Buzz outgoing messages", () => {
it("adds agent mentions, thread markers, and imeta tags", () => {
const profiles = {
Expand Down
80 changes: 68 additions & 12 deletions web/src/features/chat/lib/chat-model.ts
Original file line number Diff line number Diff line change
Expand Up @@ -91,7 +91,7 @@ function systemIdentityLabel(
): string {
if (!pubkey) return t("system.system");
if (pubkey === currentPubkey.toLowerCase()) return t("system.you");
return profiles[pubkey]?.name || truncatePubkey(pubkey);
return profiles[pubkey]?.name || fallbackProfile(pubkey).name;
}

/** Match Desktop's human-readable treatment of kind:40099 system rows. */
Expand Down Expand Up @@ -240,15 +240,49 @@ export function parseCommunityRole(
}

export function fallbackProfile(pubkey: string, name?: string, isAgent = false): UserProfile {
const normalized = pubkey.toLowerCase();
const label = isAgent ? t("common.agent") : t("common.member");
return {
pubkey: pubkey.toLowerCase(),
name: name || truncatePubkey(pubkey),
pubkey: normalized,
name: name?.trim() || `${label} ${truncatePubkey(normalized)}`,
about: "",
picture: null,
isAgent,
};
}

/** One place for the local placeholder shown when an author has no public name. */
export function profileDisplayName(
profile: UserProfile | undefined,
pubkey: string,
isAgent = profile?.isAgent ?? false,
): string {
return profile?.name.trim() || fallbackProfile(pubkey, undefined, isAgent).name;
}

function metadataObject(content: string): Record<string, unknown> {
try {
const parsed: unknown = JSON.parse(content);
return parsed && typeof parsed === "object" && !Array.isArray(parsed)
? (parsed as Record<string, unknown>)
: {};
} catch {
return {};
}
}

export function metadataDisplayName(metadata: Record<string, unknown>): string | undefined {
for (const key of ["display_name", "displayName", "name"] as const) {
const value = metadata[key];
if (typeof value === "string" && value.trim()) return value.trim();
}
return undefined;
}

/**
* Latest kind-0 metadata per author. `name` stays empty when the latest metadata
* has no usable name so callers can keep configured or already known names.
*/
export function profilesFromEvents(
events: NostrEvent[],
agentPubkeys: ReadonlySet<string>,
Expand All @@ -260,25 +294,47 @@ export function profilesFromEvents(
}
const profiles: Record<string, UserProfile> = {};
for (const [pubkey, event] of latest) {
let metadata: Record<string, unknown> = {};
try {
metadata = JSON.parse(event.content) as Record<string, unknown>;
} catch {
metadata = {};
}
const metadata = metadataObject(event.content);
const profile = fallbackProfile(pubkey, undefined, agentPubkeys.has(pubkey));
const displayName = metadata.display_name ?? metadata.displayName ?? metadata.name;
profiles[pubkey] = {
...profile,
name:
typeof displayName === "string" && displayName.trim() ? displayName.trim() : profile.name,
name: metadataDisplayName(metadata) ?? "",
about: typeof metadata.about === "string" ? metadata.about : "",
picture: typeof metadata.picture === "string" && metadata.picture ? metadata.picture : null,
};
}
return profiles;
}

/** Merge fetched metadata without replacing a known name with a local placeholder. */
export function mergeProfiles(
current: Record<string, UserProfile>,
incoming: Record<string, UserProfile>,
): Record<string, UserProfile> {
const next = { ...current };
for (const [pubkey, update] of Object.entries(incoming)) {
const existing = next[pubkey];
const base = existing ?? fallbackProfile(pubkey, undefined, update.isAgent);
next[pubkey] = {
...base,
...update,
name: update.name || base.name,
isAgent: base.isAgent || update.isAgent,
};
}
return next;
}

export function isValidProfilePicture(picture: string): boolean {
const value = picture.trim();
if (!value) return true;
try {
const protocol = new URL(value).protocol;
return protocol === "http:" || protocol === "https:";
} catch {
return false;
}
}
export function mergeProfileMetadata(
currentContent: string | undefined,
input: { name: string; about: string; picture: string },
Expand Down
Loading