From 712c152bb2c97aabea66cbc766c2b61e6e175aca Mon Sep 17 00:00:00 2001 From: Taylor Ho Date: Mon, 16 Nov 2026 11:48:30 -0800 Subject: [PATCH 01/17] feat(solo): grant opening agents chat admin access Promote every agent addressed in a new Solo chat through the existing member-administration API before releasing its opening message. Keep workspace-only agents and later additions as ordinary participants. Retain setup intent in the existing local creation receipt. Recover exact promotion commands across interrupted delivery without restoring later demotions or removals; keep expired unrecorded grants explicit. Co-authored-by: Carl Signed-off-by: Taylor Ho --- docs/buzz-help.md | 7 +- docs/solo/README.md | 9 + src/features/relay/channel-writes.ts | 55 ++++- src/features/relay/session.ts | 5 + .../relay/solo-admins.integration.test.ts | 216 ++++++++++++++++++ src/features/relay/solo-admins.test.ts | 202 ++++++++++++++++ src/features/relay/solo-admins.ts | 119 ++++++++++ src/features/solo/SoloDraft.test.tsx | 16 +- src/features/solo/SoloDraft.tsx | 2 +- 9 files changed, 625 insertions(+), 6 deletions(-) create mode 100644 src/features/relay/solo-admins.integration.test.ts create mode 100644 src/features/relay/solo-admins.test.ts create mode 100644 src/features/relay/solo-admins.ts diff --git a/docs/buzz-help.md b/docs/buzz-help.md index fd35b457de..2cb307f861 100644 --- a/docs/buzz-help.md +++ b/docs/buzz-help.md @@ -413,7 +413,12 @@ and are asked to sign in again in Buzz. the full, scrollable list of names. Messages and huddle entries split groups. - **Solo** organizes your chats with agents. Choose **New chat**, select or tag - an agent, and send a message. Solo conversations continue at the chat's top + an agent, and send a message. Every agent addressed in the opening message + becomes a chat admin before that message is delivered; you remain owner. + Agents included only through workspace defaults, or added later, keep ordinary + participation. If admin setup is interrupted, Retry on the opening message + continues it without restoring later demotions or removals. If setup expires, + start a new chat. Solo conversations continue at the chat's top level rather than requiring a new thread for each reply. Where available, use **Model and effort** in the composer before sending; Solo keeps those choices for that chat until you reset them in the same control, even if its available diff --git a/docs/solo/README.md b/docs/solo/README.md index ae4909a52a..708a782167 100644 --- a/docs/solo/README.md +++ b/docs/solo/README.md @@ -85,6 +85,15 @@ behavior on the label, so a rename touches copy only. agents: answer as one channel-scoped, top-level conversation. It is not access authority. The in-app agent harness reads it from the channel list; remote harnesses that only read `about` need to learn the label. +- The app promotes every agent addressed in the opening message through the + existing member-administration commands before releasing that message to + local agents or the relay. Workspace-only agents and later additions remain + ordinary participants. The create's local Outbox receipt retains the opening + recipients across interruptions; retries reconstruct the same grants and + confirm their recorded IDs before sending. A recorded grant stays complete + after a later demotion or removal. Expired, unrecorded grants require a new + chat; recovery never changes a command's timestamp. This needs no relay update + and does not change existing chats or tool-created Solo chats. - The Buzz tools' `channel_create` with `solo` sends the same create for any caller, including the standalone stdio server: signed by the caller, with the label and any `members` it names. The caller is the creator, so an agent's diff --git a/src/features/relay/channel-writes.ts b/src/features/relay/channel-writes.ts index 9207199fcd..343549c963 100644 --- a/src/features/relay/channel-writes.ts +++ b/src/features/relay/channel-writes.ts @@ -2,7 +2,13 @@ import { canonicalDetailsName } from "./channel-details-protocol"; import { exactLifecycleTag } from "./channel-lifecycle-protocol"; import { channelIdentityUnsupported, channelLabelTags } from "./channel-labels"; import { SOLO_NAMED_LABEL, SOLO_LABEL } from "../solo/labels"; -import type { Outbox } from "./outbox"; +import type { Outbox, OutboxRecovery } from "./outbox"; +import type { RelayWriter } from "./transport"; +import { + promoteSoloAdmins, + soloAdminKey, + soloAdminRecovery, +} from "./solo-admins"; import { isBatchAddition } from "../channel-members/members"; import { withdraw } from "./withdraw"; import type { ChannelQueries, ChannelSummary } from "./contracts"; @@ -46,6 +52,7 @@ export function createChannelWrites( /** Signed roster discovery, including channels this viewer cannot open. */ discovery: RelayReader = reader, channelIdentity = false, + adminWriter?: RelayWriter, ) { const available = !!outbox?.supports(9007); function writer(addition = false) { @@ -533,6 +540,38 @@ export function createChannelWrites( } /** Solo chats this device is starting, until they can take events. */ const starts = new Map>(); + const adminSetups = new Map>(); + /** Publication retries also call this after reload. The create's local + * receipt retains the original recipients until every grant is recorded. */ + function prepareOpening(id: string): Promise | undefined { + const pending = (receipts ?? outbox) + ?.snapshot() + .find((item) => item.recovery?.key === soloAdminKey(id)); + if (!pending) return; + const active = adminSetups.get(id); + if (active) return active; + const work = (async () => { + const source = writer(); + if (!adminWriter || !relayAuthor) + throw new Error("This connection cannot set up chat admins."); + await created(pending.event.id); + const saved = await source.recovery(soloAdminKey(id)); + // An explicit dismissal in another window retires this setup too. + if (!saved) return; + await promoteSoloAdmins( + saved, + adminWriter, + discovery, + relayAuthor, + signal, + ); + signal.throwIfAborted(); + await source.dismiss(saved.event.id, saved.recovery); + })(); + adminSetups.set(id, work); + void work.catch(() => {}).finally(() => adminSetups.delete(id)); + return work; + } /** The Canvas of each chat this device is starting ("" for none), until * its save lands; see `startingCanvas`. */ const canvases = new Map(); @@ -594,6 +633,7 @@ export function createChannelWrites( refreshMembership, memberChannels, listsMember, + prepareOpening, createChannel( id: string, title: string, @@ -651,6 +691,7 @@ export function createChannelWrites( members: readonly string[] = [], active?: () => boolean, labels: readonly string[] = [], + recovery?: OutboxRecovery, ) { writer(); identifier(id); @@ -683,7 +724,7 @@ export function createChannelWrites( ...[...new Set(members)].map((key) => ["p", key]), ], }, - undefined, + recovery, active, ); }, @@ -701,8 +742,15 @@ export function createChannelWrites( /** The chat's Canvas, and the work that saves it once the chat * exists; nothing waits for it, and a failure leaves a working chat. */ setup?: { canvas: string; apply(): Promise }, - options?: { labels?: readonly string[]; active?: () => boolean }, + options?: { + labels?: readonly string[]; + active?: () => boolean; + admins?: readonly string[]; + }, ) { + const recovery = soloAdminRecovery(id, members, options?.admins); + if (recovery && (!adminWriter || !relayAuthor)) + throw new Error("This connection cannot set up chat admins."); const create = api.create( id, title, @@ -711,6 +759,7 @@ export function createChannelWrites( members, options?.active, options?.labels, + recovery, ); channels.start?.({ id, diff --git a/src/features/relay/session.ts b/src/features/relay/session.ts index fb53c9ca11..9b9d00ee4d 100644 --- a/src/features/relay/session.ts +++ b/src/features/relay/session.ts @@ -368,6 +368,10 @@ export function createRelaySession( if (event.kind === 9007 || event.kind === 9000) return; const id = event.tags.find(([name]) => name === "h")?.[1]; if (!id) return; + // Opening agents receive admin before either local wake or publication. + const opening = + event.kind === 9 ? channelWrites.prepareOpening(id) : undefined; + if (opening) return opening; const ready = channelWrites.starting(id); if (ready && event.kind === 9) hearStarting(event, id); return ready; @@ -1827,6 +1831,7 @@ export function createRelaySession( transport?.relayAuthor, { read: (filters, settings) => readVerified(filters, settings, false) }, transport?.channelIdentity === true, + transport?.memberAdministration, ); startingChannel = (id) => channelWrites.starting(id); // Roster authority invalidates in-flight reads, including account-owned diff --git a/src/features/relay/solo-admins.integration.test.ts b/src/features/relay/solo-admins.integration.test.ts new file mode 100644 index 0000000000..57586b3f9c --- /dev/null +++ b/src/features/relay/solo-admins.integration.test.ts @@ -0,0 +1,216 @@ +import { assert, afterEach, expect, it, vi } from "vitest"; +import { createRelaySession } from "./session"; +import { keypair, metadata, signed } from "./testing"; +import { matchesEvent } from "./projection"; +import { SOLO_LABEL } from "../solo/labels"; +import { soloAdminKey } from "./solo-admins"; +import { validateMemberAdministrationTemplate } from "../channel-members/administration-protocol"; +import type { OutgoingEvent } from "./outbox"; +import type { ReadFilter, RelayEvent } from "./events"; +import type { EventTemplate } from "nostr-tools"; + +const sessions: ReturnType[] = []; +afterEach(() => { + for (const session of sessions.splice(0)) session.dispose(); +}); + +function setup() { + const viewer = keypair(), + relay = keypair(); + const channel = crypto.randomUUID(); + const agents: [string, string] = [keypair().pubkey, keypair().pubkey]; + const workspaceAgent = keypair().pubkey; + let journal: readonly OutgoingEvent[] = []; + const events = new Map(); + const roles = new Map(); + const genericPublish = vi.fn(async (event: RelayEvent) => { + if (event.kind === 9000) + throw new Error("Elevated commands require their dedicated host route"); + events.set(event.id, event); + if (event.kind === 9007) { + roles.set(viewer.pubkey, "owner"); + for (const [tag, key] of event.tags) + if (tag === "p" && key) roles.set(key, "member"); + } + }); + const adminPublish = vi.fn(async (event: RelayEvent) => { + validateMemberAdministrationTemplate(event, viewer.pubkey); + if (events.has(event.id)) return; + events.set(event.id, event); + const agent = event.tags.find(([tag]) => tag === "p")?.[1]; + assert.exists(agent); + roles.set(agent, "admin"); + }); + const transport = { + viewer: viewer.pubkey, + relayAuthor: relay.pubkey, + channelIdentity: true as const, + media: () => undefined, + query: async (filters: readonly ReadFilter[]) => { + const roster = signed(relay, { + kind: 39002, + content: "", + tags: [ + ["d", channel], + ...[...roles].map(([key, role]) => ["p", key, "", role]), + ], + }); + return [ + ...events.values(), + ...(roles.size + ? [ + roster, + metadata(relay, channel, "Work", Math.floor(Date.now() / 1000), [ + ["t", "stream"], + ["private"], + ["t", SOLO_LABEL], + ["P", viewer.pubkey], + ]), + ] + : []), + ].filter((event) => + filters.some((filter) => matchesEvent(event, filter)), + ); + }, + writer: { + kinds: [9, 9000, 9007], + sign: async (template: EventTemplate) => signed(viewer, template), + publish: genericPublish, + }, + memberAdministration: { + sign: async (template: EventTemplate) => { + validateMemberAdministrationTemplate(template, viewer.pubkey); + return signed(viewer, template); + }, + publish: adminPublish, + }, + }; + const open = async () => { + const owner = createRelaySession(transport, { + outboxStorage: { + load: () => structuredClone(journal), + save: (next) => { + journal = structuredClone(next); + }, + }, + }); + sessions.push(owner); + await owner.session.outbox?.ready(); + owner.session.channels.ensureList(); + await vi.waitFor(() => + expect(owner.session.channels.list().status).toBe("ready"), + ); + return owner; + }; + const start = (owner: Awaited>) => { + const creation = owner.session.channelWrites.start( + channel, + "Work", + [...agents, workspaceAgent], + undefined, + false, + undefined, + { admins: agents }, + ); + void creation.ready.catch(() => {}); + const message = owner.session.messages.send( + channel, + "Work on this", + agents, + ); + return { creation, message }; + }; + return { + channel, + viewer, + agents, + workspaceAgent, + roles, + events, + genericPublish, + adminPublish, + open, + start, + }; +} + +it("holds the opening message and local wake until all admins are ready through the existing host route", async () => { + const h = setup(); + const owner = await h.open(); + const heard = vi.fn(); + owner.session.subscribeLive(heard, { replay: true }); + let release = () => {}; + const held = new Promise((resolve) => { + release = resolve; + }); + const publish = h.adminPublish.getMockImplementation(); + assert.exists(publish); + h.adminPublish.mockImplementation(async (event) => { + await held; + await publish(event); + }); + try { + const { message } = h.start(owner); + await vi.waitFor(() => expect(h.adminPublish).toHaveBeenCalledOnce()); + expect(h.genericPublish.mock.calls.map(([event]) => event.kind)).toEqual([ + 9007, + ]); + expect(heard).not.toHaveBeenCalled(); + expect( + owner.session.outbox + ?.snapshot() + .some((item) => item.recovery?.key === soloAdminKey(h.channel)), + ).toBe(true); + release(); + await vi.waitFor(() => expect(h.events.has(message)).toBe(true)); + expect(h.agents.map((key) => h.roles.get(key))).toEqual(["admin", "admin"]); + expect(h.roles.get(h.workspaceAgent)).toBe("member"); + expect(h.roles.get(h.viewer.pubkey)).toBe("owner"); + expect(h.adminPublish).toHaveBeenCalledTimes(2); + expect( + owner.session.outbox + ?.snapshot() + .some((item) => item.recovery?.key === soloAdminKey(h.channel)), + ).toBe(false); + } finally { + release(); + } +}); + +it("resumes a partial setup from the durable outbox after restart without restoring a later demotion", async () => { + const h = setup(); + const first = await h.open(); + const publish = h.adminPublish.getMockImplementation(); + assert.exists(publish); + h.adminPublish + .mockImplementationOnce(publish) + .mockRejectedValueOnce(new Error("offline")); + const { message } = h.start(first); + await vi.waitFor(() => + expect( + first.session.outbox?.snapshot().find((item) => item.event.id === message) + ?.delivery, + ).toBe("failed"), + ); + expect(h.events.has(message)).toBe(false); + h.roles.set(h.agents[0], "bot"); + first.dispose(); + const resumed = await h.open(); + resumed.session.outbox?.retry(message); + await vi.waitFor(() => expect(h.events.has(message)).toBe(true)); + expect(h.roles.get(h.agents[0])).toBe("bot"); + expect(h.roles.get(h.agents[1])).toBe("admin"); + expect( + h.adminPublish.mock.calls.filter( + ([event]) => event.tags[1]?.[1] === h.agents[0], + ), + ).toHaveLength(1); + const second = h.adminPublish.mock.calls.filter( + ([event]) => event.tags[1]?.[1] === h.agents[1], + ); + expect(second).toHaveLength(2); + expect(second[0]?.[0].id).toBe(second[1]?.[0].id); + expect( + h.genericPublish.mock.calls.filter(([event]) => event.kind === 9), + ).toHaveLength(1); +}); diff --git a/src/features/relay/solo-admins.test.ts b/src/features/relay/solo-admins.test.ts new file mode 100644 index 0000000000..113ef2cf68 --- /dev/null +++ b/src/features/relay/solo-admins.test.ts @@ -0,0 +1,202 @@ +import { assert, expect, it, vi } from "vitest"; +import { promoteSoloAdmins, soloAdminRecovery } from "./solo-admins"; +import { keypair, signed } from "./testing"; +import { matchesEvent } from "./projection"; +import type { OutgoingEvent } from "./outbox"; +import type { ReadFilter, RelayEvent } from "./events"; + +function setup() { + const owner = keypair(), + relay = keypair(); + const agents: [string, string] = [keypair().pubkey, keypair().pubkey]; + const workspaceAgent = keypair().pubkey; + const channel = crypto.randomUUID(); + const members = [...agents, workspaceAgent]; + const create = signed(owner, { + kind: 9007, + content: "", + created_at: Math.floor(Date.now() / 1000), + tags: [["h", channel], ...members.map((key) => ["p", key])], + }); + const creation: OutgoingEvent = { + event: create, + delivery: "accepted", + recovery: soloAdminRecovery(channel, members, agents), + }; + const records = new Map(); + const roles = new Map(members.map((key) => [key, "member"])); + const read = vi.fn(async (filters: readonly ReadFilter[]) => { + const roster = signed(relay, { + kind: 39002, + content: "", + tags: [ + ["d", channel], + ["p", owner.pubkey, "", "owner"], + ...[...roles].map(([key, role]) => ["p", key, "", role]), + ], + }); + return [...records.values(), roster].filter((event) => + filters.some((filter) => matchesEvent(event, filter)), + ); + }); + const publish = vi.fn(async (event: RelayEvent) => { + const agent = event.tags.find(([tag]) => tag === "p")?.[1]; + assert.exists(agent); + records.set(event.id, event); + roles.set(agent, "admin"); + }); + const writer = { + sign: vi.fn(async (template: Parameters[1]) => + signed(owner, template), + ), + publish, + }; + const controller = new AbortController(); + const run = (saved = creation) => + promoteSoloAdmins(saved, writer, { read }, relay.pubkey, controller.signal); + return { + owner, + agents, + workspaceAgent, + channel, + creation, + records, + roles, + read, + writer, + publish, + run, + controller, + }; +} + +it("promotes all opening agents in order, confirms a lost ACK, and leaves workspace-only agents ordinary", async () => { + const h = setup(); + const normal = h.publish.getMockImplementation(); + assert.exists(normal); + let release = () => {}; + const held = new Promise((resolve) => { + release = resolve; + }); + let entered = () => {}; + const started = new Promise((resolve) => { + entered = resolve; + }); + h.publish + .mockImplementationOnce(async (event) => { + await normal(event); + throw new Error("ACK lost"); + }) + .mockImplementationOnce(async (event) => { + entered(); + await held; + await normal(event); + }); + let finished = false; + const work = h.run().then(() => { + finished = true; + }); + try { + await started; + expect(finished).toBe(false); + expect(h.roles.get(h.agents[0])).toBe("admin"); + expect(h.roles.get(h.agents[1])).toBe("member"); + expect(h.roles.get(h.workspaceAgent)).toBe("member"); + } finally { + release(); + } + await work; + expect(h.agents.map((key) => h.roles.get(key))).toEqual(["admin", "admin"]); + expect(h.publish.mock.calls.map(([event]) => event.tags)).toEqual( + h.agents.map((key) => [ + ["h", h.channel], + ["p", key], + ["role", "admin"], + ]), + ); + expect( + h.publish.mock.calls.every( + ([event]) => + event.pubkey === h.owner.pubkey && + event.created_at === h.creation.event.created_at, + ), + ).toBe(true); +}); + +it("resumes the exact failed grant after restart without restoring a demoted or removed opening agent", async () => { + const h = setup(); + const normal = h.publish.getMockImplementation(); + assert.exists(normal); + h.publish + .mockImplementationOnce(normal) + .mockRejectedValueOnce(new Error("offline")); + await expect(h.run()).rejects.toThrow("offline"); + const failedId = h.publish.mock.calls[1]?.[0].id; + h.roles.set(h.agents[0], "bot"); + await h.run(structuredClone(h.creation)); + expect(h.publish.mock.calls.map(([event]) => event.id).slice(1)).toEqual([ + failedId, + failedId, + ]); + expect(h.roles.get(h.agents[0])).toBe("bot"); + h.roles.delete(h.agents[0]); + await h.run(structuredClone(h.creation)); + expect(h.publish).toHaveBeenCalledTimes(3); + expect(h.roles.has(h.agents[0])).toBe(false); +}); + +it.each(["owner", "guest", "absent"])( + "preserves an opening agent changed to %s before its grant", + async (role) => { + const h = setup(); + if (role === "absent") h.roles.delete(h.agents[0]); + else h.roles.set(h.agents[0], role); + await expect(h.run()).rejects.toThrow("access changed"); + expect(h.publish).not.toHaveBeenCalled(); + }, +); + +it("keeps uncertainty recoverable when a publish claims success but no command is recorded", async () => { + const h = setup(); + h.publish.mockResolvedValue(undefined); + await expect(h.run()).rejects.toThrow("unconfirmed"); + expect(h.publish).toHaveBeenCalledOnce(); +}); + +it("does not turn a failed role read into a permission grant", async () => { + const h = setup(); + h.read.mockRejectedValueOnce(new Error("read offline")); + await expect(h.run()).rejects.toThrow("read offline"); + expect(h.writer.sign).not.toHaveBeenCalled(); + expect(h.publish).not.toHaveBeenCalled(); +}); + +it("never re-dates an expired grant, but can still confirm recorded grants after expiry", async () => { + const h = setup(); + await h.run(); + const now = Date.now(); + const clock = vi.spyOn(Date, "now").mockReturnValue(now + 16 * 60 * 1000); + try { + await h.run(); + h.records.clear(); + await expect(h.run()).rejects.toThrow("expired"); + expect(h.publish).toHaveBeenCalledTimes(2); + } finally { + clock.mockRestore(); + } +}); + +it("rejects recovery that grants a nonmember admin, without signing", async () => { + const h = setup(); + assert.exists(h.creation.recovery); + await expect( + h.run({ + ...h.creation, + recovery: { + ...h.creation.recovery, + value: JSON.stringify([keypair().pubkey]), + }, + }), + ).rejects.toThrow("initial chat agents"); + expect(h.writer.sign).not.toHaveBeenCalled(); +}); diff --git a/src/features/relay/solo-admins.ts b/src/features/relay/solo-admins.ts new file mode 100644 index 0000000000..cdac752b1b --- /dev/null +++ b/src/features/relay/solo-admins.ts @@ -0,0 +1,119 @@ +import { getEventHash } from "nostr-tools"; +import { memberAdministrationTemplate } from "../channel-members/administration-protocol"; +import type { OutboxRecovery, OutgoingEvent } from "./outbox"; +import type { RelayReader } from "./reader"; +import type { RelayWriter } from "./transport"; + +export const soloAdminKey = (channel: string) => + `solo-initial-admins:${channel}`; + +/** Local recovery only; the relay still receives an ordinary channel create. */ +export function soloAdminRecovery( + channel: string, + members: readonly string[], + admins: readonly string[] = [], +): OutboxRecovery | undefined { + if (!admins.length) return; + const unique = [...new Set(admins)]; + if ( + unique.length > 32 || + unique.some((key) => !/^[0-9a-f]{64}$/.test(key) || !members.includes(key)) + ) + throw new Error("Opening admins must be initial chat agents."); + return { key: soloAdminKey(channel), value: JSON.stringify(unique) }; +} + +/** Reconstruct the exact same promotions after interruption. Their timestamp + * and channel come from the saved create, so retries never invent a new grant + * that could undo a later demotion or removal. */ +export async function promoteSoloAdmins( + creation: OutgoingEvent, + writer: RelayWriter, + reader: RelayReader, + relayAuthor: string, + signal: AbortSignal, +) { + const create = creation.event; + const channel = create.tags.find(([tag]) => tag === "h")?.[1]; + const admins: unknown = JSON.parse(creation.recovery?.value ?? "null"); + if ( + create.kind !== 9007 || + !channel || + creation.recovery?.key !== soloAdminKey(channel) || + !Array.isArray(admins) || + !admins.length || + admins.some((key) => typeof key !== "string" || key === create.pubkey) || + soloAdminRecovery( + channel, + create.tags.flatMap(([tag, key]) => (tag === "p" && key ? [key] : [])), + admins, + )?.value !== creation.recovery.value + ) + throw new Error("The saved chat admin setup is invalid."); + const read = (filters: Parameters[0]) => + reader.read(filters, { signal, fresh: true, priority: "foreground" }); + for (const admin of admins as string[]) { + signal.throwIfAborted(); + const template = { + ...memberAdministrationTemplate(channel, { + pubkey: admin, + expectedRole: "member", + role: "admin", + }), + created_at: create.created_at, + }; + const id = getEventHash({ ...template, pubkey: create.pubkey }); + const recorded = async () => + ( + await read([ + { + kinds: [9000], + ids: [id], + authors: [create.pubkey], + limit: 1, + consistency: "strong", + }, + ]) + ).some((event) => event.id === id && event.pubkey === create.pubkey); + // A recorded grant remains complete even when its recipient was demoted. + if (await recorded()) continue; + if (Date.now() / 1000 - create.created_at >= 15 * 60) + throw new Error("Chat admin setup expired. Start a new chat to retry."); + const rosters = await read([ + { + kinds: [39002], + authors: [relayAuthor], + "#d": [channel], + limit: 1, + consistency: "strong", + }, + ]); + const roster = rosters.find( + (event) => + event.kind === 39002 && + event.pubkey === relayAuthor && + event.tags.some(([tag, value]) => tag === "d" && value === channel), + ); + const role = roster?.tags.find( + ([tag, key]) => tag === "p" && key === admin, + )?.[3]; + if (!role || !["member", "bot", "admin"].includes(role)) + throw new Error( + "An opening agent's access changed. Check chat access before retrying.", + ); + const signed = await writer.sign(template, signal); + signal.throwIfAborted(); + if (signed.id !== id || signed.pubkey !== create.pubkey) + throw new Error("The signer changed the chat admin command."); + try { + await writer.publish(signed, signal); + } catch (error) { + if (!(await recorded())) throw error; + } + // An OK alone is not proof of the requested role change. + if (!(await recorded())) + throw new Error( + "Chat admin setup is unconfirmed. Retry the opening message.", + ); + } +} diff --git a/src/features/solo/SoloDraft.test.tsx b/src/features/solo/SoloDraft.test.tsx index acc588dc2f..33920a23d3 100644 --- a/src/features/solo/SoloDraft.test.tsx +++ b/src/features/solo/SoloDraft.test.tsx @@ -314,6 +314,7 @@ it("uses restored explicit mentions, not a separate picker", async () => { undefined, false, undefined, + { admins: ["b".repeat(64)] }, ); expect(test.channelWrites.addAgents).not.toHaveBeenCalled(); expect(test.messages.send).toHaveBeenCalledWith(id, "@Outside agent Help", [ @@ -465,6 +466,7 @@ it("a refused start gives its prompt, files and settings back to a blank New cha undefined, true, undefined, + { admins: ["a".repeat(64)] }, ); expect(test.messages.send).toHaveBeenLastCalledWith( retry, @@ -866,6 +868,7 @@ it("keeps the chosen agent through draft remount, first send, refused-start reco undefined, false, undefined, + { admins: ["b".repeat(64)] }, ); expect(test.messages.send).toHaveBeenLastCalledWith(retry, "Hello", [ "b".repeat(64), @@ -1116,6 +1119,7 @@ it.each([true, false])( undefined, false, undefined, + { admins: ["a".repeat(64)] }, ); expect(test.messages.send).toHaveBeenCalledWith( id, @@ -2143,6 +2147,7 @@ it.each([false, true])( authority.pubkey, undefined, true, + { sign, publish }, ); const agent = { pubkey: viewer.pubkey, name: "Viewer", managed: true }; const eligible = { @@ -2264,6 +2269,9 @@ it.each(["remember", "off"])( await waitFor(() => expect(started).toHaveBeenCalledOnce()); expect(f.messages.send).toHaveBeenCalledOnce(); expect(f.channelWrites.create).toHaveBeenCalledOnce(); + expect((f.channelWrites.start.mock.calls[0] as unknown[])[6]).toEqual({ + admins: recipients.map((recipient) => recipient.pubkey), + }); const id = started.mock.calls[0]?.[0]; expect(readView("first-followup", `draft:${id}`, null)).toEqual({ text: "", @@ -3444,6 +3452,7 @@ it("shows an editable ordinary source link and sends it to the pill's default ag undefined, false, undefined, + { admins: ["a".repeat(64)] }, ); expect(t.messages.send).toHaveBeenCalledWith( id, @@ -3643,6 +3652,7 @@ function soloDraftWithInventory( undefined, false, undefined, + { admins: [aaron.pubkey] }, ); expect(test.messages.send).toHaveBeenCalledWith(id, "@Aaron hi", [ aaron.pubkey, @@ -3796,6 +3806,7 @@ it.each([false, true])( expect(test.channelWrites.start.mock.calls[0]?.[2]).toEqual( prepareStart.mock.calls[0]?.[1].members, ); + expect(startOptions(test)).toMatchObject({ admins: ["a".repeat(64)] }); expect(test.messages.send.mock.calls[0]?.[0]).toBe( prepareStart.mock.calls[0]?.[1].channelId, ); @@ -3985,7 +3996,10 @@ it("a region's New chat starts a labeled chat its source can find, without filin await waitFor(() => expect(onStarted).toHaveBeenCalledOnce()); const id = test.channelWrites.create.mock.calls[0]?.[0] ?? ""; // Unguarded, so the Outbox replays it after a restart like any New chat. - expect(startOptions(test)).toEqual({ labels: [REGION] }); + expect(startOptions(test)).toEqual({ + admins: ["a".repeat(64)], + labels: [REGION], + }); expect(readView("test", regionStartKey(id), null)).toEqual({ region: REGION, workspace: "work", diff --git a/src/features/solo/SoloDraft.tsx b/src/features/solo/SoloDraft.tsx index 5ecd5171fb..c1d5620633 100644 --- a/src/features/solo/SoloDraft.tsx +++ b/src/features/solo/SoloDraft.tsx @@ -574,7 +574,7 @@ export function SoloDraft({ } : undefined, // Unguarded, so a restart can retry it like any New chat. - ...(region ? [{ labels: [region] }] : []), + { admins: recipients, ...(region ? { labels: [region] } : {}) }, ); } catch (reason) { if (startKey) writeView(scope, startKey, null); From c111ae8c6dd4083da794d1d66637510871e537fc Mon Sep 17 00:00:00 2001 From: Taylor Ho Date: Mon, 16 Nov 2026 14:35:09 -0800 Subject: [PATCH 02/17] test(search): await find shortcut registration Wait for the fixture shortcut installed by React before invoking it. Page load alone does not establish that its registration effect ran. Keep both geometry journeys and their assertions unchanged. Co-authored-by: Carl Signed-off-by: Taylor Ho --- tests/browser/find-on-screen.spec.mjs | 10 +++++++--- 1 file changed, 7 insertions(+), 3 deletions(-) diff --git a/tests/browser/find-on-screen.spec.mjs b/tests/browser/find-on-screen.spec.mjs index 0ac511ca94..5bc720d1ac 100644 --- a/tests/browser/find-on-screen.spec.mjs +++ b/tests/browser/find-on-screen.spec.mjs @@ -44,6 +44,10 @@ test.afterAll(async () => { const bar = (page) => page.locator("search"); const field = (page) => page.getByRole("searchbox", { name: "Find on screen" }); +const openFind = async (page) => { + await page.waitForFunction(() => typeof window.openFind === "function"); + await page.evaluate(() => window.openFind()); +}; const box = (locator) => locator.evaluate((element) => { const { x, y, width, height } = element.getBoundingClientRect(); @@ -78,7 +82,7 @@ test("the bar keeps the window's top-right corner inside a dialog", async ({ const errors = watchPageErrors(page); await page.setViewportSize({ width: 1200, height: 800 }); await page.goto(url); - await page.evaluate(() => window.openFind()); + await openFind(page); await expect(field(page)).toBeFocused(); const outside = await box(bar(page)); await field(page).press("Escape"); @@ -86,7 +90,7 @@ test("the bar keeps the window's top-right corner inside a dialog", async ({ await page.evaluate(() => window.setModal(true)); const dialog = page.getByRole("dialog", { name: "Members" }); await expect(dialog).toBeVisible(); - await page.evaluate(() => window.openFind()); + await openFind(page); await expect(dialog.locator("search")).toHaveCount(1); await expect(field(page)).toBeFocused(); expect(await box(bar(page))).toEqual(outside); @@ -105,7 +109,7 @@ test("stepping reveals each match in a long code block", async ({ page }) => { const errors = watchPageErrors(page); await page.setViewportSize({ width: 900, height: 700 }); await page.goto(url); - await page.evaluate(() => window.openFind()); + await openFind(page); await field(page).fill("needle"); const status = page.locator("search [role=status]"); await expect(status).toHaveText("1 of 2"); From b77b428e114f8cc19ebbf6bc0aa8cf0791056dc0 Mon Sep 17 00:00:00 2001 From: Taylor Ho Date: Mon, 16 Nov 2026 14:35:11 -0800 Subject: [PATCH 03/17] test(solo): consolidate opening admin recovery coverage Exercise sequential grants, lost acknowledgments, command shape and fixed signing identity/timestamp in the existing session delivery journey. Retain durable restart and exact command replay there, plus focused stale receipt removal, access changes, expiry and invalid-intent helper checks. Remove the duplicate helper journey and its unused fixture data without changing the opening-agent admin behavior or publication gate. Co-authored-by: Carl Signed-off-by: Taylor Ho --- .../relay/solo-admins.integration.test.ts | 37 ++++++-- src/features/relay/solo-admins.test.ts | 84 ++----------------- 2 files changed, 37 insertions(+), 84 deletions(-) diff --git a/src/features/relay/solo-admins.integration.test.ts b/src/features/relay/solo-admins.integration.test.ts index 57586b3f9c..8395617a21 100644 --- a/src/features/relay/solo-admins.integration.test.ts +++ b/src/features/relay/solo-admins.integration.test.ts @@ -134,7 +134,7 @@ function setup() { }; } -it("holds the opening message and local wake until all admins are ready through the existing host route", async () => { +it("confirms a lost grant ACK and holds the opening message and local wake until every admin is ready", async () => { const h = setup(); const owner = await h.open(); const heard = vi.fn(); @@ -145,13 +145,20 @@ it("holds the opening message and local wake until all admins are ready through }); const publish = h.adminPublish.getMockImplementation(); assert.exists(publish); - h.adminPublish.mockImplementation(async (event) => { - await held; - await publish(event); - }); + h.adminPublish + .mockImplementationOnce(async (event) => { + await publish(event); + throw new Error("ACK lost"); + }) + .mockImplementationOnce(async (event) => { + await held; + await publish(event); + }); try { const { message } = h.start(owner); - await vi.waitFor(() => expect(h.adminPublish).toHaveBeenCalledOnce()); + await vi.waitFor(() => expect(h.adminPublish).toHaveBeenCalledTimes(2)); + expect(h.roles.get(h.agents[0])).toBe("admin"); + expect(h.roles.get(h.agents[1])).toBe("member"); expect(h.genericPublish.mock.calls.map(([event]) => event.kind)).toEqual([ 9007, ]); @@ -167,6 +174,24 @@ it("holds the opening message and local wake until all admins are ready through expect(h.roles.get(h.workspaceAgent)).toBe("member"); expect(h.roles.get(h.viewer.pubkey)).toBe("owner"); expect(h.adminPublish).toHaveBeenCalledTimes(2); + expect(h.adminPublish.mock.calls.map(([event]) => event.tags)).toEqual( + h.agents.map((key) => [ + ["h", h.channel], + ["p", key], + ["role", "admin"], + ]), + ); + const create = h.genericPublish.mock.calls.find( + ([event]) => event.kind === 9007, + )?.[0]; + assert.exists(create); + expect( + h.adminPublish.mock.calls.every( + ([event]) => + event.pubkey === h.viewer.pubkey && + event.created_at === create.created_at, + ), + ).toBe(true); expect( owner.session.outbox ?.snapshot() diff --git a/src/features/relay/solo-admins.test.ts b/src/features/relay/solo-admins.test.ts index 113ef2cf68..d3e12f5d30 100644 --- a/src/features/relay/solo-admins.test.ts +++ b/src/features/relay/solo-admins.test.ts @@ -9,22 +9,20 @@ function setup() { const owner = keypair(), relay = keypair(); const agents: [string, string] = [keypair().pubkey, keypair().pubkey]; - const workspaceAgent = keypair().pubkey; const channel = crypto.randomUUID(); - const members = [...agents, workspaceAgent]; const create = signed(owner, { kind: 9007, content: "", created_at: Math.floor(Date.now() / 1000), - tags: [["h", channel], ...members.map((key) => ["p", key])], + tags: [["h", channel], ...agents.map((key) => ["p", key])], }); const creation: OutgoingEvent = { event: create, delivery: "accepted", - recovery: soloAdminRecovery(channel, members, agents), + recovery: soloAdminRecovery(channel, agents, agents), }; const records = new Map(); - const roles = new Map(members.map((key) => [key, "member"])); + const roles = new Map(agents.map((key) => [key, "member"])); const read = vi.fn(async (filters: readonly ReadFilter[]) => { const roster = signed(relay, { kind: 39002, @@ -55,10 +53,7 @@ function setup() { const run = (saved = creation) => promoteSoloAdmins(saved, writer, { read }, relay.pubkey, controller.signal); return { - owner, agents, - workspaceAgent, - channel, creation, records, roles, @@ -66,82 +61,15 @@ function setup() { writer, publish, run, - controller, }; } -it("promotes all opening agents in order, confirms a lost ACK, and leaves workspace-only agents ordinary", async () => { +it("does not restore a removed opening agent when replaying a stale creation receipt", async () => { const h = setup(); - const normal = h.publish.getMockImplementation(); - assert.exists(normal); - let release = () => {}; - const held = new Promise((resolve) => { - release = resolve; - }); - let entered = () => {}; - const started = new Promise((resolve) => { - entered = resolve; - }); - h.publish - .mockImplementationOnce(async (event) => { - await normal(event); - throw new Error("ACK lost"); - }) - .mockImplementationOnce(async (event) => { - entered(); - await held; - await normal(event); - }); - let finished = false; - const work = h.run().then(() => { - finished = true; - }); - try { - await started; - expect(finished).toBe(false); - expect(h.roles.get(h.agents[0])).toBe("admin"); - expect(h.roles.get(h.agents[1])).toBe("member"); - expect(h.roles.get(h.workspaceAgent)).toBe("member"); - } finally { - release(); - } - await work; - expect(h.agents.map((key) => h.roles.get(key))).toEqual(["admin", "admin"]); - expect(h.publish.mock.calls.map(([event]) => event.tags)).toEqual( - h.agents.map((key) => [ - ["h", h.channel], - ["p", key], - ["role", "admin"], - ]), - ); - expect( - h.publish.mock.calls.every( - ([event]) => - event.pubkey === h.owner.pubkey && - event.created_at === h.creation.event.created_at, - ), - ).toBe(true); -}); - -it("resumes the exact failed grant after restart without restoring a demoted or removed opening agent", async () => { - const h = setup(); - const normal = h.publish.getMockImplementation(); - assert.exists(normal); - h.publish - .mockImplementationOnce(normal) - .mockRejectedValueOnce(new Error("offline")); - await expect(h.run()).rejects.toThrow("offline"); - const failedId = h.publish.mock.calls[1]?.[0].id; - h.roles.set(h.agents[0], "bot"); - await h.run(structuredClone(h.creation)); - expect(h.publish.mock.calls.map(([event]) => event.id).slice(1)).toEqual([ - failedId, - failedId, - ]); - expect(h.roles.get(h.agents[0])).toBe("bot"); + await h.run(); h.roles.delete(h.agents[0]); await h.run(structuredClone(h.creation)); - expect(h.publish).toHaveBeenCalledTimes(3); + expect(h.publish).toHaveBeenCalledTimes(2); expect(h.roles.has(h.agents[0])).toBe(false); }); From 543f23b8bfcb987c0b3b9ece9341c801feec4ce7 Mon Sep 17 00:00:00 2001 From: Taylor Ho Date: Mon, 16 Nov 2026 15:15:22 -0800 Subject: [PATCH 04/17] test(navigation): isolate warm sidebar preference requests Count only the selected community's preference decoding when checking a warm Messages return. Background unread loading for another community must not count as a re-fetch of the retained sidebar snapshot. Drain held route continuations before removing their interception so cleanup does not auto-continue a request before its handler resumes. Preserve the existing frame, selection, scroll and zero-count assertions. Co-authored-by: Carl Signed-off-by: Taylor Ho --- tests/browser/navigation-groups.spec.mjs | 21 ++++++++++++--------- 1 file changed, 12 insertions(+), 9 deletions(-) diff --git a/tests/browser/navigation-groups.spec.mjs b/tests/browser/navigation-groups.spec.mjs index e6f773178e..8a9e9abeb7 100644 --- a/tests/browser/navigation-groups.spec.mjs +++ b/tests/browser/navigation-groups.spec.mjs @@ -1027,15 +1027,16 @@ scrollTest( expect(scroll).toBeGreaterThan(100); await openPage(page, "Workflows"); await expect(sidebar).toBeHidden(); - let release; - const held = new Promise((resolve) => { - release = resolve; - }); + const held = gate(); + // Other communities may warm their unread preferences independently. + const preferences = "**/api/relay/primary/sidebar-preferences"; + const continuations = []; let decodes = 0; - await page.route("**/sidebar-preferences", async (route) => { + await page.route(preferences, (route) => { decodes++; - await held; - await route.continue(); + const continued = held.promise.then(() => route.continue()); + continuations.push(continued); + return continued; }); await page.evaluate(() => { window.sidebarFrames = []; @@ -1084,8 +1085,10 @@ scrollTest( "Page return must reuse the engine snapshot, not fetch/decode again", ).toBe(0); } finally { - release(); - await page.unroute("**/sidebar-preferences"); + held.resolve(); + // Removing the route can auto-continue an in-flight request. + await Promise.all(continuations); + await page.unroute(preferences); } }, ); From 802ad7560d381c59971e86dbc82f4f1f65eb486a Mon Sep 17 00:00:00 2001 From: Taylor Ho Date: Mon, 16 Nov 2026 16:49:17 -0800 Subject: [PATCH 05/17] feat(solo): grant admin when owners add agents later Request Admin in the existing membership addition for new agents in an owned Solo chat. Keep existing members and saved Bot/Admin retry events unchanged, while preserving other channel admission defaults. Co-authored-by: Carl Signed-off-by: Taylor Ho --- docs/buzz-help.md | 6 +- docs/solo/README.md | 9 +- docs/solo/sharing.md | 6 +- .../channels/ChannelMembersDialog.test.tsx | 27 ++++- src/features/relay/channel-writes.ts | 13 ++- .../relay/session-agent-admission.test.ts | 107 ++++++++++++++---- 6 files changed, 128 insertions(+), 40 deletions(-) diff --git a/docs/buzz-help.md b/docs/buzz-help.md index b6f05086fa..af10079875 100644 --- a/docs/buzz-help.md +++ b/docs/buzz-help.md @@ -422,8 +422,10 @@ and are asked to sign in again in Buzz. - **Solo** organizes your chats with agents. Choose **New chat**, select or tag an agent, and send a message. Every agent addressed in the opening message becomes a chat admin before that message is delivered; you remain owner. - Agents included only through workspace defaults, or added later, keep ordinary - participation. If admin setup is interrupted, Retry on the opening message + Agents you add later to a Solo chat you own also join as admins, whether from + the composer or Chat access. Agents included only through workspace defaults + keep ordinary participation, and existing members keep their saved roles. + If admin setup is interrupted, Retry on the opening message continues it without restoring later demotions or removals. If setup expires, start a new chat. Solo conversations continue at the chat's top level rather than requiring a new thread for each reply. Where available, use diff --git a/docs/solo/README.md b/docs/solo/README.md index 36bfe5958d..f869936a43 100644 --- a/docs/solo/README.md +++ b/docs/solo/README.md @@ -102,13 +102,16 @@ behavior on the label, so a rename touches copy only. harnesses that only read `about` need to learn the label. - The app promotes every agent addressed in the opening message through the existing member-administration commands before releasing that message to - local agents or the relay. Workspace-only agents and later additions remain - ordinary participants. The create's local Outbox receipt retains the opening + local agents or the relay. Workspace-only agents remain ordinary participants. + When the viewer owns the Solo chat, new agents added later through the composer + or Chat access receive Admin in the membership command. Existing members keep + their saved roles; retries retain the original addition's role and command ID. + The create's local Outbox receipt retains the opening recipients across interruptions; retries reconstruct the same grants and confirm their recorded IDs before sending. A recorded grant stays complete after a later demotion or removal. Expired, unrecorded grants require a new chat; recovery never changes a command's timestamp. This needs no relay update - and does not change existing chats or tool-created Solo chats. + and does not migrate existing members' roles or change tool-created grants. - The Buzz tools' `channel_create` with `solo` sends the same create for any caller, including the standalone stdio server: signed by the caller, with the label and any `members` it names. The caller is the creator, so an agent's diff --git a/docs/solo/sharing.md b/docs/solo/sharing.md index b4fd011238..af23d63e2d 100644 --- a/docs/solo/sharing.md +++ b/docs/solo/sharing.md @@ -39,8 +39,10 @@ people, agents and channels** for an owner who can add agents) filters current access and lists people under **Not in this chat**, each with an **Add** button; Enter adds the highlighted person. Adding is immediate and uses the Solo share rule (`canShareSoloChat`), with per-person **Adding…**, error and **Retry** states. The -owner's selectable agents are offered too and join as Bot, even with a Guest -admission default, without starting a run. Composer mentions use the same grant. +owner's selectable agents are offered too and join as Admin, even with a Guest +admission default, without starting a run. Composer mentions use the same grant +when the viewer owns the chat; other participants' composer additions use Bot. +Existing members keep their roles, and retries finish the original saved grant. Where the viewer cannot add agents, a note says to mention an agent in the chat instead. Current access uses the channel groups (**People**, **Agents**) with Owner and diff --git a/src/bundled/channels/ChannelMembersDialog.test.tsx b/src/bundled/channels/ChannelMembersDialog.test.tsx index e546683e28..68054e2c48 100644 --- a/src/bundled/channels/ChannelMembersDialog.test.tsx +++ b/src/bundled/channels/ChannelMembersDialog.test.tsx @@ -199,6 +199,20 @@ async function setup( profile(viewer, { name: "Carl" }), personProfile, ]; + const currentRoster = () => + type === "solo" + ? signed(relay, { + kind: 39002, + created_at: clock, + content: "", + tags: [ + ["d", id], + ...members.map((key) => + key === viewer.pubkey ? ["p", key, "", "owner"] : ["p", key], + ), + ], + }) + : roster(relay, id, members, clock); const query = vi.fn(async (filters: Parameters[1][]) => { if (filters.some((filter) => filter.search)) { if (searchFailure) throw new Error("Search offline"); @@ -225,8 +239,8 @@ async function setup( await options.pendingMemberNames; if (filters.some((filter) => filter.kinds?.includes(39002))) await rosterRead; - return [roster(relay, id, members, clock), ...stableEvents].filter( - (event) => filters.some((filter) => matchesEvent(event, filter)), + return [currentRoster(), ...stableEvents].filter((event) => + filters.some((filter) => matchesEvent(event, filter)), ); }); const readAgentLibrary = vi.fn( @@ -320,7 +334,8 @@ async function setup( viewer, replaceRoster: (keys: string[]) => { members.splice(0, members.length, ...keys); - live?.receive([roster(relay, id, members, ++clock)]); + clock++; + live?.receive([currentRoster()]); }, delayRoster: () => { applyAddition = false; @@ -3024,7 +3039,7 @@ it("lets the Solo owner add an agent without sending a message", async () => { ).toEqual([ ["h", "11111111-1111-4111-8111-111111111111"], ["p", t.agent.pubkey], - ["role", "bot"], + ["role", "admin"], ]); await t.user.click(screen.getByRole("button", { name: "Close" })); await t.user.click(t.trigger); @@ -3256,7 +3271,7 @@ it.each([false, true])( ); it.each(["private", "public"] as const)( - "adds the Solo owner's agent as Bot in a %s chat with a Guest default", + "adds the Solo owner's agent as Admin in a %s chat with a Guest default", async (visibility) => { const t = await setup("solo", false, true, undefined, undefined, { visibility, @@ -3268,7 +3283,7 @@ it.each(["private", "public"] as const)( ); await screen.findByText("Fixture agent added."); expect(t.publish).toHaveBeenCalledOnce(); - expect(t.publish.mock.calls[0]?.[0].tags).toContainEqual(["role", "bot"]); + expect(t.publish.mock.calls[0]?.[0].tags).toContainEqual(["role", "admin"]); }, ); diff --git a/src/features/relay/channel-writes.ts b/src/features/relay/channel-writes.ts index 343549c963..e00e5b1860 100644 --- a/src/features/relay/channel-writes.ts +++ b/src/features/relay/channel-writes.ts @@ -462,8 +462,12 @@ export function createChannelWrites( if (active?.() === false) throw new DOMException("Channel addition cancelled", "AbortError"); const original = await refreshMembership(id); - // Solo agents must be able to reply even with a saved Guest admission default. - const roleTags = original.channelType === "solo" ? [["role", "bot"]] : []; + // Owners' new Solo agents get Admin; other Solo additions can still reply + // even with a saved Guest admission default. Existing members are untouched. + const roleTags = + original.channelType === "solo" + ? [["role", original.viewerRole === "owner" ? "admin" : "bot"]] + : []; if (active?.() === false) throw new DOMException("Channel addition cancelled", "AbortError"); const unique = [...new Set(keys)].filter( @@ -511,7 +515,10 @@ export function createChannelWrites( ([name, value]) => name === "p" && value === key, ) && roles.length === roleTags.length && - roles.every((tag) => tag.length === 2 && tag[1] === "bot") + // Recovery finishes the saved grant even if the viewer's role changed. + roles.every( + (tag) => tag.length === 2 && ["bot", "admin"].includes(tag[1]), + ) ); }); if (previous && Date.now() / 1000 - previous.event.created_at >= 15 * 60) diff --git a/src/features/relay/session-agent-admission.test.ts b/src/features/relay/session-agent-admission.test.ts index 416919e95f..bbc48a0d8c 100644 --- a/src/features/relay/session-agent-admission.test.ts +++ b/src/features/relay/session-agent-admission.test.ts @@ -6,7 +6,13 @@ import { matchesEvent } from "./projection"; import type { RelayEvent } from "./events"; import { SOLO_LABEL } from "../solo/labels"; -function setup(visibility: "private" | "public" = "private") { +type ViewerRole = "owner" | "admin" | "member"; + +function setup( + visibility: "private" | "public" = "private", + initialRole: ViewerRole = "member", +) { + let viewerRole = initialRole; const viewer = keypair(), relay = keypair(), agent = keypair(); @@ -43,6 +49,18 @@ function setup(visibility: "private" | "public" = "private") { content: "", tags: [["d", id], ["t", type], ["name", id], ...extra], }); + const membership = (id: string, keys: string[]) => + signed(relay, { + kind: 39002, + created_at: clock, + content: "", + tags: [ + ["d", id], + ...keys.map((key) => + key === viewer.pubkey ? ["p", key, "", viewerRole] : ["p", key], + ), + ], + }); const publish = vi.fn(async (_event: RelayEvent) => { const target = _event.tags.find(([name]) => name === "h")?.[1]; if (denied) throw new PublishRejected("Only channel admins can add agents"); @@ -107,8 +125,8 @@ function setup(visibility: "private" | "public" = "private") { ["t", SOLO_LABEL], ["join_role", "guest"], ]), - roster(relay, parent, members, clock), - roster(relay, child, childMembers, clock), + membership(parent, members), + membership(child, childMembers), ]; return events.filter((event) => filters.some((filter) => matchesEvent(event, filter)), @@ -161,6 +179,10 @@ function setup(visibility: "private" | "public" = "private") { return signingRequested; }, releaseSigning: () => releaseSigning?.(), + setViewerRole: (role: ViewerRole) => { + viewerRole = role; + clock++; + }, setDenied: (value: boolean) => { denied = value; }, @@ -178,10 +200,18 @@ function setup(visibility: "private" | "public" = "private") { }; } -it.each(["private", "public"] as const)( - "adds an outside agent as Bot with a Guest default in a %s Solo chat", - async (visibility) => { - const test = setup(visibility); +it.each( + (["private", "public"] as const).flatMap((visibility) => + (["owner", "admin", "member"] as const).map((viewerRole) => ({ + visibility, + viewerRole, + addedRole: viewerRole === "owner" ? "admin" : "bot", + })), + ), +)( + "adds an agent as $addedRole for a $viewerRole in a $visibility Solo chat with a Guest default", + async ({ visibility, viewerRole, addedRole }) => { + const test = setup(visibility, viewerRole); try { await test.ready(); await test.owner.session.channelWrites.addAgents(test.child, [ @@ -194,7 +224,7 @@ it.each(["private", "public"] as const)( tags: expect.arrayContaining([ ["h", test.child], ["p", test.agent], - ["role", "bot"], + ["role", addedRole], ]), }); expect( @@ -276,24 +306,53 @@ it("reports channel-specific uncertainty when an accepted addition lacks roster } }); -it("keeps channel permission failures and retries the same saved invitation", async () => { - const test = setup(); +it.each([ + { initialRole: "member", retryRole: "member", addedRole: "bot" }, + { initialRole: "member", retryRole: "owner", addedRole: "bot" }, + { initialRole: "owner", retryRole: "member", addedRole: "admin" }, +] as const)( + "keeps the saved $addedRole invitation when $initialRole retries as $retryRole", + async ({ initialRole, retryRole, addedRole }) => { + const test = setup("private", initialRole); + try { + await test.ready(); + test.setDenied(true); + await expect( + test.owner.session.channelWrites.addAgents(test.child, [test.agent]), + ).rejects.toThrow(/Only channel admins/); + expect( + test.owner.session.channels + .list() + .channels.find((item) => item.id === test.child)?.members, + ).not.toContain(test.agent); + const first = test.publish.mock.calls[0]?.[0]; + expect(first?.tags).toContainEqual(["role", addedRole]); + test.setViewerRole(retryRole); + test.setDenied(false); + await test.owner.session.channelWrites.addAgents(test.child, [ + test.agent, + ]); + expect(test.publish.mock.calls[1]?.[0]).toEqual(first); + expect(test.publish).toHaveBeenCalledTimes(2); + } finally { + test.owner.dispose(); + } + }, +); +it("preserves ordinary channel admission defaults for an owner", async () => { + const test = setup("private", "owner"); try { await test.ready(); - test.setDenied(true); - await expect( - test.owner.session.channelWrites.addAgents(test.child, [test.agent]), - ).rejects.toThrow(/Only channel admins/); - expect( - test.owner.session.channels - .list() - .channels.find((item) => item.id === test.child)?.members, - ).not.toContain(test.agent); - const first = test.publish.mock.calls[0]?.[0].id; - test.setDenied(false); - await test.owner.session.channelWrites.addAgents(test.child, [test.agent]); - expect(test.publish.mock.calls[1]?.[0].id).toBe(first); - expect(test.publish).toHaveBeenCalledTimes(2); + await test.owner.session.channelWrites.addAgents(test.parent, [test.agent]); + expect(test.publish).toHaveBeenCalledOnce(); + const tags = test.publish.mock.calls[0]?.[0].tags ?? []; + expect(tags).toEqual( + expect.arrayContaining([ + ["h", test.parent], + ["p", test.agent], + ]), + ); + expect(tags.filter(([name]) => name === "role")).toEqual([]); } finally { test.owner.dispose(); } From 549140abd1fa185141fd151cf6db25e71971bfd5 Mon Sep 17 00:00:00 2001 From: Taylor Ho Date: Mon, 16 Nov 2026 16:53:17 -0800 Subject: [PATCH 06/17] fix(solo): narrow saved invitation role matching Compare optional role tag values directly while retaining exact Bot and Admin grants for retries. Co-authored-by: Carl Signed-off-by: Taylor Ho --- src/features/relay/channel-writes.ts | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/src/features/relay/channel-writes.ts b/src/features/relay/channel-writes.ts index e00e5b1860..56ff5a89a6 100644 --- a/src/features/relay/channel-writes.ts +++ b/src/features/relay/channel-writes.ts @@ -517,7 +517,8 @@ export function createChannelWrites( roles.length === roleTags.length && // Recovery finishes the saved grant even if the viewer's role changed. roles.every( - (tag) => tag.length === 2 && ["bot", "admin"].includes(tag[1]), + (tag) => + tag.length === 2 && (tag[1] === "bot" || tag[1] === "admin"), ) ); }); From 057088b86ef5526a58cc261ceb47ded4f8c8ea09 Mon Sep 17 00:00:00 2001 From: Taylor Ho Date: Mon, 16 Nov 2026 17:45:34 -0800 Subject: [PATCH 07/17] fix(relay): route saved admin additions through browser host Admit only the exact single-Admin addition with its original client ID through the existing member-administration boundary. Keep generic signing closed and verify exact signed-event replay through the broker after restart. Co-authored-by: Carl Signed-off-by: Taylor Ho --- browser-host/relay-broker-api.test.mjs | 80 +++++++++++++++++++ browser-host/relay-broker.mjs | 8 +- .../administration-protocol.ts | 27 +++++++ src/features/relay/transport.ts | 11 ++- 4 files changed, 123 insertions(+), 3 deletions(-) diff --git a/browser-host/relay-broker-api.test.mjs b/browser-host/relay-broker-api.test.mjs index bb56f0c3df..5eb5ab4728 100644 --- a/browser-host/relay-broker-api.test.mjs +++ b/browser-host/relay-broker-api.test.mjs @@ -4005,6 +4005,66 @@ test("details routes are narrow, require the live owner, and do not widen lifecy } }); +test("later Admin additions cross the broker and replay the exact saved event after restart", async () => { + const h = await harness(success); + let first; + let restored; + let live; + let records = []; + const storage = { + load: () => structuredClone(records), + save: (next) => { + records = structuredClone(next); + }, + }; + try { + const transport = await connectBrokerTransport(h.base); + first = createOutbox(transport.viewer, transport.writer, storage); + await first.outbox.ready(); + const id = first.outbox.send({ + kind: 9000, + content: "", + tags: [ + ["h", "11111111-1111-4111-8111-111111111111"], + ["p", getPublicKey(new Uint8Array(32).fill(5))], + ["role", "admin"], + ], + }); + await vi.waitFor(() => + expect(first.outbox.snapshot()[0]?.delivery).toBe("failed"), + ); + // Signing succeeds through the purpose-bound route. Publication needs a live socket. + const signed = first.outbox.snapshot()[0]?.signed; + expect(signed).toBeDefined(); + const saved = JSON.parse(JSON.stringify(signed)); + expect(verifyEvent(structuredClone(saved))).toBe(true); + expect(saved.tags).toContainEqual(["role", "admin"]); + expect(saved.tags.at(-1)?.[0]).toBe("client-id"); + expect(h.publications).toHaveLength(0); + expect((await h.post("sign", saved)).status).toBe(400); + expect((await h.post("publish", saved)).status).toBe(400); + first.dispose(); + wallClock += 10000; + const resumed = await connectBrokerTransport(h.base); + live = await openBrokerSocket(resumed); + restored = createOutbox(resumed.viewer, resumed.writer, storage); + await restored.outbox.ready(); + restored.outbox.retry(id); + await vi.waitFor(() => + expect(restored.outbox.snapshot()[0]?.delivery).toBe("accepted"), + ); + expect(h.publications).toEqual([saved]); + expect( + JSON.parse(JSON.stringify(restored.outbox.snapshot()[0]?.signed)), + ).toEqual(saved); + } finally { + first?.dispose(); + restored?.dispose(); + live?.dispose(); + await h.close(); + } +}); + test("member administration uses isolated shape-limited routes and the current community socket", async () => { const h = await harness(success); let live; @@ -4061,6 +4121,26 @@ test("member administration uses isolated shape-limited routes and the current c { ...template, tags: [...template.tags, ["h", id]] }, { ...template, tags: null }, { ...template, tags: [null] }, + ...[ + [...template.tags, ["client-id", "invalid"]], + [ + ...template.tags, + ["client-id", "22222222-2222-4222-8222-222222222222"], + ["p", target], + ], + [ + template.tags[0], + ["p", transport.viewer], + template.tags[2], + ["client-id", "22222222-2222-4222-8222-222222222222"], + ], + [ + template.tags[0], + template.tags[1], + ["role", "owner"], + ["client-id", "22222222-2222-4222-8222-222222222222"], + ], + ].map((tags) => ({ ...template, tags })), ]; for (const event of invalid) for (const route of [ diff --git a/browser-host/relay-broker.mjs b/browser-host/relay-broker.mjs index f609f56bdc..cce880e605 100644 --- a/browser-host/relay-broker.mjs +++ b/browser-host/relay-broker.mjs @@ -24,7 +24,10 @@ import { communityGitRepository, parseGitRead, } from "../src/features/repos/git.ts"; -import { validateMemberAdministrationTemplate } from "../src/features/channel-members/administration-protocol.ts"; +import { + isAdminAddition, + validateMemberAdministrationTemplate, +} from "../src/features/channel-members/administration-protocol.ts"; import { validateLifecycleTemplate } from "../src/features/relay/channel-lifecycle-protocol.ts"; import { validateDetailsTemplate } from "../src/features/relay/channel-details-protocol.ts"; import { validateArchiveRequestTemplate } from "../src/features/relay/identity-archive-protocol.ts"; @@ -2963,7 +2966,8 @@ export function relayBrokerPlugin({ if (signing || publishing) { if (administration) { try { - validateMemberAdministrationTemplate(filters, viewer); + if (!isAdminAddition(filters, viewer)) + validateMemberAdministrationTemplate(filters, viewer); } catch { return json(res, 400, { error: "Invalid member administration command", diff --git a/src/features/channel-members/administration-protocol.ts b/src/features/channel-members/administration-protocol.ts index 98a173bfbd..93ffc0758f 100644 --- a/src/features/channel-members/administration-protocol.ts +++ b/src/features/channel-members/administration-protocol.ts @@ -247,6 +247,33 @@ export function memberAdministrationTemplate( }; } +/** The exact single-Admin addition saved by Outbox, including its retry ID. + * This uses the existing administration boundary; ordinary writes stay closed. */ +export function isAdminAddition(event: EventTemplate, viewer: string): boolean { + const tags = event?.tags; + if (!Array.isArray(tags)) return false; + const client = tags.at(-1); + if ( + event.kind !== 9000 || + tags.length !== 4 || + tags[2]?.[0] !== "role" || + tags[2]?.[1] !== "admin" || + client?.length !== 2 || + client[0] !== "client-id" + ) + return false; + try { + lifecycleChannelId(client[1] ?? ""); + validateMemberAdministrationTemplate( + { ...event, tags: tags.slice(0, -1) }, + viewer, + ); + return true; + } catch { + return false; + } +} + /** Purpose-bound broker admission; relay remains the authoritative ACL boundary. */ export function validateMemberAdministrationTemplate( event: EventTemplate, diff --git a/src/features/relay/transport.ts b/src/features/relay/transport.ts index f7558cf6e4..ae586ea1ad 100644 --- a/src/features/relay/transport.ts +++ b/src/features/relay/transport.ts @@ -1,3 +1,4 @@ +import { isAdminAddition } from "../channel-members/administration-protocol.ts"; import type { ArtifactIncrementalReader } from "./artifact-incremental-reader.ts"; import type { VerifiedProfileAuthority } from "./verified-profile"; import type { ReminderHost } from "./reminders"; @@ -563,6 +564,7 @@ export async function connectBrokerTransport( "invalid-response", "Relay broker session is malformed", ); + const viewer = session.viewer; let traffic: LiveSubscription | undefined; const presence = presenceObservation(); const relayHttpUrl = relayHttpBase(session.relayHttpUrl, session.relayUrl); @@ -572,6 +574,8 @@ export async function connectBrokerTransport( "X-Buzz-Live-ID": traffic?.identity?.() ?? "", }); const publish = async (event: RelayEvent, signal: AbortSignal) => { + if (session.memberAdministration === true && isAdminAddition(event, viewer)) + return routeWriter("member-administration").publish(event, signal); const result = await fetch(`${endpoint}/publish`, { method: "POST", credentials: "same-origin", @@ -583,6 +587,11 @@ export async function connectBrokerTransport( return acceptPublish(result, event.id); }; const sign = async (template: EventTemplate, signal: AbortSignal) => { + if ( + session.memberAdministration === true && + isAdminAddition(template, viewer) + ) + return routeWriter("member-administration").sign(template, signal); const result = await fetch(`${endpoint}/sign`, { method: "POST", credentials: "same-origin", @@ -596,7 +605,7 @@ export async function connectBrokerTransport( return event; }; /** Dedicated shape-limited host sign/publish routes, separate from the outbox writer. */ - const routeWriter = (route: string): RelayWriter => ({ + const routeWriter = (route: string) => ({ async sign(template: EventTemplate, signal: AbortSignal) { const response = await fetch(`${endpoint}/${route}-sign`, { method: "POST", From 85459e5f544757c03d6866e24bb653e13ac097d2 Mon Sep 17 00:00:00 2001 From: Taylor Ho Date: Mon, 16 Nov 2026 17:56:57 -0800 Subject: [PATCH 08/17] fix(outbox): let expired admin setup be abandoned safely Make expired delivered setup an explicit recovery-owner removal. Preserve the chat, current roles and gate on storage failure; cancel an active grant before publication when its receipt is removed. Expose abandonment across the expiry deadline without adding a timer. Co-authored-by: Carl Signed-off-by: Taylor Ho --- docs/buzz-help.md | 3 +- docs/solo/README.md | 7 +- src/bundled/channels/OutboxStatus.test.tsx | 152 ++++++++++++++++++ src/bundled/channels/OutboxStatus.tsx | 36 ++++- src/features/relay/channel-writes.ts | 37 +++-- .../relay/solo-admins.integration.test.ts | 59 +++++++ src/features/relay/solo-admins.test.ts | 45 +++++- src/features/relay/solo-admins.ts | 34 +++- 8 files changed, 349 insertions(+), 24 deletions(-) diff --git a/docs/buzz-help.md b/docs/buzz-help.md index 0b5b8bc593..6dc9c13b4b 100644 --- a/docs/buzz-help.md +++ b/docs/buzz-help.md @@ -427,7 +427,8 @@ and are asked to sign in again in Buzz. keep ordinary participation, and existing members keep their saved roles. If admin setup is interrupted, Retry on the opening message continues it without restoring later demotions or removals. If setup expires, - start a new chat. Solo conversations continue at the chat's top + choose **Abandon admin setup** in Outbox to keep the chat and current roles, + then retry the message; or start a new chat for automatic Admin setup. Solo conversations continue at the chat's top level rather than requiring a new thread for each reply. Where available, use **Model and effort** in the composer before sending; Solo keeps those choices for that chat until you reset them in the same control, even if its available diff --git a/docs/solo/README.md b/docs/solo/README.md index f869936a43..f54baa6082 100644 --- a/docs/solo/README.md +++ b/docs/solo/README.md @@ -109,8 +109,11 @@ behavior on the label, so a rename touches copy only. The create's local Outbox receipt retains the opening recipients across interruptions; retries reconstruct the same grants and confirm their recorded IDs before sending. A recorded grant stays complete - after a later demotion or removal. Expired, unrecorded grants require a new - chat; recovery never changes a command's timestamp. This needs no relay update + after a later demotion or removal. Expired, unrecorded grants are never re-dated. + Outbox offers **Abandon admin setup** for the expired, delivered create: explicit + abandonment retires its recovery receipt while keeping the chat and granted + roles. It sends no message automatically; the user retries with current roles + or starts a new chat for automatic Admin setup. This needs no relay update and does not migrate existing members' roles or change tool-created grants. - The Buzz tools' `channel_create` with `solo` sends the same create for any caller, including the standalone stdio server: signed by the caller, with the diff --git a/src/bundled/channels/OutboxStatus.test.tsx b/src/bundled/channels/OutboxStatus.test.tsx index 2644910a5f..b93ca5277d 100644 --- a/src/bundled/channels/OutboxStatus.test.tsx +++ b/src/bundled/channels/OutboxStatus.test.tsx @@ -1,4 +1,5 @@ // @vitest-environment jsdom +import { soloAdminRecovery } from "../../features/relay/solo-admins"; import "@testing-library/jest-dom/vitest"; import { afterEach, assert, expect, it, vi } from "vitest"; import { @@ -525,3 +526,154 @@ it.each(["agent", "team", "solo", "agent-share"] as const)( } }, ); + +it("abandons expired admin setup durably through Outbox and releases the chat gate", async () => { + const viewer = keypair(), + relay = keypair(), + agent = keypair(); + const channel = crypto.randomUUID(); + const creation = signed(viewer, { + kind: 9007, + created_at: Math.floor(Date.now() / 1000) - 16 * 60, + content: "", + tags: [ + ["h", channel], + ["p", agent.pubkey], + ], + }); + let records: readonly OutgoingEvent[] = [ + { + event: eventDto(creation), + signed: creation, + delivery: "accepted", + recovery: soloAdminRecovery(channel, [agent.pubkey], [agent.pubkey]), + }, + ]; + const events = new Map([[creation.id, creation]]); + const now = Date.now(); + const clock = vi + .spyOn(Date, "now") + .mockReturnValue((creation.created_at + 14 * 60) * 1000); + let failRemoval = false; + const storage = { + load: () => structuredClone(records), + save: (next: readonly OutgoingEvent[]) => { + if (failRemoval && !next.some((item) => item.recovery)) + throw new Error("Storage unavailable"); + records = structuredClone(next); + }, + }; + const adminSign = vi.fn(async (template) => + signed(viewer, template), + ); + const publish = vi.fn(async (event: RelayEvent) => { + events.set(event.id, event); + }); + const open = () => + createRelaySession( + { + viewer: viewer.pubkey, + relayAuthor: relay.pubkey, + channelIdentity: true, + media: () => undefined, + query: async (filters) => + [ + ...events.values(), + metadata(relay, channel, "Work", creation.created_at, [ + ["t", "stream"], + ["t", "buzz.solo"], + ["private"], + ["P", viewer.pubkey], + ]), + signed(relay, { + kind: 39002, + content: "", + tags: [ + ["d", channel], + ["p", viewer.pubkey, "", "owner"], + ["p", agent.pubkey, "", "member"], + ], + }), + ].filter((event) => + filters.some((filter) => matchesEvent(event, filter)), + ), + writer: { + kinds: [9, 9007], + sign: async (template) => signed(viewer, template), + publish, + }, + memberAdministration: { sign: adminSign, publish }, + }, + { outboxStorage: storage }, + ); + const first = open(); + let resumed: ReturnType | undefined; + try { + const session = first.session; + const outbox = session.outbox; + assert.exists(outbox); + await outbox.ready(); + session.channels.ensureList(); + await vi.waitFor(() => + expect(session.channels.list().status).toBe("ready"), + ); + const view = render( + , + ); + fireEvent.click(screen.getByText("Outbox · 1 items")); + clock.mockReturnValue(now); + await expect(session.channelWrites.prepareOpening(channel)).rejects.toThrow( + "expired", + ); + fireEvent.click(screen.getByRole("button", { name: "Remove from outbox" })); + await screen.findByRole("button", { name: "Abandon admin setup" }); + expect(outbox.snapshot().some((item) => item.recovery)).toBe(true); + expect( + screen.getByText(/Retry your message to continue with the current roles/), + ).toBeVisible(); + const remove = () => + screen.getByRole("button", { name: "Abandon admin setup" }); + failRemoval = true; + fireEvent.click(remove()); + expect(await screen.findByRole("alert")).toHaveTextContent( + "Storage unavailable", + ); + expect(outbox.snapshot().some((item) => item.recovery)).toBe(true); + await expect(session.channelWrites.prepareOpening(channel)).rejects.toThrow( + "expired", + ); + failRemoval = false; + fireEvent.click(remove()); + await waitFor(() => expect(outbox.snapshot()).toHaveLength(0)); + expect(records.some((item) => item.recovery)).toBe(false); + expect(session.channels.get?.(channel)?.members).toContain(agent.pubkey); + view.unmount(); + const sent = session.messages.send( + channel, + "Continue with the current roles", + [agent.pubkey], + ); + await vi.waitFor(() => expect(events.has(sent)).toBe(true)); + first.dispose(); + resumed = open(); + await resumed.session.outbox?.ready(); + resumed.session.channels.ensureList(); + await vi.waitFor(() => + expect(resumed?.session.channels.list().status).toBe("ready"), + ); + const next = resumed.session.messages.send(channel, "After restart", [ + agent.pubkey, + ]); + await vi.waitFor(() => expect(events.has(next)).toBe(true)); + expect(adminSign).not.toHaveBeenCalled(); + expect(publish.mock.calls.every(([event]) => event.kind === 9)).toBe(true); + } finally { + first.dispose(); + resumed?.dispose(); + clock.mockRestore(); + } +}); diff --git a/src/bundled/channels/OutboxStatus.tsx b/src/bundled/channels/OutboxStatus.tsx index 8d70565478..edd1d823da 100644 --- a/src/bundled/channels/OutboxStatus.tsx +++ b/src/bundled/channels/OutboxStatus.tsx @@ -7,6 +7,7 @@ import { PRODUCT_FEEDBACK_KIND } from "../../features/relay/product-feedback"; import { HELD_RETRY_REFUSED, type Outbox } from "../../features/relay/outbox"; import type { RelaySession } from "../../features/relay/session"; import { isBatchAddition } from "../../features/channel-members/members"; +import { isExpiredSoloAdminSetup } from "../../features/relay/solo-admins"; /** A batch names everyone its Retry re-adds. */ function additionLabel(tags: readonly (readonly string[])[]) { @@ -30,7 +31,9 @@ export function OutboxStatus({ outbox.subscribe, outbox.snapshot, outbox.snapshot, - ).filter((item) => item.event.kind !== PRODUCT_FEEDBACK_KIND); + ) + .filter((item) => item.event.kind !== PRODUCT_FEEDBACK_KIND) + .map((item) => ({ ...item, abandonSetup: isExpiredSoloAdminSetup(item) })); const [error, setError] = useState(); return ( @@ -47,9 +50,11 @@ export function OutboxStatus({ {operations.map((item) => (
  • - {item.event.kind === 9000 - ? additionLabel(item.event.tags) - : item.event.content.slice(0, 100)}{" "} + {item.abandonSetup + ? "Opening agent admin setup" + : item.event.kind === 9000 + ? additionLabel(item.event.tags) + : item.event.content.slice(0, 100)}{" "} ·{" "} { { @@ -131,11 +136,25 @@ export function OutboxStatus({ (item.delivery === "failed" || item.delivery === "unknown") && ( {HELD_RETRY_REFUSED} )}{" "} + {item.abandonSetup && ( + + Admin setup expired. Abandoning keeps this chat and any roles + already granted. Retry your message to continue with the current + roles. + + )}{" "} {item.delivery !== "sending" && ( )}
  • diff --git a/src/features/relay/channel-writes.ts b/src/features/relay/channel-writes.ts index 56ff5a89a6..801bc32da5 100644 --- a/src/features/relay/channel-writes.ts +++ b/src/features/relay/channel-writes.ts @@ -562,19 +562,30 @@ export function createChannelWrites( const source = writer(); if (!adminWriter || !relayAuthor) throw new Error("This connection cannot set up chat admins."); - await created(pending.event.id); - const saved = await source.recovery(soloAdminKey(id)); - // An explicit dismissal in another window retires this setup too. - if (!saved) return; - await promoteSoloAdmins( - saved, - adminWriter, - discovery, - relayAuthor, - signal, - ); - signal.throwIfAborted(); - await source.dismiss(saved.event.id, saved.recovery); + const abandoned = new AbortController(); + const stop = source.observeDismiss((item) => { + if (item.event.id === pending.event.id) + abandoned.abort( + new DOMException("Chat admin setup was abandoned", "AbortError"), + ); + }); + try { + await created(pending.event.id); + const saved = await source.recovery(soloAdminKey(id)); + // An explicit dismissal in another window retires this setup too. + if (!saved) return; + await promoteSoloAdmins( + saved, + adminWriter, + discovery, + relayAuthor, + AbortSignal.any([signal, abandoned.signal]), + ); + signal.throwIfAborted(); + await source.dismiss(saved.event.id, saved.recovery); + } finally { + stop(); + } })(); adminSetups.set(id, work); void work.catch(() => {}).finally(() => adminSetups.delete(id)); diff --git a/src/features/relay/solo-admins.integration.test.ts b/src/features/relay/solo-admins.integration.test.ts index 8395617a21..ef40bf8456 100644 --- a/src/features/relay/solo-admins.integration.test.ts +++ b/src/features/relay/solo-admins.integration.test.ts @@ -129,6 +129,7 @@ function setup() { events, genericPublish, adminPublish, + transport, open, start, }; @@ -239,3 +240,61 @@ it("resumes a partial setup from the durable outbox after restart without restor h.genericPublish.mock.calls.filter(([event]) => event.kind === 9), ).toHaveLength(1); }); + +it("abandons expired setup while signing is held without granting or releasing its message", async () => { + const h = setup(); + const sign = h.transport.memberAdministration.sign; + let release = () => {}; + let started = () => {}; + const held = new Promise((resolve) => { + release = resolve; + }); + const signing = new Promise((resolve) => { + started = resolve; + }); + h.transport.memberAdministration.sign = async (template) => { + started(); + await held; + return sign(template); + }; + const owner = await h.open(); + const clock = vi.spyOn(Date, "now"); + try { + const { message } = h.start(owner); + await signing; + const outbox = owner.session.outbox; + assert.exists(outbox); + const receipt = outbox + .snapshot() + .find((item) => item.recovery?.key === soloAdminKey(h.channel)); + assert.exists(receipt); + const active = owner.session.channelWrites.prepareOpening(h.channel); + assert.exists(active); + const outcome = active.then( + () => undefined, + (error: unknown) => error, + ); + clock.mockReturnValue(Date.now() + 16 * 60 * 1000); + await outbox.dismiss(receipt.event.id, receipt.recovery); + release(); + const error = await outcome; + expect(h.adminPublish).not.toHaveBeenCalled(); + expect(error).toBeInstanceOf(Error); + expect(h.agents.map((key) => h.roles.get(key))).toEqual([ + "member", + "member", + ]); + expect(h.events.has(message)).toBe(false); + await vi.waitFor(() => + expect( + outbox.snapshot().find((item) => item.event.id === message)?.delivery, + ).toBe("failed"), + ); + outbox.retry(message); + await vi.waitFor(() => expect(h.events.has(message)).toBe(true)); + expect(h.adminPublish).not.toHaveBeenCalled(); + } finally { + release(); + clock.mockRestore(); + } +}); diff --git a/src/features/relay/solo-admins.test.ts b/src/features/relay/solo-admins.test.ts index d3e12f5d30..4579b9c6d0 100644 --- a/src/features/relay/solo-admins.test.ts +++ b/src/features/relay/solo-admins.test.ts @@ -1,5 +1,9 @@ import { assert, expect, it, vi } from "vitest"; -import { promoteSoloAdmins, soloAdminRecovery } from "./solo-admins"; +import { + isExpiredSoloAdminSetup, + promoteSoloAdmins, + soloAdminRecovery, +} from "./solo-admins"; import { keypair, signed } from "./testing"; import { matchesEvent } from "./projection"; import type { OutgoingEvent } from "./outbox"; @@ -128,3 +132,42 @@ it("rejects recovery that grants a nonmember admin, without signing", async () = ).rejects.toThrow("initial chat agents"); expect(h.writer.sign).not.toHaveBeenCalled(); }); + +it("limits abandonment to a valid delivered and expired opening-admin receipt", () => { + const h = setup(); + const recovery = h.creation.recovery; + const createdAt = h.creation.event.created_at; + assert.exists(recovery); + assert.exists(createdAt); + const clock = vi + .spyOn(Date, "now") + .mockReturnValue(Date.now() + 16 * 60 * 1000); + try { + expect(isExpiredSoloAdminSetup(h.creation)).toBe(true); + for (const item of [ + { ...h.creation, delivery: "unknown" as const }, + { ...h.creation, recovery: undefined }, + { + ...h.creation, + recovery: { key: "another-owner", value: recovery.value }, + }, + { + ...h.creation, + recovery: { key: recovery.key, value: "invalid JSON" }, + }, + { + ...h.creation, + recovery: { + key: recovery.key, + value: JSON.stringify([keypair().pubkey]), + }, + }, + { ...h.creation, event: { ...h.creation.event, kind: 9000 } }, + ]) + expect(isExpiredSoloAdminSetup(item)).toBe(false); + clock.mockReturnValue((createdAt + 14 * 60) * 1000); + expect(isExpiredSoloAdminSetup(h.creation)).toBe(false); + } finally { + clock.mockRestore(); + } +}); diff --git a/src/features/relay/solo-admins.ts b/src/features/relay/solo-admins.ts index fe301b3e99..9238f6d6ae 100644 --- a/src/features/relay/solo-admins.ts +++ b/src/features/relay/solo-admins.ts @@ -23,6 +23,36 @@ export function soloAdminRecovery( return { key: soloAdminKey(channel), value: JSON.stringify(unique) }; } +/** Only explicit abandonment of a delivered, expired setup may waive its gate. + * No unrecorded grant can start after this deadline; recorded roles stay put. */ +export function isExpiredSoloAdminSetup(item: OutgoingEvent): boolean { + const create = item.event; + const channel = create.tags.find(([tag]) => tag === "h")?.[1]; + if ( + create.kind !== 9007 || + !channel || + !["accepted", "seen"].includes(item.delivery) || + item.recovery?.key !== soloAdminKey(channel) || + !(Date.now() / 1000 - (create.created_at ?? Infinity) >= 15 * 60) + ) + return false; + try { + const admins: unknown = JSON.parse(item.recovery.value); + return ( + Array.isArray(admins) && + admins.length > 0 && + admins.every((key) => typeof key === "string" && key !== create.pubkey) && + soloAdminRecovery( + channel, + create.tags.flatMap(([tag, key]) => (tag === "p" && key ? [key] : [])), + admins, + )?.value === item.recovery.value + ); + } catch { + return false; + } +} + /** Reconstruct the exact same promotions after interruption. Their timestamp * and channel come from the saved create, so retries never invent a new grant * that could undo a later demotion or removal. */ @@ -78,7 +108,9 @@ export async function promoteSoloAdmins( // A recorded grant remains complete even when its recipient was demoted. if (await recorded()) continue; if (Date.now() / 1000 - create.created_at >= 15 * 60) - throw new Error("Chat admin setup expired. Start a new chat to retry."); + throw new Error( + "Chat admin setup expired. Abandon setup in Outbox to continue with current roles, or start a new chat.", + ); const rosters = await read([ { kinds: [39002], From aae5daba11ba7f4b7e2b7ee4c77d9bd1fade0194 Mon Sep 17 00:00:00 2001 From: Taylor Ho Date: Mon, 16 Nov 2026 18:18:55 -0800 Subject: [PATCH 09/17] fix(outbox): preserve expired messages when continuing a chat Require a new explicit Send after setup abandonment. Cover timestamp rejection of the exact expired event without changing it, then user-initiated delivery with current roles. Co-authored-by: Carl Signed-off-by: Taylor Ho --- docs/buzz-help.md | 2 +- docs/solo/README.md | 2 +- src/bundled/channels/OutboxStatus.test.tsx | 2 +- src/bundled/channels/OutboxStatus.tsx | 2 +- .../relay/solo-admins.integration.test.ts | 34 +++++++++++++++++-- 5 files changed, 36 insertions(+), 6 deletions(-) diff --git a/docs/buzz-help.md b/docs/buzz-help.md index 6dc9c13b4b..597c5a1d8e 100644 --- a/docs/buzz-help.md +++ b/docs/buzz-help.md @@ -428,7 +428,7 @@ and are asked to sign in again in Buzz. If admin setup is interrupted, Retry on the opening message continues it without restoring later demotions or removals. If setup expires, choose **Abandon admin setup** in Outbox to keep the chat and current roles, - then retry the message; or start a new chat for automatic Admin setup. Solo conversations continue at the chat's top + then send a new message; or start a new chat for automatic Admin setup. Solo conversations continue at the chat's top level rather than requiring a new thread for each reply. Where available, use **Model and effort** in the composer before sending; Solo keeps those choices for that chat until you reset them in the same control, even if its available diff --git a/docs/solo/README.md b/docs/solo/README.md index f54baa6082..a919b38fbf 100644 --- a/docs/solo/README.md +++ b/docs/solo/README.md @@ -112,7 +112,7 @@ behavior on the label, so a rename touches copy only. after a later demotion or removal. Expired, unrecorded grants are never re-dated. Outbox offers **Abandon admin setup** for the expired, delivered create: explicit abandonment retires its recovery receipt while keeping the chat and granted - roles. It sends no message automatically; the user retries with current roles + roles. It sends no message automatically; the user sends a new message with current roles or starts a new chat for automatic Admin setup. This needs no relay update and does not migrate existing members' roles or change tool-created grants. - The Buzz tools' `channel_create` with `solo` sends the same create for any diff --git a/src/bundled/channels/OutboxStatus.test.tsx b/src/bundled/channels/OutboxStatus.test.tsx index b93ca5277d..d9ddd16508 100644 --- a/src/bundled/channels/OutboxStatus.test.tsx +++ b/src/bundled/channels/OutboxStatus.test.tsx @@ -633,7 +633,7 @@ it("abandons expired admin setup durably through Outbox and releases the chat ga await screen.findByRole("button", { name: "Abandon admin setup" }); expect(outbox.snapshot().some((item) => item.recovery)).toBe(true); expect( - screen.getByText(/Retry your message to continue with the current roles/), + screen.getByText(/Send a new message to continue with the current roles/), ).toBeVisible(); const remove = () => screen.getByRole("button", { name: "Abandon admin setup" }); diff --git a/src/bundled/channels/OutboxStatus.tsx b/src/bundled/channels/OutboxStatus.tsx index edd1d823da..5118efb431 100644 --- a/src/bundled/channels/OutboxStatus.tsx +++ b/src/bundled/channels/OutboxStatus.tsx @@ -139,7 +139,7 @@ export function OutboxStatus({ {item.abandonSetup && ( Admin setup expired. Abandoning keeps this chat and any roles - already granted. Retry your message to continue with the current + already granted. Send a new message to continue with the current roles. )}{" "} diff --git a/src/features/relay/solo-admins.integration.test.ts b/src/features/relay/solo-admins.integration.test.ts index ef40bf8456..73249e192a 100644 --- a/src/features/relay/solo-admins.integration.test.ts +++ b/src/features/relay/solo-admins.integration.test.ts @@ -5,7 +5,7 @@ import { matchesEvent } from "./projection"; import { SOLO_LABEL } from "../solo/labels"; import { soloAdminKey } from "./solo-admins"; import { validateMemberAdministrationTemplate } from "../channel-members/administration-protocol"; -import type { OutgoingEvent } from "./outbox"; +import { PublishRejected, type OutgoingEvent } from "./outbox"; import type { ReadFilter, RelayEvent } from "./events"; import type { EventTemplate } from "nostr-tools"; @@ -290,8 +290,38 @@ it("abandons expired setup while signing is held without granting or releasing i outbox.snapshot().find((item) => item.event.id === message)?.delivery, ).toBe("failed"), ); + const oldMessage = outbox + .snapshot() + .find((item) => item.event.id === message); + assert.exists(oldMessage); + assert.exists(oldMessage.event.created_at); + expect(oldMessage.event.created_at).toBeLessThan( + Date.now() / 1000 - 15 * 60, + ); + // Model the relay's timestamp rejection: Retry preserves the old event. + h.genericPublish.mockRejectedValueOnce( + new PublishRejected("Event too old"), + ); outbox.retry(message); - await vi.waitFor(() => expect(h.events.has(message)).toBe(true)); + await vi.waitFor(() => + expect( + outbox.snapshot().find((item) => item.event.id === message), + ).toMatchObject({ + delivery: "failed", + error: "Event too old", + }), + ); + expect(h.genericPublish.mock.lastCall?.[0]).toEqual(oldMessage.signed); + const fresh = owner.session.messages.send( + h.channel, + "Continue with current roles", + h.agents, + ); + await vi.waitFor(() => expect(h.events.has(fresh)).toBe(true)); + expect(h.events.has(message)).toBe(false); + expect( + outbox.snapshot().find((item) => item.event.id === message)?.event, + ).toEqual(oldMessage.event); expect(h.adminPublish).not.toHaveBeenCalled(); } finally { release(); From 752ceaa21769d70f229a5c9771f89cfad8c6f127 Mon Sep 17 00:00:00 2001 From: Taylor Ho Date: Mon, 16 Nov 2026 18:58:30 -0800 Subject: [PATCH 10/17] fix(outbox): fence admin setup publication across windows Serialize exact durable setup ownership with dismissal through grant publication and final retirement. Sign outside the lock, preserve recovery after failed storage, and discard stale local ownership before another save can reclaim it. Co-authored-by: Carl Signed-off-by: Taylor Ho --- docs/buzz-help.md | 8 +- docs/solo/README.md | 4 +- src/features/relay/channel-writes.ts | 48 ++-- src/features/relay/outbox-recovery.test.ts | 113 ++++++++++ src/features/relay/outbox.ts | 63 +++++- tests/browser/fixture.mjs | 25 +++ tests/browser/solo-admin-abandonment.spec.mjs | 210 ++++++++++++++++++ 7 files changed, 442 insertions(+), 29 deletions(-) create mode 100644 tests/browser/solo-admin-abandonment.spec.mjs diff --git a/docs/buzz-help.md b/docs/buzz-help.md index 597c5a1d8e..e5b736416f 100644 --- a/docs/buzz-help.md +++ b/docs/buzz-help.md @@ -427,9 +427,11 @@ and are asked to sign in again in Buzz. keep ordinary participation, and existing members keep their saved roles. If admin setup is interrupted, Retry on the opening message continues it without restoring later demotions or removals. If setup expires, - choose **Abandon admin setup** in Outbox to keep the chat and current roles, - then send a new message; or start a new chat for automatic Admin setup. Solo conversations continue at the chat's top - level rather than requiring a new thread for each reply. Where available, use + choose **Abandon admin setup** in Outbox to keep the chat and current roles. + This stops unfinished setup in other windows too; it does not undo grants + already accepted by the relay. You can send a new message, or start a new chat + for automatic Admin setup. Solo conversations continue at the chat's top level + rather than requiring a new thread for each reply. Where available, use **Model and effort** in the composer before sending; Solo keeps those choices for that chat until you reset them in the same control, even if its available models change. If a loaded catalog no longer offers a saved choice, the diff --git a/docs/solo/README.md b/docs/solo/README.md index a919b38fbf..9b0084780c 100644 --- a/docs/solo/README.md +++ b/docs/solo/README.md @@ -112,7 +112,9 @@ behavior on the label, so a rename touches copy only. after a later demotion or removal. Expired, unrecorded grants are never re-dated. Outbox offers **Abandon admin setup** for the expired, delivered create: explicit abandonment retires its recovery receipt while keeping the chat and granted - roles. It sends no message automatically; the user sends a new message with current roles + roles. Grant publication and retirement share the receipt’s durable ownership + lock, so another window’s unfinished signature cannot publish after abandonment. + It sends no message automatically; the user sends a new message with current roles or starts a new chat for automatic Admin setup. This needs no relay update and does not migrate existing members' roles or change tool-created grants. - The Buzz tools' `channel_create` with `solo` sends the same create for any diff --git a/src/features/relay/channel-writes.ts b/src/features/relay/channel-writes.ts index 801bc32da5..990c9ab07c 100644 --- a/src/features/relay/channel-writes.ts +++ b/src/features/relay/channel-writes.ts @@ -560,32 +560,32 @@ export function createChannelWrites( if (active) return active; const work = (async () => { const source = writer(); - if (!adminWriter || !relayAuthor) + const withRecovery = source.withRecovery; + const finishRecovery = source.finishRecovery; + if (!adminWriter || !relayAuthor || !withRecovery || !finishRecovery) throw new Error("This connection cannot set up chat admins."); - const abandoned = new AbortController(); - const stop = source.observeDismiss((item) => { - if (item.event.id === pending.event.id) - abandoned.abort( - new DOMException("Chat admin setup was abandoned", "AbortError"), - ); - }); - try { - await created(pending.event.id); - const saved = await source.recovery(soloAdminKey(id)); - // An explicit dismissal in another window retires this setup too. - if (!saved) return; - await promoteSoloAdmins( - saved, - adminWriter, - discovery, - relayAuthor, - AbortSignal.any([signal, abandoned.signal]), + await created(pending.event.id); + const saved = await source.recovery(soloAdminKey(id)); + if (!saved?.recovery) + throw new Error( + "Chat admin setup was abandoned. Send a new message to continue.", ); - signal.throwIfAborted(); - await source.dismiss(saved.event.id, saved.recovery); - } finally { - stop(); - } + const recovery = saved.recovery; + await promoteSoloAdmins( + saved, + { + ...adminWriter, + publish: (event, signal) => + withRecovery(saved.event.id, recovery, () => + adminWriter.publish(event, signal), + ), + }, + discovery, + relayAuthor, + signal, + ); + signal.throwIfAborted(); + await finishRecovery(saved.event.id, recovery); })(); adminSetups.set(id, work); void work.catch(() => {}).finally(() => adminSetups.delete(id)); diff --git a/src/features/relay/outbox-recovery.test.ts b/src/features/relay/outbox-recovery.test.ts index 07a5f720ea..ac47c8226f 100644 --- a/src/features/relay/outbox-recovery.test.ts +++ b/src/features/relay/outbox-recovery.test.ts @@ -803,3 +803,116 @@ it("does not expose replacement intent to an earlier queued save", async () => { ).toBe(true); } }); + +it("fences a fresh local recovery against another owner's durable dismissal", async () => { + const store = memory(); + const a = setup(store); + await a.outbox.ready(); + const id = a.outbox.send({ ...input, kind: 9007 }, recovery); + await vi.waitFor(() => expect(store.load()[0]?.delivery).toBe("accepted")); + const b = setup(store); + await b.outbox.ready(); + await b.outbox.dismiss(id, recovery); + const publish = vi.fn(async () => {}); + assert.exists(a.outbox.withRecovery); + await expect(a.outbox.withRecovery(id, recovery, publish)).rejects.toThrow( + "removed or changed", + ); + expect(publish).not.toHaveBeenCalled(); + expect(await a.outbox.recovery(recovery.key)).toBeUndefined(); + expect(a.outbox.snapshot()).toEqual([]); + a.outbox.send({ ...input, content: "New explicit Send" }); + await vi.waitFor(() => expect(a.publish).toHaveBeenCalledTimes(2)); + expect(store.load().some((item) => item.event.id === id)).toBe(false); +}); + +it("holds shared recovery ownership through publication before dismissal can commit", async () => { + const store = memory(); + const event = signed(viewer, { ...input, kind: 9007 }); + store.save([{ event, signed: event, delivery: "accepted", recovery }]); + let tail = Promise.resolve(); + let requests = 0; + const queued = gate(); + const shared: OutboxStorage = { + ...store, + async lock(id, run) { + expect(id).toBe(event.id); + const before = tail; + const next = gate(); + tail = next.promise; + if (++requests === 2) queued.release(); + await before; + try { + return await run(); + } finally { + next.release(); + } + }, + }; + const a = setup(shared), + b = setup(shared); + await Promise.all([a.outbox.ready(), b.outbox.ready()]); + const entered = gate(), + release = gate(); + const order: string[] = []; + assert.exists(a.outbox.withRecovery); + try { + const publication = a.outbox.withRecovery(event.id, recovery, async () => { + entered.release(); + await release.promise; + order.push("published"); + }); + await entered.promise; + const dismissal = b.outbox.dismiss(event.id, recovery).then(() => { + order.push("dismissed"); + }); + await queued.promise; + expect(order).toEqual([]); + expect(store.load()).toHaveLength(1); + release.release(); + await Promise.all([publication, dismissal]); + expect(order).toEqual(["published", "dismissed"]); + expect(store.load()).toEqual([]); + await expect(a.outbox.dismiss(event.id, recovery)).rejects.toThrow( + "removed or changed", + ); + } finally { + release.release(); + } +}); + +it("does not release dependent work by joining a pending abandonment", async () => { + const store = memory(); + const event = signed(viewer, { ...input, kind: 9007 }); + store.save([{ event, signed: event, delivery: "seen", recovery }]); + const deleting = gate(), + release = gate(); + const h = setup({ + ...store, + async save(records) { + if (!records.length) { + deleting.release(); + await release.promise; + } + store.save(records); + }, + }); + await h.outbox.ready(); + assert.exists(h.outbox.finishRecovery); + const deliver = vi.fn(); + try { + const abandonment = h.outbox.dismiss(event.id, recovery); + await deleting.promise; + const completion = h.outbox + .finishRecovery(event.id, recovery) + .then(deliver); + const refused = expect(completion).rejects.toThrow("removed or changed"); + release.release(); + await abandonment; + await refused; + expect(deliver).not.toHaveBeenCalled(); + expect(store.load()).toEqual([]); + } finally { + release.release(); + } +}); diff --git a/src/features/relay/outbox.ts b/src/features/relay/outbox.ts index d7c8bd6f6e..c5e28f3ace 100644 --- a/src/features/relay/outbox.ts +++ b/src/features/relay/outbox.ts @@ -70,6 +70,16 @@ export interface Outbox { ready(): Promise; /** Fresh shared-journal ownership without importing another window's operations. */ recovery(key: string): Promise; + /** Verify the exact durable receipt and retain its dismissal lock through + * dependent publication. Signing must happen before acquiring this lock. + * Older Outboxes may omit this; dependent publication must fail closed. */ + withRecovery?( + id: string, + recovery: OutboxRecovery, + run: () => Promise, + ): Promise; + /** Complete under exact ownership, without joining an independent dismissal. */ + finishRecovery?(id: string, recovery: OutboxRecovery): Promise; send( input: OutboxInput, recovery?: OutboxRecovery, @@ -338,6 +348,17 @@ export function createOutbox( let storageError: string | undefined; let hydrated = false; let durable = Promise.resolve(); + let ownership = Promise.resolve(); + function locked(id: string, run: () => Promise): Promise { + if (storage.lock) return storage.lock(id, run); + // Memory/single-window stores still serialize publication with dismissal. + const work = ownership.then(run, run); + ownership = work.then( + () => {}, + () => {}, + ); + return work; + } const notify = () => { visible = Object.freeze([ ...completed.entries().map(([, item]) => item), @@ -911,6 +932,38 @@ export function createOutbox( else schedule(event.id, intent); return { id: event.id, persisted: intent }; } + async function withRecovery( + id: string, + recovery: OutboxRecovery, + run: () => Promise, + ): Promise { + await outbox.ready(); + await durable.catch(() => {}); + await locked(id, async () => { + const shared = (await storage.load({ readOnly: true })).find( + (item) => item.event.id === id, + ); + if (closed) throw abortError(); + if ( + shared?.recovery?.key !== recovery.key || + shared.recovery.value !== recovery.value + ) { + // This includes fresh local receipts: they cannot reclaim a durable + // dismissal through a later unrelated journal save. + storage.forget?.(id); + restoredReceipts.delete(id); + completed.delete(id); + snapshot = Object.freeze( + snapshot.filter((item) => item.event.id !== id), + ); + notify(); + throw new Error( + "This operation was removed or changed in another window. Send a new message to continue.", + ); + } + await run(); + }); + } const outbox: Outbox = Object.freeze({ snapshot: () => finalSnapshot ?? snapshot, subscribe: (listener: () => void) => subscribe(listeners, listener), @@ -943,6 +996,12 @@ export function createOutbox( } return shared; }, + withRecovery, + async finishRecovery(id: string, recovery: OutboxRecovery) { + await withRecovery(id, recovery, () => persist(id, "dismiss")); + admissionGates.delete(id); + sendHolds.delete(id); + }, async recover(id: string, recovery: OutboxRecovery, consume?: () => void) { const adopt = async () => { await outbox.ready(); @@ -1159,7 +1218,9 @@ export function createOutbox( ), ); const remove = () => persist(id, "dismiss"); - const work = (storage.lock ? storage.lock(id, remove) : remove()) + const work = ( + owner ? withRecovery(id, owner, remove) : locked(id, remove) + ) .then(() => { admissionGates.delete(id); sendHolds.delete(id); diff --git a/tests/browser/fixture.mjs b/tests/browser/fixture.mjs index 73fe7aaef6..930a208a51 100644 --- a/tests/browser/fixture.mjs +++ b/tests/browser/fixture.mjs @@ -34,6 +34,7 @@ export const historySize = 640; // broker/subscriber and model only the upstream relay policy with ephemeral keys. export const test = base.extend({ productionBroker: [false, { option: true }], + openingAdminSetup: [false, { option: true }], enabledPlugins: [[], { option: true }], builderlab: [{}, { option: true }], /** The production broker's live setup deadline. It runs in Node, so the @@ -133,6 +134,7 @@ export const test = base.extend({ browserName, browser, productionBroker, + openingAdminSetup, enabledPlugins, builderlab, liveSetupTimeoutMs, @@ -1082,6 +1084,17 @@ export const test = base.extend({ .map((entry) => entry.event); }; const answer = (community, filter) => { + if (openingAdminSetup && (filter.ids || filter.kinds?.includes(9007))) + return [ + report.setupCreation, + ...report.publications.map((item) => item.event), + ].filter( + (event) => + event && + (filter.ids + ? filter.ids.includes(event.id) + : filter.kinds.includes(event.kind)), + ); // These ordinary fixture channels have no Huddle creation receipt. if (filter.kinds?.length === 1 && filter.kinds[0] === 9007) return []; // The real relay can return both current metadata and rosters in one query. @@ -2166,6 +2179,17 @@ export const test = base.extend({ return acceptReadPublication(community, event); if (event.kind === 30078 || event.kind === 20002) return acceptReadPublication(community, event); + if (openingAdminSetup && [9000, 9].includes(event.kind)) { + // This receiver's clock is independently controlled by the journey. + expect( + Math.abs(report.setupReceiverTime - event.created_at), + ).toBeLessThanOrEqual(900); + if (event.kind === 9000) { + expect(event.tags).toContainEqual(["role", "admin"]); + report.publications.push({ community, event }); + return; + } + } expect([9, 7]).toContain(event.kind); const channel = event.tags.find(([k]) => k === "h")?.[1]; const history = histories.get(`${community}/${channel}`); @@ -2185,6 +2209,7 @@ export const test = base.extend({ : {}), discovery: (community) => ({ self: getPublicKey(relayKey), + ...(openingAdminSetup ? { supported_nips: [29] } : {}), // Solo details publications below retain label changes as well as names. ...(ownSoloChannels.length ? { supported_extensions: ["nip-cl"] } diff --git a/tests/browser/solo-admin-abandonment.spec.mjs b/tests/browser/solo-admin-abandonment.spec.mjs new file mode 100644 index 0000000000..a2380bb107 --- /dev/null +++ b/tests/browser/solo-admin-abandonment.spec.mjs @@ -0,0 +1,210 @@ +import { test, expect } from "./fixture.mjs"; +import { openPage } from "./navigation.mjs"; +import { openChannelDetails } from "./channel-details.mjs"; + +const channel = "11111111-1111-4111-8111-111111111111"; +const chat = "33333333-3333-4333-8333-333333333333"; +test.use({ + productionBroker: true, + openingAdminSetup: true, + channelLifecycle: true, + channelIds: [channel, chat], + channelNames: { [channel]: "Project updates", [chat]: "Recovery chat" }, + soloChannels: [chat], + ownSoloChannels: [chat], + soloAgentNames: ["Recovery agent"], + savedCommunities: ["primary"], + historyCounts: { [channel]: 0, [chat]: 0 }, +}); + +async function openOutbox(page, origin) { + await page.goto(origin); + await openPage(page, "Messages"); + await page + .getByRole("button", { name: "Project updates", exact: true }) + .click(); + await openChannelDetails(page); + const panel = page.getByRole("complementary", { + name: "Channel settings", + exact: true, + }); + await panel.getByText("Diagnostics", { exact: true }).click(); + const summary = panel.locator("summary").filter({ hasText: /^Outbox ·/ }); + await summary.click(); + return summary.locator(".."); +} + +// Browser-only: separate windows share the production IndexedDB journal and +// Web Locks while each has its own session, signing request and cancellation. +for (const mode of ["cross-window", "same-window", "failed-storage"]) + test(`expired setup abandonment fences held signing (${mode})`, async ({ + page, + context, + app, + }) => { + const createdAt = Math.floor(Date.now() / 1000); + const agent = app.soloAgents[0].pubkey; + const creation = app.sign({ + kind: 9007, + created_at: createdAt, + content: "", + tags: [ + ["h", chat], + ["p", agent], + ], + }); + const message = app.sign({ + kind: 9, + created_at: createdAt, + content: "Opening work", + tags: [ + ["h", chat], + ["p", agent], + ], + }); + const recovery = { + key: `solo-initial-admins:${chat}`, + value: JSON.stringify([agent]), + }; + app.report.setupCreation = creation; + const scope = `https://primary.example:${app.viewer}`; + app.report.setupReceiverTime = createdAt + 895; + await page.clock.setFixedTime(new Date((createdAt + 899) * 1000)); + await page.addInitScript( + ({ scope, creation, message, recovery }) => { + localStorage.setItem( + `buzz-outbox-v1:${scope}`, + JSON.stringify([ + { + event: creation, + signed: creation, + delivery: "accepted", + recovery, + }, + { event: message, signed: message, delivery: "failed" }, + ]), + ); + }, + { scope, creation, message, recovery }, + ); + let release = () => {}; + let signingStarted = false; + const held = new Promise((resolve) => { + release = resolve; + }); + await page.route("**/member-administration-sign", async (route) => { + const response = await route.fetch(); + expect(response.status()).toBe(200); + signingStarted = true; + await held; + await route.fulfill({ response }); + }); + let other; + try { + const a = await openOutbox(page, app.origin); + const row = a.getByRole("listitem").filter({ hasText: "Opening work" }); + await row.getByRole("button", { name: "Retry", exact: true }).click(); + await expect.poll(() => signingStarted).toBe(true); + await page.clock.setFixedTime(new Date((createdAt + 900) * 1000)); + other = mode === "same-window" ? page : await context.newPage(); + if (other !== page) { + app.watchPageErrors(other); + await other.clock.setFixedTime(new Date((createdAt + 900) * 1000)); + } + const b = other === page ? a : await openOutbox(other, app.origin); + if (mode === "same-window") { + // The view was opened before expiry: first click exposes explicit consent. + await b + .getByRole("button", { name: "Remove from outbox", exact: true }) + .first() + .click(); + } + if (mode === "failed-storage") + await other.evaluate( + ({ scope, id }) => { + const remove = IDBObjectStore.prototype.delete; + IDBObjectStore.prototype.delete = function (key) { + if (Array.isArray(key) && key[0] === scope && key[1] === id) { + IDBObjectStore.prototype.delete = remove; + this.transaction.abort(); + } + return remove.call(this, key); + }; + }, + { scope, id: creation.id }, + ); + await b + .getByRole("button", { name: "Abandon admin setup", exact: true }) + .click(); + if (mode === "failed-storage") + await expect(b.getByRole("alert")).toBeVisible(); + else + await expect( + b.getByRole("button", { name: "Abandon admin setup", exact: true }), + ).toHaveCount(0); + // Dismissal's UI completes only after the strict IndexedDB commit. + release(); + if (mode === "failed-storage") { + await expect + .poll( + () => + app.report.publications.filter(({ event }) => event.kind === 9) + .length, + ) + .toBe(1); + const grants = app.report.publications.filter( + ({ event }) => event.kind === 9000, + ); + expect(grants).toHaveLength(1); + expect(app.report.setupReceiverTime - grants[0].event.created_at).toBe( + 895, + ); + expect( + app.report.publications.find(({ event }) => event.kind === 9).event, + ).toEqual(message); + } else { + await expect(row).toContainText("Not sent"); + expect( + app.report.publications.filter(({ event }) => + [9000, 9].includes(event.kind), + ), + ).toEqual([]); + await expect( + row.getByRole("button", { name: "Retry", exact: true }), + ).toBeEnabled(); + if (mode === "cross-window") { + await other + .getByRole("button", { name: "Recovery chat", exact: true }) + .click(); + const composer = other.getByRole("textbox", { + name: "Message your agents", + exact: true, + }); + await composer.fill("Continue with current roles"); + await composer.press("Enter"); + await expect + .poll( + () => + app.report.publications.filter(({ event }) => event.kind === 9) + .length, + ) + .toBe(1); + expect( + app.report.publications.filter(({ event }) => event.kind === 9000), + ).toEqual([]); + const fresh = app.report.publications.find( + ({ event }) => event.kind === 9, + ).event; + expect(fresh.id).not.toBe(message.id); + expect(fresh.content).toBe("Continue with current roles"); + } + } + } finally { + release(); + await page.unrouteAll({ behavior: "wait" }); + if (other && other !== page) { + await other.unrouteAll({ behavior: "wait" }); + await other.close(); + } + } + }); From 3f27a6ed7dda9b3fbfe46052999d37a4eae3513f Mon Sep 17 00:00:00 2001 From: Taylor Ho Date: Mon, 16 Nov 2026 19:56:24 -0800 Subject: [PATCH 11/17] fix(outbox): make shared receipt dismissal idempotent Co-authored-by: Carl Signed-off-by: Taylor Ho --- src/features/relay/outbox-recovery.test.ts | 38 +++++++++++- src/features/relay/outbox.ts | 6 +- tests/browser/message-management.spec.mjs | 72 ++++++++++++++++++++++ 3 files changed, 112 insertions(+), 4 deletions(-) diff --git a/src/features/relay/outbox-recovery.test.ts b/src/features/relay/outbox-recovery.test.ts index ac47c8226f..9f47424b77 100644 --- a/src/features/relay/outbox-recovery.test.ts +++ b/src/features/relay/outbox-recovery.test.ts @@ -819,6 +819,10 @@ it("fences a fresh local recovery against another owner's durable dismissal", as "removed or changed", ); expect(publish).not.toHaveBeenCalled(); + assert.exists(a.outbox.finishRecovery); + await expect(a.outbox.finishRecovery(id, recovery)).rejects.toThrow( + "removed or changed", + ); expect(await a.outbox.recovery(recovery.key)).toBeUndefined(); expect(a.outbox.snapshot()).toEqual([]); a.outbox.send({ ...input, content: "New explicit Send" }); @@ -873,14 +877,42 @@ it("holds shared recovery ownership through publication before dismissal can com await Promise.all([publication, dismissal]); expect(order).toEqual(["published", "dismissed"]); expect(store.load()).toEqual([]); - await expect(a.outbox.dismiss(event.id, recovery)).rejects.toThrow( - "removed or changed", - ); + await expect(a.outbox.dismiss(event.id, recovery)).resolves.toBeUndefined(); + expect(a.outbox.snapshot()).toEqual([]); } finally { release.release(); } }); +it.each(["key", "value"] as const)( + "refuses dismissal, publication and completion after shared recovery %s changes", + async (field) => { + const store = memory(); + const event = signed(viewer, { ...input, kind: 9007 }); + store.save([{ event, signed: event, delivery: "accepted", recovery }]); + const h = setup(store); + await h.outbox.ready(); + const changed = { ...recovery, [field]: "different owner" }; + store.save([ + { event, signed: event, delivery: "accepted", recovery: changed }, + ]); + const publish = vi.fn(async () => {}); + assert.exists(h.outbox.withRecovery); + assert.exists(h.outbox.finishRecovery); + await expect(h.outbox.dismiss(event.id, recovery)).rejects.toThrow( + "removed or changed", + ); + await expect( + h.outbox.withRecovery(event.id, recovery, publish), + ).rejects.toThrow("removed or changed"); + await expect(h.outbox.finishRecovery(event.id, recovery)).rejects.toThrow( + "removed or changed", + ); + expect(publish).not.toHaveBeenCalled(); + expect(store.load()[0]?.recovery).toEqual(changed); + }, +); + it("does not release dependent work by joining a pending abandonment", async () => { const store = memory(); const event = signed(viewer, { ...input, kind: 9007 }); diff --git a/src/features/relay/outbox.ts b/src/features/relay/outbox.ts index c5e28f3ace..c84bdcb679 100644 --- a/src/features/relay/outbox.ts +++ b/src/features/relay/outbox.ts @@ -936,6 +936,7 @@ export function createOutbox( id: string, recovery: OutboxRecovery, run: () => Promise, + dismissAbsent = false, ): Promise { await outbox.ready(); await durable.catch(() => {}); @@ -957,6 +958,9 @@ export function createOutbox( snapshot.filter((item) => item.event.id !== id), ); notify(); + // Only dismissal is idempotent. Missing ownership must still fence + // dependent publication and successful recovery completion. + if (!shared && dismissAbsent) return; throw new Error( "This operation was removed or changed in another window. Send a new message to continue.", ); @@ -1219,7 +1223,7 @@ export function createOutbox( ); const remove = () => persist(id, "dismiss"); const work = ( - owner ? withRecovery(id, owner, remove) : locked(id, remove) + owner ? withRecovery(id, owner, remove, true) : locked(id, remove) ) .then(() => { admissionGates.delete(id); diff --git a/tests/browser/message-management.spec.mjs b/tests/browser/message-management.spec.mjs index 20684c32da..da371a0478 100644 --- a/tests/browser/message-management.spec.mjs +++ b/tests/browser/message-management.spec.mjs @@ -11,6 +11,78 @@ test.use({ historyCounts: { alpha: 2, beta: 1 }, }); +// Separate app windows retain their own row/confirmation while sharing the +// production IndexedDB receipt and Web Lock. A DOM emulator cannot prove this. +test("discarding an orphan already removed by another window closes confirmation", async ({ + page, + context, + app, +}, testInfo) => { + const message = app.sign({ + kind: 9, + created_at: Math.floor(Date.now() / 1000) - 3600, + content: "Orphaned follow-up", + tags: [["h", "alpha"]], + }); + await page.addInitScript( + ({ scope, message }) => { + localStorage.setItem( + `buzz-outbox-v1:${scope}`, + JSON.stringify([ + { + event: message, + signed: message, + delivery: "unknown", + recovery: { key: "follow-up:orphan", value: "orphan" }, + }, + ]), + ); + }, + { scope: `https://primary.example:${app.viewer}`, message }, + ); + const confirm = async (window) => { + await open(window, app); + const row = window.locator(`[data-message-id="${message.id}"]`); + await expect(row).toBeVisible(); + await hoverMessage(row); + await row.getByRole("button", { name: "More message actions" }).click(); + await window + .getByRole("menuitem", { name: "Remove from this device", exact: true }) + .click(); + return window.getByRole("alertdialog", { + name: "Remove message from this device?", + exact: true, + }); + }; + const a = await confirm(page); + const other = await context.newPage(); + app.watchPageErrors(other); + try { + const b = await confirm(other); + await b.getByRole("button", { name: "Remove", exact: true }).click(); + await expect(b).toHaveCount(0); + await expect(other.getByText(message.content, { exact: true })).toHaveCount( + 0, + ); + await expect(a).toBeVisible(); + await a.getByRole("button", { name: "Remove", exact: true }).click(); + await expect(a).toHaveCount(0); + await expect(page.getByText(message.content, { exact: true })).toHaveCount( + 0, + ); + expect( + app.report.publications.filter(({ event }) => + [5, 9].includes(event.kind), + ), + ).toEqual([]); + await page.screenshot({ + path: testInfo.outputPath("discarded-in-both-windows.png"), + }); + } finally { + await other.close(); + } +}); + // Real shared-row/portal integration, keyboard focus and responsive geometry; // failure, retry, identity and permission matrices stay in lower-layer tests. test("manage a channel message, peer unread state, and its thread", async ({ From 588d64dfe8e5d06a69a0900b75f5d1944656c626 Mon Sep 17 00:00:00 2001 From: Taylor Ho Date: Mon, 16 Nov 2026 20:58:48 -0800 Subject: [PATCH 12/17] fix(solo): grant automatic admin only to owned agents Apply verified profile ownership to initial members and new Solo additions. Include owned workspace defaults without addressing them in the opening message, and preserve recorded grants and exact signed invitation retries. Co-authored-by: Carl Signed-off-by: Taylor Ho --- docs/buzz-help.md | 11 ++- docs/solo/README.md | 14 +-- docs/solo/sharing.md | 7 +- .../channels/ChannelMembersDialog.test.tsx | 35 +++++-- .../channels/ChannelsPage.solo.test.tsx | 8 ++ src/features/relay/channel-writes.ts | 36 +++++-- .../relay/session-agent-admission.test.ts | 95 +++++++++++++++++-- src/features/relay/session.ts | 2 + .../relay/solo-admins.integration.test.ts | 22 +++-- src/features/relay/solo-admins.test.ts | 88 ++++++++++++++++- src/features/relay/solo-admins.ts | 37 ++++++++ src/features/relay/testing.ts | 26 ++++- src/features/solo/SoloDraft.test.tsx | 59 +++++++++++- src/features/solo/SoloDraft.tsx | 7 +- tests/browser/fixture.mjs | 23 +++-- tests/browser/solo-admin-abandonment.spec.mjs | 79 +++++++++++++++ 16 files changed, 496 insertions(+), 53 deletions(-) diff --git a/docs/buzz-help.md b/docs/buzz-help.md index e5b736416f..996d749532 100644 --- a/docs/buzz-help.md +++ b/docs/buzz-help.md @@ -420,11 +420,12 @@ and are asked to sign in again in Buzz. the full, scrollable list of names. Messages and huddle entries split groups. - **Solo** organizes your chats with agents. Choose **New chat**, select or tag - an agent, and send a message. Every agent addressed in the opening message - becomes a chat admin before that message is delivered; you remain owner. - Agents you add later to a Solo chat you own also join as admins, whether from - the composer or Chat access. Agents included only through workspace defaults - keep ordinary participation, and existing members keep their saved roles. + an agent, and send a message. Your agents become chat admins before the opening + message is delivered, including agents added by workspace defaults; you remain + owner. Ownership is verified from their signed profiles. Your agents added + later to a Solo chat you own also join as admins, whether from the composer or + Chat access. Other people's agents get ordinary participation; later additions + use Bot. Existing members keep their saved roles. If admin setup is interrupted, Retry on the opening message continues it without restoring later demotions or removals. If setup expires, choose **Abandon admin setup** in Outbox to keep the chat and current roles. diff --git a/docs/solo/README.md b/docs/solo/README.md index 9b0084780c..55b498976a 100644 --- a/docs/solo/README.md +++ b/docs/solo/README.md @@ -100,14 +100,16 @@ behavior on the label, so a rename touches copy only. agents: answer as one channel-scoped, top-level conversation. It is not access authority. The in-app agent harness reads it from the channel list; remote harnesses that only read `about` need to learn the label. -- The app promotes every agent addressed in the opening message through the - existing member-administration commands before releasing that message to - local agents or the relay. Workspace-only agents remain ordinary participants. - When the viewer owns the Solo chat, new agents added later through the composer - or Chat access receive Admin in the membership command. Existing members keep +- New Solo chats grant Admin to the creator's agents whose signed profiles verify + that ownership, including agents included through workspace defaults. Agents + owned by someone else keep ordinary participation. The app uses the existing + member-administration commands before releasing the opening message to local + agents or the relay. When the viewer owns the Solo chat, their own new agents + added later through the composer or Chat access receive Admin; other agents + join as Bot. Existing members keep their saved roles; retries retain the original addition's role and command ID. The create's local Outbox receipt retains the opening - recipients across interruptions; retries reconstruct the same grants and + admin targets across interruptions; retries reconstruct the same grants and confirm their recorded IDs before sending. A recorded grant stays complete after a later demotion or removal. Expired, unrecorded grants are never re-dated. Outbox offers **Abandon admin setup** for the expired, delivered create: explicit diff --git a/docs/solo/sharing.md b/docs/solo/sharing.md index bb38c743c7..1f2224a5c5 100644 --- a/docs/solo/sharing.md +++ b/docs/solo/sharing.md @@ -39,9 +39,10 @@ people, agents and channels** for an owner who can add agents) filters current access and lists people under **Not in this chat**, each with an **Add** button; Enter adds the highlighted person. Adding is immediate and uses the Solo share rule (`canShareSoloChat`), with per-person **Adding…**, error and **Retry** states. The -owner's selectable agents are offered too and join as Admin, even with a Guest -admission default, without starting a run. Composer mentions use the same grant -when the viewer owns the chat; other participants' composer additions use Bot. +owner's selectable agents are offered too. Agents whose signed profiles verify +that the chat owner owns them join as Admin; other agents join as Bot, even with +a Guest admission default, without starting a run. Composer mentions use the +same rule; other participants' composer additions use Bot. Existing members keep their roles, and retries finish the original saved grant. Where the viewer cannot add agents, a note says to mention an agent in the chat instead. diff --git a/src/bundled/channels/ChannelMembersDialog.test.tsx b/src/bundled/channels/ChannelMembersDialog.test.tsx index 68054e2c48..8696c853f4 100644 --- a/src/bundled/channels/ChannelMembersDialog.test.tsx +++ b/src/bundled/channels/ChannelMembersDialog.test.tsx @@ -26,6 +26,7 @@ import type { VerifiedProfileAuthority } from "../../features/relay/verified-pro import { keypair, metadata, + ownedProfile, profile, roster, signed, @@ -114,6 +115,7 @@ async function setup( pendingMemberNames?: Promise; channelCreation?: boolean; memberWrites?: boolean; + agentOwner?: "viewer" | "other"; searchProfiles?: ( query: string, limit: number, @@ -129,8 +131,9 @@ async function setup( const viewer = keypair(), relay = options.relay ?? keypair(), person = keypair(); + const agentKey = keypair(); const agent = { - pubkey: "ab".repeat(32), + pubkey: agentKey.pubkey, name: "Fixture agent", relayUrl: "wss://relay.example.test", owner: viewer.pubkey, @@ -167,6 +170,17 @@ async function setup( }); const personProfile = profile(person, { name: "Morgan" }); const stableEvents = [ + ...(localAgent + ? [ + eventDto( + await ownedProfile( + agentKey, + options.agentOwner === "other" ? person : viewer, + "Fixture agent", + ), + ), + ] + : []), signed(relay, { kind: 39000, content: "", @@ -2034,7 +2048,7 @@ it("shares the identity presentation with invitation rows without assigning a ch expect( within(row).queryByText("Agent", { exact: true }), ).not.toBeInTheDocument(); - expect(within(row).queryByText(/Managed by/)).not.toBeInTheDocument(); + expect(within(row).getByText("Managed by Carl (you)")).toBeVisible(); expect( row.querySelector('[data-avatar-shape="squircle"]'), ).toBeInTheDocument(); @@ -3270,12 +3284,21 @@ it.each([false, true])( }, ); -it.each(["private", "public"] as const)( - "adds the Solo owner's agent as Admin in a %s chat with a Guest default", - async (visibility) => { +it.each( + (["private", "public"] as const).flatMap((visibility) => + (["viewer", "other"] as const).map((agentOwner) => ({ + visibility, + agentOwner, + role: agentOwner === "viewer" ? "admin" : "bot", + })), + ), +)( + "adds an agent owned by $agentOwner as $role in a $visibility Solo chat with a Guest default", + async ({ visibility, agentOwner, role }) => { const t = await setup("solo", false, true, undefined, undefined, { visibility, joinRole: "guest", + agentOwner, }); await t.user.type(screen.getByRole("searchbox"), "Fixture agent"); await t.user.click( @@ -3283,7 +3306,7 @@ it.each(["private", "public"] as const)( ); await screen.findByText("Fixture agent added."); expect(t.publish).toHaveBeenCalledOnce(); - expect(t.publish.mock.calls[0]?.[0].tags).toContainEqual(["role", "admin"]); + expect(t.publish.mock.calls[0]?.[0].tags).toContainEqual(["role", role]); }, ); diff --git a/src/bundled/channels/ChannelsPage.solo.test.tsx b/src/bundled/channels/ChannelsPage.solo.test.tsx index 1cc4fb8ec2..50f0b252ae 100644 --- a/src/bundled/channels/ChannelsPage.solo.test.tsx +++ b/src/bundled/channels/ChannelsPage.solo.test.tsx @@ -52,6 +52,14 @@ vi.mock( ); composerDOMFixture(); +// Navigation fixtures deliberately never finish display-profile loading. +// Ownership authority is exercised in the Solo/admin session tests. +vi.mock("../../features/relay/solo-admins", async (original) => ({ + ...(await original()), + ownedSoloAgents: vi.fn< + typeof import("../../features/relay/solo-admins").ownedSoloAgents + >(async (_profiles, _viewer, keys) => new Set(keys)), +})); const owners: ReturnType[] = []; afterEach(() => { cleanup(); diff --git a/src/features/relay/channel-writes.ts b/src/features/relay/channel-writes.ts index 990c9ab07c..4dfc68c9e2 100644 --- a/src/features/relay/channel-writes.ts +++ b/src/features/relay/channel-writes.ts @@ -8,12 +8,14 @@ import { promoteSoloAdmins, soloAdminKey, soloAdminRecovery, + ownedSoloAgents, } from "./solo-admins"; import { isBatchAddition } from "../channel-members/members"; import { withdraw } from "./withdraw"; import type { ChannelQueries, ChannelSummary } from "./contracts"; import type { RelayReader } from "./reader"; import type { EventData } from "./events"; +import type { ProfileQueries } from "./profile-directory"; export const DEFAULT_TEMPORARY_CHANNEL_TTL_SECONDS = 7 * 24 * 60 * 60; @@ -47,6 +49,8 @@ export function createChannelWrites( agents?: { selectable: () => readonly string[]; archived: (pubkey: string) => boolean; + profiles?: Pick; + viewer?: string; }, relayAuthor?: string, /** Signed roster discovery, including channels this viewer cannot open. */ @@ -462,12 +466,6 @@ export function createChannelWrites( if (active?.() === false) throw new DOMException("Channel addition cancelled", "AbortError"); const original = await refreshMembership(id); - // Owners' new Solo agents get Admin; other Solo additions can still reply - // even with a saved Guest admission default. Existing members are untouched. - const roleTags = - original.channelType === "solo" - ? [["role", original.viewerRole === "owner" ? "admin" : "bot"]] - : []; if (active?.() === false) throw new DOMException("Channel addition cancelled", "AbortError"); const unique = [...new Set(keys)].filter( @@ -490,6 +488,7 @@ export function createChannelWrites( unique.some((key) => !original.members?.includes(key) && !known.has(key)) ) throw new Error("Choose an agent from your agent library."); + let owned: ReadonlySet | undefined; // Additions are published and acknowledged in turn; the roster is then // confirmed with one exact read rather than a gate after every command. const added: string[] = []; @@ -514,7 +513,7 @@ export function createChannelWrites( item.event.tags.some( ([name, value]) => name === "p" && value === key, ) && - roles.length === roleTags.length && + roles.length === (original.channelType === "solo" ? 1 : 0) && // Recovery finishes the saved grant even if the viewer's role changed. roles.every( (tag) => @@ -526,6 +525,28 @@ export function createChannelWrites( throw new Error( `This agent-add request expired. Open Outbox, remove the “Add agent ${key.slice(0, 12)}” item, then add the agent again. Check channel membership first if the request was unconfirmed.`, ); + if ( + original.channelType === "solo" && + !previous && + original.viewerRole === "owner" + ) { + owned ??= await ownedSoloAgents( + agents?.profiles, + agents?.viewer, + unique, + ); + } + const roleTags = + original.channelType === "solo" + ? [ + [ + "role", + original.viewerRole === "owner" && owned?.has(key) + ? "admin" + : "bot", + ], + ] + : []; const operation = previous?.event.id ?? writer(!!active).send( @@ -583,6 +604,7 @@ export function createChannelWrites( discovery, relayAuthor, signal, + (keys) => ownedSoloAgents(agents?.profiles, agents?.viewer, keys), ); signal.throwIfAborted(); await finishRecovery(saved.event.id, recovery); diff --git a/src/features/relay/session-agent-admission.test.ts b/src/features/relay/session-agent-admission.test.ts index bbc48a0d8c..85f1d339f1 100644 --- a/src/features/relay/session-agent-admission.test.ts +++ b/src/features/relay/session-agent-admission.test.ts @@ -1,9 +1,9 @@ import { expect, it, vi } from "vitest"; import { createRelaySession } from "./session"; import { PublishRejected } from "./outbox"; -import { keypair, roster, signed } from "./testing"; +import { keypair, ownedProfile, roster, signed } from "./testing"; import { matchesEvent } from "./projection"; -import type { RelayEvent } from "./events"; +import { eventDto, type RelayEvent } from "./events"; import { SOLO_LABEL } from "../solo/labels"; type ViewerRole = "owner" | "admin" | "member"; @@ -11,6 +11,7 @@ type ViewerRole = "owner" | "admin" | "member"; function setup( visibility: "private" | "public" = "private", initialRole: ViewerRole = "member", + ownership: "viewer" | "other" | "missing" = "viewer", ) { let viewerRole = initialRole; const viewer = keypair(), @@ -42,7 +43,20 @@ function setup( } return signed(viewer, template); }); - const secondAgent = keypair().pubkey; + const second = keypair(), + other = keypair(); + const secondAgent = second.pubkey; + let agentProfile = + ownership === "missing" + ? Promise.resolve( + signed(agent, { + kind: 0, + tags: [], + content: JSON.stringify({ owner: viewer.pubkey }), + }), + ) + : ownedProfile(agent, ownership === "viewer" ? viewer : other); + const secondProfile = ownedProfile(second, other); const meta = (id: string, type: string, extra: string[][] = []) => signed(relay, { kind: 39000, @@ -64,10 +78,13 @@ function setup( const publish = vi.fn(async (_event: RelayEvent) => { const target = _event.tags.find(([name]) => name === "h")?.[1]; if (denied) throw new PublishRejected("Only channel admins can add agents"); + const added = _event.tags.flatMap(([tag, key]) => + tag === "p" && key ? [key] : [], + ); if (!omitMembership && target === parent) - members = [viewer.pubkey, agent.pubkey]; + members = [...new Set([...members, ...added])]; if (!omitMembership && target === child) - childMembers = [viewer.pubkey, agent.pubkey]; + childMembers = [...new Set([...childMembers, ...added])]; clock++; afterPublish(); }); @@ -113,6 +130,8 @@ function setup( roster(agent, child, [viewer.pubkey, agent.pubkey], clock + 1), ]; const events = [ + eventDto(await agentProfile), + eventDto(await secondProfile), signed(relay, { kind: 13535, created_at: clock, @@ -141,6 +160,26 @@ function setup( child, agent: agent.pubkey, secondAgent, + async transferAgent() { + const profile = await ownedProfile(agent, other); + agentProfile = Promise.resolve( + signed(agent, { + kind: 0, + tags: profile.tags, + content: profile.content, + created_at: clock + 10, + }), + ); + await owner.session.read( + [{ kinds: [0], authors: [agent.pubkey], limit: 1 }], + { fresh: true }, + ); + expect( + owner.session.profiles + .event?.(agent.pubkey) + ?.tags.find(([tag]) => tag === "auth")?.[1], + ).toBe(other.pubkey); + }, archive: (key: string) => { clock++; archived.push(key); @@ -200,6 +239,43 @@ function setup( }; } +it.each(["other", "missing"] as const)( + "adds a selectable agent as Bot when its signed ownership is %s", + async (ownership) => { + const test = setup("private", "owner", ownership); + try { + await test.ready(); + await test.owner.session.channelWrites.addAgents(test.child, [ + test.agent, + ]); + expect(test.publish.mock.calls[0]?.[0].tags).toContainEqual([ + "role", + "bot", + ]); + } finally { + test.owner.dispose(); + } + }, +); + +it("chooses each new agent's role separately in a mixed-ownership Solo addition", async () => { + const test = setup("private", "owner"); + try { + await test.ready(); + await test.owner.session.channelWrites.addAgents(test.child, [ + test.agent, + test.secondAgent, + ]); + expect( + test.publish.mock.calls.map(([event]) => + event.tags.filter(([tag]) => tag === "role"), + ), + ).toEqual([[["role", "admin"]], [["role", "bot"]]]); + } finally { + test.owner.dispose(); + } +}); + it.each( (["private", "public"] as const).flatMap((visibility) => (["owner", "admin", "member"] as const).map((viewerRole) => ({ @@ -310,9 +386,15 @@ it.each([ { initialRole: "member", retryRole: "member", addedRole: "bot" }, { initialRole: "member", retryRole: "owner", addedRole: "bot" }, { initialRole: "owner", retryRole: "member", addedRole: "admin" }, + { + initialRole: "owner", + retryRole: "owner", + addedRole: "admin", + transferred: true, + }, ] as const)( "keeps the saved $addedRole invitation when $initialRole retries as $retryRole", - async ({ initialRole, retryRole, addedRole }) => { + async ({ initialRole, retryRole, addedRole, ...options }) => { const test = setup("private", initialRole); try { await test.ready(); @@ -327,6 +409,7 @@ it.each([ ).not.toContain(test.agent); const first = test.publish.mock.calls[0]?.[0]; expect(first?.tags).toContainEqual(["role", addedRole]); + if ("transferred" in options) await test.transferAgent(); test.setViewerRole(retryRole); test.setDenied(false); await test.owner.session.channelWrites.addAgents(test.child, [ diff --git a/src/features/relay/session.ts b/src/features/relay/session.ts index 9b9d00ee4d..d2095be759 100644 --- a/src/features/relay/session.ts +++ b/src/features/relay/session.ts @@ -1818,6 +1818,8 @@ export function createRelaySession( { selectable: () => agentChoices.snapshot().selectable.map((agent) => agent.pubkey), + profiles: profiles.queries, + viewer: transport?.viewer ?? "", archived: (pubkey) => agentUnavailable( { diff --git a/src/features/relay/solo-admins.integration.test.ts b/src/features/relay/solo-admins.integration.test.ts index 73249e192a..3ce3cfcc66 100644 --- a/src/features/relay/solo-admins.integration.test.ts +++ b/src/features/relay/solo-admins.integration.test.ts @@ -1,12 +1,12 @@ import { assert, afterEach, expect, it, vi } from "vitest"; import { createRelaySession } from "./session"; -import { keypair, metadata, signed } from "./testing"; +import { keypair, metadata, ownedProfile, signed } from "./testing"; import { matchesEvent } from "./projection"; import { SOLO_LABEL } from "../solo/labels"; import { soloAdminKey } from "./solo-admins"; import { validateMemberAdministrationTemplate } from "../channel-members/administration-protocol"; import { PublishRejected, type OutgoingEvent } from "./outbox"; -import type { ReadFilter, RelayEvent } from "./events"; +import { eventDto, type ReadFilter, type RelayEvent } from "./events"; import type { EventTemplate } from "nostr-tools"; const sessions: ReturnType[] = []; @@ -18,8 +18,13 @@ function setup() { const viewer = keypair(), relay = keypair(); const channel = crypto.randomUUID(); - const agents: [string, string] = [keypair().pubkey, keypair().pubkey]; - const workspaceAgent = keypair().pubkey; + const agentKeys = [keypair(), keypair()] as const; + const agents: [string, string] = [agentKeys[0].pubkey, agentKeys[1].pubkey]; + const workspaceKey = keypair(); + const workspaceAgent = workspaceKey.pubkey; + const profiles = Promise.all( + [...agentKeys, workspaceKey].map((key) => ownedProfile(key, viewer)), + ); let journal: readonly OutgoingEvent[] = []; const events = new Map(); const roles = new Map(); @@ -56,6 +61,7 @@ function setup() { ], }); return [ + ...(await profiles).map(eventDto), ...events.values(), ...(roles.size ? [ @@ -110,7 +116,7 @@ function setup() { undefined, false, undefined, - { admins: agents }, + { admins: [...agents, workspaceAgent] }, ); void creation.ready.catch(() => {}); const message = owner.session.messages.send( @@ -172,11 +178,11 @@ it("confirms a lost grant ACK and holds the opening message and local wake until release(); await vi.waitFor(() => expect(h.events.has(message)).toBe(true)); expect(h.agents.map((key) => h.roles.get(key))).toEqual(["admin", "admin"]); - expect(h.roles.get(h.workspaceAgent)).toBe("member"); + expect(h.roles.get(h.workspaceAgent)).toBe("admin"); expect(h.roles.get(h.viewer.pubkey)).toBe("owner"); - expect(h.adminPublish).toHaveBeenCalledTimes(2); + expect(h.adminPublish).toHaveBeenCalledTimes(3); expect(h.adminPublish.mock.calls.map(([event]) => event.tags)).toEqual( - h.agents.map((key) => [ + [...h.agents, h.workspaceAgent].map((key) => [ ["h", h.channel], ["p", key], ["role", "admin"], diff --git a/src/features/relay/solo-admins.test.ts b/src/features/relay/solo-admins.test.ts index 4579b9c6d0..79d3eeb374 100644 --- a/src/features/relay/solo-admins.test.ts +++ b/src/features/relay/solo-admins.test.ts @@ -1,13 +1,67 @@ import { assert, expect, it, vi } from "vitest"; import { isExpiredSoloAdminSetup, + ownedSoloAgents, promoteSoloAdmins, soloAdminRecovery, } from "./solo-admins"; -import { keypair, signed } from "./testing"; +import { keypair, ownedProfile, signed } from "./testing"; import { matchesEvent } from "./projection"; import type { OutgoingEvent } from "./outbox"; -import type { ReadFilter, RelayEvent } from "./events"; +import { eventDto, type ReadFilter, type RelayEvent } from "./events"; + +it("grants ownership only from the current verified NIP-OA profile, never library hints", async () => { + const viewer = keypair(), + other = keypair(); + const own = keypair(), + shared = keypair(), + unsigned = keypair(), + hinted = keypair(); + const heads = new Map([ + [own.pubkey, eventDto(await ownedProfile(own, viewer))], + [shared.pubkey, eventDto(await ownedProfile(shared, other))], + [unsigned.pubkey, await ownedProfile(unsigned, viewer)], + [ + hinted.pubkey, + eventDto( + signed(hinted, { + kind: 0, + content: JSON.stringify({ owner: viewer.pubkey }), + tags: [], + }), + ), + ], + ]); + const ensure = vi.fn(async () => {}); + expect( + await ownedSoloAgents( + { ensure, event: (key) => heads.get(key) }, + viewer.pubkey, + [...heads.keys(), own.pubkey], + ), + ).toEqual(new Set([own.pubkey])); + expect(ensure).toHaveBeenCalledExactlyOnceWith([...heads.keys()]); +}); + +it("does not grant from an ownership head replaced while its attestation is checked", async () => { + const viewer = keypair(), + agent = keypair(); + const previous = eventDto(await ownedProfile(agent, viewer)); + const changed = eventDto( + signed(agent, { + kind: 0, + content: "{}", + tags: [], + created_at: previous.created_at + 1, + }), + ); + const event = vi.fn().mockReturnValueOnce(previous).mockReturnValue(changed); + expect( + await ownedSoloAgents({ ensure: async () => {}, event }, viewer.pubkey, [ + agent.pubkey, + ]), + ).toEqual(new Set()); +}); function setup() { const owner = keypair(), @@ -54,8 +108,16 @@ function setup() { publish, }; const controller = new AbortController(); + const owned = vi.fn(async () => new Set(agents)); const run = (saved = creation) => - promoteSoloAdmins(saved, writer, { read }, relay.pubkey, controller.signal); + promoteSoloAdmins( + saved, + writer, + { read }, + relay.pubkey, + controller.signal, + owned, + ); return { agents, creation, @@ -64,6 +126,7 @@ function setup() { read, writer, publish, + owned, run, }; } @@ -77,6 +140,25 @@ it("does not restore a removed opening agent when replaying a stale creation rec expect(h.roles.has(h.agents[0])).toBe(false); }); +it("refuses an unrecorded opening grant after ownership changes without replacing the saved intent", async () => { + const h = setup(); + const saved = structuredClone(h.creation); + h.owned.mockResolvedValue(new Set()); + await expect(h.run()).rejects.toThrow("not verified as owned"); + expect(h.writer.sign).not.toHaveBeenCalled(); + expect(h.publish).not.toHaveBeenCalled(); + expect(structuredClone(h.creation)).toEqual(saved); +}); + +it("confirms recorded opening grants after an ownership change without issuing new grants", async () => { + const h = setup(); + await h.run(); + h.owned.mockClear().mockResolvedValue(new Set()); + await h.run(); + expect(h.owned).not.toHaveBeenCalled(); + expect(h.publish).toHaveBeenCalledTimes(2); +}); + it.each(["owner", "guest", "absent"])( "preserves an opening agent changed to %s before its grant", async (role) => { diff --git a/src/features/relay/solo-admins.ts b/src/features/relay/solo-admins.ts index 9238f6d6ae..f06d01298c 100644 --- a/src/features/relay/solo-admins.ts +++ b/src/features/relay/solo-admins.ts @@ -1,4 +1,7 @@ import { getEventHash } from "nostr-tools"; +import { attestedOwner } from "../agents/owner-attestation"; +import { hasEventProof } from "./events"; +import type { ProfileQueries } from "./profile-directory"; import { memberAdministrationTemplate } from "../channel-members/administration-protocol"; import type { OutboxRecovery, OutgoingEvent } from "./outbox"; import type { RelayReader } from "./reader"; @@ -7,6 +10,33 @@ import type { RelayWriter } from "./transport"; export const soloAdminKey = (channel: string) => `solo-initial-admins:${channel}`; +/** Library inclusion is discovery, never authority to grant chat Admin. */ +export async function ownedSoloAgents( + profiles: Pick | undefined, + viewer: string | undefined, + keys: readonly string[], +): Promise> { + const owned = new Set(); + if (!profiles || !viewer || !keys.length) return owned; + const unique = [...new Set(keys)]; + await profiles.ensure(unique); + await Promise.all( + unique.map(async (key) => { + const head = profiles.event?.(key); + if ( + head && + hasEventProof(head) && + head.kind === 0 && + head.pubkey === key && + (await attestedOwner(head)) === viewer && + profiles.event?.(key) === head + ) + owned.add(key); + }), + ); + return new Set(unique.filter((key) => owned.has(key))); +} + /** Local recovery only; the relay still receives an ordinary channel create. */ export function soloAdminRecovery( channel: string, @@ -62,6 +92,7 @@ export async function promoteSoloAdmins( reader: RelayReader, relayAuthor: string, signal: AbortSignal, + owned?: (keys: readonly string[]) => Promise>, ) { const create = creation.event; const channel = create.tags.find(([tag]) => tag === "h")?.[1]; @@ -82,6 +113,7 @@ export async function promoteSoloAdmins( throw new Error("The saved chat admin setup is invalid."); const read = (filters: Parameters[0]) => reader.read(filters, { signal, fresh: true, priority: "foreground" }); + let ownership: Promise> | undefined; for (const admin of admins as string[]) { signal.throwIfAborted(); const template = { @@ -111,6 +143,11 @@ export async function promoteSoloAdmins( throw new Error( "Chat admin setup expired. Abandon setup in Outbox to continue with current roles, or start a new chat.", ); + ownership ??= owned?.(admins as string[]); + if (!(await ownership)?.has(admin)) + throw new Error( + "An opening agent is not verified as owned by the chat creator. Check chat access before retrying.", + ); const rosters = await read([ { kinds: [39002], diff --git a/src/features/relay/testing.ts b/src/features/relay/testing.ts index 11bcada592..54aae7e18a 100644 --- a/src/features/relay/testing.ts +++ b/src/features/relay/testing.ts @@ -1,5 +1,5 @@ import { schnorr } from "@noble/curves/secp256k1.js"; -import { hexToBytes } from "nostr-tools/utils"; +import { bytesToHex, hexToBytes } from "nostr-tools/utils"; import { finalizeEvent, generateSecretKey, @@ -23,6 +23,30 @@ export function signed( ): RelayEvent { return finalizeEvent({ created_at: 1_700_000_000, ...template }, key.secret); } +/** A real NIP-OA delegation on an agent's signed profile. */ +export async function ownedProfile( + agent: Key, + owner: Key, + name?: string, +): Promise { + const conditions = "kind=0"; + const digest = await crypto.subtle.digest( + "SHA-256", + new TextEncoder().encode(`nostr:agent-auth:${agent.pubkey}:${conditions}`), + ); + return signed(agent, { + kind: 0, + content: JSON.stringify(name ? { name } : {}), + tags: [ + [ + "auth", + owner.pubkey, + conditions, + bytesToHex(schnorr.sign(new Uint8Array(digest), owner.secret)), + ], + ], + }); +} /** The native `relay_verify_signatures` command, with real BIP-340 checks. */ export const nativeSignatureChecks = (args: unknown) => ( diff --git a/src/features/solo/SoloDraft.test.tsx b/src/features/solo/SoloDraft.test.tsx index 33920a23d3..b4add93984 100644 --- a/src/features/solo/SoloDraft.test.tsx +++ b/src/features/solo/SoloDraft.test.tsx @@ -38,6 +38,7 @@ import { ToastProvider } from "../../shared/design-system/ui/Toast"; import { ChatNotStarted, createChannelWrites } from "../relay/channel-writes"; import { createOutbox } from "../relay/outbox"; import { keypair, signed } from "../relay/testing"; +import { ownedSoloAgents } from "../relay/solo-admins"; import { SOLO_LABEL } from "./labels"; import { attachmentDraft } from "../messages/attachment-draft"; import type { @@ -89,6 +90,10 @@ vi.mock("../channel-navigation/solo-navigation", async (original) => ({ })); composerDOMFixture(); +vi.mock("../relay/solo-admins", async (original) => ({ + ...(await original()), + ownedSoloAgents: vi.fn(), +})); afterEach(cleanup); afterEach(() => regionNavigation.set(undefined)); afterEach(() => { @@ -97,6 +102,9 @@ afterEach(() => { delete (HTMLElement.prototype as Partial).scrollIntoView; }); beforeEach(() => { + vi.mocked(ownedSoloAgents).mockImplementation( + async (_profiles, _viewer, keys) => new Set(keys), + ); localStorage.clear(); Object.defineProperty(navigator, "locks", { configurable: true, @@ -321,6 +329,53 @@ it("uses restored explicit mentions, not a separate picker", async () => { "b".repeat(64), ]); }); + +it.each([true, false])( + "applies verified ownership equally to workspace defaults (owned=%s)", + async (workspaceOwned) => { + const test = await projectSetup(["b".repeat(64)]); + const admins = workspaceOwned + ? ["a".repeat(64), "b".repeat(64)] + : ["a".repeat(64)]; + vi.mocked(ownedSoloAgents).mockResolvedValueOnce(new Set(admins)); + writeView( + "test", + "solo:project:work:new-draft", + taggedDraft("Use the workspace"), + ); + render( + , + ); + await userEvent.click(screen.getByRole("button", { name: "Send message" })); + await waitFor(() => expect(test.messages.send).toHaveBeenCalledOnce()); + expect(test.channelWrites.start.mock.calls[0]?.[2]).toEqual([ + "a".repeat(64), + "b".repeat(64), + ]); + expect(startOptions(test)).toMatchObject({ admins }); + expect(test.messages.send.mock.calls[0]?.[2]).toEqual(["a".repeat(64)]); + }, +); + +it("sends to a shared opening agent without requesting Admin", async () => { + const test = setup(); + vi.mocked(ownedSoloAgents).mockResolvedValueOnce(new Set()); + writeView( + "test", + "solo:new-draft", + taggedDraft("Help with this", "b".repeat(64), "Outside agent"), + ); + render(); + await userEvent.click(screen.getByRole("button", { name: "Send message" })); + await waitFor(() => expect(test.messages.send).toHaveBeenCalledOnce()); + expect(startOptions(test)).toMatchObject({ admins: [] }); + expect(test.messages.send.mock.calls[0]?.[2]).toEqual(["b".repeat(64)]); +}); type User = ReturnType; it.each([ { @@ -3806,7 +3861,9 @@ it.each([false, true])( expect(test.channelWrites.start.mock.calls[0]?.[2]).toEqual( prepareStart.mock.calls[0]?.[1].members, ); - expect(startOptions(test)).toMatchObject({ admins: ["a".repeat(64)] }); + expect(startOptions(test)).toMatchObject({ + admins: ["a".repeat(64), "b".repeat(64)], + }); expect(test.messages.send.mock.calls[0]?.[0]).toBe( prepareStart.mock.calls[0]?.[1].channelId, ); diff --git a/src/features/solo/SoloDraft.tsx b/src/features/solo/SoloDraft.tsx index c1d5620633..d1be2776e1 100644 --- a/src/features/solo/SoloDraft.tsx +++ b/src/features/solo/SoloDraft.tsx @@ -19,6 +19,7 @@ import { } from "./workspace"; import { useCallback, useEffect, useRef, useState } from "react"; import type { RelaySession } from "../relay/session"; +import { ownedSoloAgents } from "../relay/solo-admins"; import { readView, writeView, @@ -474,6 +475,10 @@ export function SoloDraft({ "Solo chats can only use your available agents. Check mentions and workspace defaults.", ); } + const admins = [ + ...(await ownedSoloAgents(session.profiles, session.viewer, members)), + ]; + if (!mounted.current) return; // Read at Send: the region's source may have stopped since. const regionOwner = () => { const current = region @@ -574,7 +579,7 @@ export function SoloDraft({ } : undefined, // Unguarded, so a restart can retry it like any New chat. - { admins: recipients, ...(region ? { labels: [region] } : {}) }, + { admins, ...(region ? { labels: [region] } : {}) }, ); } catch (reason) { if (startKey) writeView(scope, startKey, null); diff --git a/tests/browser/fixture.mjs b/tests/browser/fixture.mjs index 930a208a51..d84bd4720a 100644 --- a/tests/browser/fixture.mjs +++ b/tests/browser/fixture.mjs @@ -284,16 +284,27 @@ export const test = base.extend({ const key = generateSecretKey(); soloAgentKeys.push(key); const pubkey = getPublicKey(key); - // A NIP-OA owner attestation marks a real agent profile; the app reads - // only its shape. Outside agents belong to someone else. - const owner = soloAgentNames.includes(name) - ? viewer - : getPublicKey(generateSecretKey()); + // Real ownership proofs: Admin admission verifies the delegation, + // independently of whether the identity appears in the library. + const ownerKey = soloAgentNames.includes(name) + ? userKey + : generateSecretKey(); + const owner = getPublicKey(ownerKey); + const delegation = createHash("sha256") + .update(`nostr:agent-auth:${pubkey}:`) + .digest(); servedProfiles.set( pubkey, sign( 0, - [["auth", owner, "", "0".repeat(128)]], + [ + [ + "auth", + owner, + "", + bytesToHex(schnorr.sign(delegation, ownerKey)), + ], + ], JSON.stringify({ name, is_agent: true }), key, ), diff --git a/tests/browser/solo-admin-abandonment.spec.mjs b/tests/browser/solo-admin-abandonment.spec.mjs index a2380bb107..d2f696e9d4 100644 --- a/tests/browser/solo-admin-abandonment.spec.mjs +++ b/tests/browser/solo-admin-abandonment.spec.mjs @@ -13,10 +13,89 @@ test.use({ soloChannels: [chat], ownSoloChannels: [chat], soloAgentNames: ["Recovery agent"], + soloOutsideAgentNames: ["Shared helper"], savedCommunities: ["primary"], historyCounts: { [channel]: 0, [chat]: 0 }, }); +// Restored opening intent exercises the production session, broker and signer; +// the draft's owned subset and workspace selection are covered in SoloDraft. +test("opening recovery grants a quiet owned default without promoting its shared recipient", async ({ + page, + app, +}, info) => { + const createdAt = Math.floor(Date.now() / 1000); + const [owned, shared] = app.soloAgents; + const creation = app.sign({ + kind: 9007, + created_at: createdAt, + content: "", + tags: [ + ["h", chat], + ["p", owned.pubkey], + ["p", shared.pubkey], + ], + }); + const message = app.sign({ + kind: 9, + created_at: createdAt, + content: "Only the shared helper is addressed", + tags: [ + ["h", chat], + ["p", shared.pubkey], + ], + }); + app.report.setupCreation = creation; + app.report.setupReceiverTime = createdAt; + await page.addInitScript( + ({ scope, creation, message, owned }) => { + localStorage.setItem( + `buzz-outbox-v1:${scope}`, + JSON.stringify([ + { + event: creation, + signed: creation, + delivery: "accepted", + recovery: { + key: `solo-initial-admins:${creation.tags[0][1]}`, + value: JSON.stringify([owned]), + }, + }, + { event: message, signed: message, delivery: "failed" }, + ]), + ); + }, + { + scope: `https://primary.example:${app.viewer}`, + creation, + message, + owned: owned.pubkey, + }, + ); + const outbox = await openOutbox(page, app.origin); + const row = outbox.getByRole("listitem").filter({ hasText: message.content }); + await row.getByRole("button", { name: "Retry", exact: true }).click(); + await expect + .poll( + () => + app.report.publications.filter(({ event }) => event.kind === 9).length, + ) + .toBe(1); + const grants = app.report.publications.filter( + ({ event }) => event.kind === 9000, + ); + expect(grants).toHaveLength(1); + expect(grants[0].event.tags).toContainEqual(["p", owned.pubkey]); + expect(grants[0].event.tags).not.toContainEqual(["p", shared.pubkey]); + expect( + app.report.publications.find(({ event }) => event.kind === 9).event, + ).toEqual(message); + await expect(outbox.getByRole("alert")).toHaveCount(0); + await outbox.screenshot({ + path: info.outputPath("OWNED_DEFAULT_SHARED_RECIPIENT.png"), + }); +}); + async function openOutbox(page, origin) { await page.goto(origin); await openPage(page, "Messages"); From ae87bf2f3ef65d5ac2ceac55ecc87e9ff8858a68 Mon Sep 17 00:00:00 2001 From: Taylor Ho Date: Mon, 16 Nov 2026 21:56:28 -0800 Subject: [PATCH 13/17] fix(solo): recheck ownership before automatic admin grants Honor newer verified agent profiles before each new role decision and fence opening publication across roster reads, signing and recovery locking. Preserve recorded grants, saved invitations and abandonment. Co-authored-by: Carl Signed-off-by: Taylor Ho --- src/features/relay/channel-writes.ts | 33 +-- .../relay/solo-admins.integration.test.ts | 68 ++++- src/features/relay/solo-admins.test.ts | 101 ++++++- src/features/relay/solo-admins.ts | 59 +++-- tests/browser/fixture.mjs | 39 ++- .../browser/solo-ownership-transfer.spec.mjs | 247 ++++++++++++++++++ 6 files changed, 501 insertions(+), 46 deletions(-) create mode 100644 tests/browser/solo-ownership-transfer.spec.mjs diff --git a/src/features/relay/channel-writes.ts b/src/features/relay/channel-writes.ts index 4dfc68c9e2..e9ac74612b 100644 --- a/src/features/relay/channel-writes.ts +++ b/src/features/relay/channel-writes.ts @@ -8,7 +8,7 @@ import { promoteSoloAdmins, soloAdminKey, soloAdminRecovery, - ownedSoloAgents, + soloAgentOwnership, } from "./solo-admins"; import { isBatchAddition } from "../channel-members/members"; import { withdraw } from "./withdraw"; @@ -488,7 +488,7 @@ export function createChannelWrites( unique.some((key) => !original.members?.includes(key) && !known.has(key)) ) throw new Error("Choose an agent from your agent library."); - let owned: ReadonlySet | undefined; + let profilesReady: Promise | undefined; // Additions are published and acknowledged in turn; the roster is then // confirmed with one exact read rather than a gate after every command. const added: string[] = []; @@ -525,25 +525,22 @@ export function createChannelWrites( throw new Error( `This agent-add request expired. Open Outbox, remove the “Add agent ${key.slice(0, 12)}” item, then add the agent again. Check channel membership first if the request was unconfirmed.`, ); + let owned: (() => boolean) | undefined; if ( original.channelType === "solo" && !previous && original.viewerRole === "owner" ) { - owned ??= await ownedSoloAgents( - agents?.profiles, - agents?.viewer, - unique, - ); + profilesReady ??= agents?.profiles?.ensure(unique); + await profilesReady; + owned = await soloAgentOwnership(agents?.profiles, agents?.viewer, key); } const roleTags = original.channelType === "solo" ? [ [ "role", - original.viewerRole === "owner" && owned?.has(key) - ? "admin" - : "bot", + original.viewerRole === "owner" && owned?.() ? "admin" : "bot", ], ] : []; @@ -592,19 +589,25 @@ export function createChannelWrites( "Chat admin setup was abandoned. Send a new message to continue.", ); const recovery = saved.recovery; + let profilesReady: Promise | undefined; await promoteSoloAdmins( saved, { ...adminWriter, - publish: (event, signal) => - withRecovery(saved.event.id, recovery, () => - adminWriter.publish(event, signal), - ), + publish: (event, signal, checkOwnership) => + withRecovery(saved.event.id, recovery, () => { + checkOwnership(); + return adminWriter.publish(event, signal); + }), }, discovery, relayAuthor, signal, - (keys) => ownedSoloAgents(agents?.profiles, agents?.viewer, keys), + async (key, targets) => { + profilesReady ??= agents?.profiles?.ensure(targets); + await profilesReady; + return soloAgentOwnership(agents?.profiles, agents?.viewer, key); + }, ); signal.throwIfAborted(); await finishRecovery(saved.event.id, recovery); diff --git a/src/features/relay/solo-admins.integration.test.ts b/src/features/relay/solo-admins.integration.test.ts index 3ce3cfcc66..ef08c057fc 100644 --- a/src/features/relay/solo-admins.integration.test.ts +++ b/src/features/relay/solo-admins.integration.test.ts @@ -25,6 +25,8 @@ function setup() { const profiles = Promise.all( [...agentKeys, workspaceKey].map((key) => ownedProfile(key, viewer)), ); + let beforeLock = async () => {}; + const profileOverrides = new Map(); let journal: readonly OutgoingEvent[] = []; const events = new Map(); const roles = new Map(); @@ -61,7 +63,9 @@ function setup() { ], }); return [ - ...(await profiles).map(eventDto), + ...(await profiles).map((profile) => + eventDto(profileOverrides.get(profile.pubkey) ?? profile), + ), ...events.values(), ...(roles.size ? [ @@ -94,6 +98,10 @@ function setup() { const open = async () => { const owner = createRelaySession(transport, { outboxStorage: { + async lock(_id, run) { + await beforeLock(); + return run(); + }, load: () => structuredClone(journal), save: (next) => { journal = structuredClone(next); @@ -129,6 +137,31 @@ function setup() { return { channel, viewer, + async transferAgent( + owner: Awaited>, + index: number, + ) { + const agent = agentKeys[index]; + assert.exists(agent); + const profile = await ownedProfile(agent, keypair()); + const previous = (await profiles).find( + (event) => event.pubkey === agent.pubkey, + ); + assert.exists(previous); + const changed = signed(agent, { + ...profile, + created_at: previous.created_at + 1, + }); + profileOverrides.set(agent.pubkey, changed); + await owner.session.read( + [{ kinds: [0], authors: [agent.pubkey], limit: 1 }], + { fresh: true }, + ); + expect(owner.session.profiles.event?.(agent.pubkey)?.id).toBe(changed.id); + }, + beforeLock: (run: () => Promise) => { + beforeLock = run; + }, agents, workspaceAgent, roles, @@ -334,3 +367,36 @@ it("abandons expired setup while signing is held without granting or releasing i clock.mockRestore(); } }); + +it("checks the current profile inside the shared publication lock after signing", async () => { + const h = setup(); + const owner = await h.open(); + const sign = h.transport.memberAdministration.sign; + h.transport.memberAdministration.sign = async (template) => { + const event = await sign(template); + h.beforeLock(async () => { + h.beforeLock(async () => {}); + await h.transferAgent(owner, 0); + }); + return event; + }; + const { creation, message } = h.start(owner); + await creation.ready; + await expect( + owner.session.channelWrites.prepareOpening(h.channel), + ).rejects.toThrow("not verified as owned"); + expect(h.adminPublish).not.toHaveBeenCalled(); + expect(h.roles.get(h.agents[0])).toBe("member"); + expect(h.events.has(message)).toBe(false); + await vi.waitFor(() => + expect( + owner.session.outbox?.snapshot().find((item) => item.event.id === message) + ?.delivery, + ).toBe("failed"), + ); + expect( + owner.session.outbox + ?.snapshot() + .some((item) => item.recovery?.key === soloAdminKey(h.channel)), + ).toBe(true); +}); diff --git a/src/features/relay/solo-admins.test.ts b/src/features/relay/solo-admins.test.ts index 79d3eeb374..c91e5af8d0 100644 --- a/src/features/relay/solo-admins.test.ts +++ b/src/features/relay/solo-admins.test.ts @@ -4,6 +4,7 @@ import { ownedSoloAgents, promoteSoloAdmins, soloAdminRecovery, + soloAgentOwnership, } from "./solo-admins"; import { keypair, ownedProfile, signed } from "./testing"; import { matchesEvent } from "./projection"; @@ -95,12 +96,18 @@ function setup() { filters.some((filter) => matchesEvent(event, filter)), ); }); - const publish = vi.fn(async (event: RelayEvent) => { - const agent = event.tags.find(([tag]) => tag === "p")?.[1]; - assert.exists(agent); - records.set(event.id, event); - roles.set(agent, "admin"); - }); + const publish = vi.fn( + async ( + event: RelayEvent, + _signal: AbortSignal, + _checkOwnership: () => void, + ) => { + const agent = event.tags.find(([tag]) => tag === "p")?.[1]; + assert.exists(agent); + records.set(event.id, event); + roles.set(agent, "admin"); + }, + ); const writer = { sign: vi.fn(async (template: Parameters[1]) => signed(owner, template), @@ -108,7 +115,11 @@ function setup() { publish, }; const controller = new AbortController(); - const owned = vi.fn(async () => new Set(agents)); + const owned = vi.fn( + async (_key: string): Promise<() => boolean> => + () => + true, + ); const run = (saved = creation) => promoteSoloAdmins( saved, @@ -143,7 +154,7 @@ it("does not restore a removed opening agent when replaying a stale creation rec it("refuses an unrecorded opening grant after ownership changes without replacing the saved intent", async () => { const h = setup(); const saved = structuredClone(h.creation); - h.owned.mockResolvedValue(new Set()); + h.owned.mockResolvedValue(() => false); await expect(h.run()).rejects.toThrow("not verified as owned"); expect(h.writer.sign).not.toHaveBeenCalled(); expect(h.publish).not.toHaveBeenCalled(); @@ -153,7 +164,7 @@ it("refuses an unrecorded opening grant after ownership changes without replacin it("confirms recorded opening grants after an ownership change without issuing new grants", async () => { const h = setup(); await h.run(); - h.owned.mockClear().mockResolvedValue(new Set()); + h.owned.mockClear().mockResolvedValue(() => false); await h.run(); expect(h.owned).not.toHaveBeenCalled(); expect(h.publish).toHaveBeenCalledTimes(2); @@ -253,3 +264,75 @@ it("limits abandonment to a valid delivered and expired opening-admin receipt", clock.mockRestore(); } }); + +it("invalidates a verified ownership guard when its head is replaced or evicted", async () => { + const viewer = keypair(), + agent = keypair(); + const initial = eventDto(await ownedProfile(agent, viewer)); + let head: RelayEvent | undefined = initial; + const owns = await soloAgentOwnership( + { event: () => head }, + viewer.pubkey, + agent.pubkey, + ); + expect(owns()).toBe(true); + head = eventDto(await ownedProfile(agent, keypair())); + expect(owns()).toBe(false); + head = undefined; + expect(owns()).toBe(false); +}); + +it("rechecks the next opening target after publishing the previous grant", async () => { + const h = setup(); + const publish = h.publish.getMockImplementation(); + assert.exists(publish); + h.publish.mockImplementationOnce(async (event) => { + await publish(event, new AbortController().signal, () => {}); + h.owned.mockResolvedValue(() => false); + }); + await expect(h.run()).rejects.toThrow("not verified as owned"); + expect(h.publish).toHaveBeenCalledOnce(); + expect(h.writer.sign).toHaveBeenCalledOnce(); + expect(h.roles.get(h.agents[1])).toBe("member"); +}); + +it.each(["roster read", "signing", "publication lock"])( + "refuses an unrecorded grant if ownership changes during %s", + async (boundary) => { + const h = setup(); + let current = true; + h.owned.mockResolvedValue(() => current); + if (boundary === "roster read") { + const read = h.read.getMockImplementation(); + assert.exists(read); + h.read.mockImplementation(async (filters) => { + const result = await read(filters); + if (filters.some((filter) => filter.kinds?.includes(39002))) + current = false; + return result; + }); + } else if (boundary === "signing") { + const sign = h.writer.sign.getMockImplementation(); + assert.exists(sign); + h.writer.sign.mockImplementation(async (template) => { + const result = await sign(template); + current = false; + return result; + }); + } else { + // Like the production journal: another holder can change the profile + // before this callback acquires permission to publish. + h.writer.publish = vi.fn(async (_event, _signal, checkOwnership) => { + await Promise.resolve(); + current = false; + checkOwnership(); + }); + } + await expect(h.run()).rejects.toThrow("not verified as owned"); + expect(h.records.size).toBe(0); + expect(h.roles.get(h.agents[0])).toBe("member"); + expect(h.writer.sign).toHaveBeenCalledTimes( + boundary === "roster read" ? 0 : 1, + ); + }, +); diff --git a/src/features/relay/solo-admins.ts b/src/features/relay/solo-admins.ts index f06d01298c..6e6fc53feb 100644 --- a/src/features/relay/solo-admins.ts +++ b/src/features/relay/solo-admins.ts @@ -1,6 +1,6 @@ import { getEventHash } from "nostr-tools"; import { attestedOwner } from "../agents/owner-attestation"; -import { hasEventProof } from "./events"; +import { hasEventProof, type RelayEvent } from "./events"; import type { ProfileQueries } from "./profile-directory"; import { memberAdministrationTemplate } from "../channel-members/administration-protocol"; import type { OutboxRecovery, OutgoingEvent } from "./outbox"; @@ -10,6 +10,24 @@ import type { RelayWriter } from "./transport"; export const soloAdminKey = (channel: string) => `solo-initial-admins:${channel}`; +/** A verified head is authority only while it remains the directory's head. */ +export async function soloAgentOwnership( + profiles: Pick | undefined, + viewer: string | undefined, + key: string, +): Promise<() => boolean> { + const head = profiles?.event?.(key); + const owned = !!( + viewer && + head && + hasEventProof(head) && + head.kind === 0 && + head.pubkey === key && + (await attestedOwner(head)) === viewer + ); + return () => owned && profiles?.event?.(key) === head; +} + /** Library inclusion is discovery, never authority to grant chat Admin. */ export async function ownedSoloAgents( profiles: Pick | undefined, @@ -22,16 +40,7 @@ export async function ownedSoloAgents( await profiles.ensure(unique); await Promise.all( unique.map(async (key) => { - const head = profiles.event?.(key); - if ( - head && - hasEventProof(head) && - head.kind === 0 && - head.pubkey === key && - (await attestedOwner(head)) === viewer && - profiles.event?.(key) === head - ) - owned.add(key); + if ((await soloAgentOwnership(profiles, viewer, key))()) owned.add(key); }), ); return new Set(unique.filter((key) => owned.has(key))); @@ -88,11 +97,17 @@ export function isExpiredSoloAdminSetup(item: OutgoingEvent): boolean { * that could undo a later demotion or removal. */ export async function promoteSoloAdmins( creation: OutgoingEvent, - writer: RelayWriter, + writer: Omit & { + publish( + event: RelayEvent, + signal: AbortSignal, + checkOwnership: () => void, + ): Promise; + }, reader: RelayReader, relayAuthor: string, signal: AbortSignal, - owned?: (keys: readonly string[]) => Promise>, + owned?: (key: string, targets: readonly string[]) => Promise<() => boolean>, ) { const create = creation.event; const channel = create.tags.find(([tag]) => tag === "h")?.[1]; @@ -113,7 +128,6 @@ export async function promoteSoloAdmins( throw new Error("The saved chat admin setup is invalid."); const read = (filters: Parameters[0]) => reader.read(filters, { signal, fresh: true, priority: "foreground" }); - let ownership: Promise> | undefined; for (const admin of admins as string[]) { signal.throwIfAborted(); const template = { @@ -143,11 +157,14 @@ export async function promoteSoloAdmins( throw new Error( "Chat admin setup expired. Abandon setup in Outbox to continue with current roles, or start a new chat.", ); - ownership ??= owned?.(admins as string[]); - if (!(await ownership)?.has(admin)) - throw new Error( - "An opening agent is not verified as owned by the chat creator. Check chat access before retrying.", - ); + const ownership = await owned?.(admin, admins as string[]); + const checkOwnership = () => { + if (!ownership?.()) + throw new Error( + "An opening agent is not verified as owned by the chat creator. Check chat access before retrying.", + ); + }; + checkOwnership(); const rosters = await read([ { kinds: [39002], @@ -170,12 +187,14 @@ export async function promoteSoloAdmins( throw new Error( "An opening agent's access changed. Check chat access before retrying.", ); + checkOwnership(); const signed = await writer.sign(template, signal); signal.throwIfAborted(); if (signed.id !== id || signed.pubkey !== create.pubkey) throw new Error("The signer changed the chat admin command."); try { - await writer.publish(signed, signal); + checkOwnership(); + await writer.publish(signed, signal, checkOwnership); } catch (error) { if (!(await recorded())) throw error; } diff --git a/tests/browser/fixture.mjs b/tests/browser/fixture.mjs index d84bd4720a..d9fec384d9 100644 --- a/tests/browser/fixture.mjs +++ b/tests/browser/fixture.mjs @@ -2196,7 +2196,16 @@ export const test = base.extend({ Math.abs(report.setupReceiverTime - event.created_at), ).toBeLessThanOrEqual(900); if (event.kind === 9000) { - expect(event.tags).toContainEqual(["role", "admin"]); + expect( + event.tags.filter(([tag]) => tag === "role"), + ).toEqual([ + [ + "role", + report.setupCreation + ? "admin" + : expect.stringMatching(/^(admin|bot)$/), + ], + ]); report.publications.push({ community, event }); return; } @@ -2859,6 +2868,34 @@ export const test = base.extend({ servedProfiles.set(event.pubkey, event); return event; }, + // A real, newer NIP-OA head; the client still admits it through a read. + transferSoloAgent(pubkey) { + const index = soloAgents.findIndex( + (agent) => agent.pubkey === pubkey, + ); + expect(index).toBeGreaterThanOrEqual(0); + const previous = servedProfiles.get(pubkey); + const ownerKey = generateSecretKey(); + const digest = createHash("sha256") + .update(`nostr:agent-auth:${pubkey}:`) + .digest(); + const event = sign( + 0, + [ + [ + "auth", + getPublicKey(ownerKey), + "", + bytesToHex(schnorr.sign(digest, ownerKey)), + ], + ], + previous.content, + soloAgentKeys[index], + previous.created_at + 1, + ); + servedProfiles.set(pubkey, event); + return event; + }, // Configure pre-existing members before opening the app. Reads stay at // the modeled relay, without a second browser-owned HTTP request. serveMembers(id, pubkeys) { diff --git a/tests/browser/solo-ownership-transfer.spec.mjs b/tests/browser/solo-ownership-transfer.spec.mjs new file mode 100644 index 0000000000..256c3cb770 --- /dev/null +++ b/tests/browser/solo-ownership-transfer.spec.mjs @@ -0,0 +1,247 @@ +import { test, expect } from "./fixture.mjs"; +import { openPage } from "./navigation.mjs"; +import { openChannelDetails } from "./channel-details.mjs"; + +const channel = "11111111-1111-4111-8111-111111111111"; +const chat = "33333333-3333-4333-8333-333333333333"; +test.use({ + productionBroker: true, + pluginFixtures: true, + openingAdminSetup: true, + channelLifecycle: true, + channelIds: [channel, chat], + channelNames: { [channel]: "Project updates", [chat]: "Recovery chat" }, + soloChannels: [chat], + ownSoloChannels: [chat], + soloAgentNames: ["First agent", "Transferring agent"], + savedCommunities: ["primary"], + historyCounts: { [channel]: 0, [chat]: 0 }, +}); + +for (const opening of [true, false]) + test(`${opening ? "opening" : "later addition"} rechecks a received ownership transfer before the next grant`, async ({ + page, + app, + }, info) => { + const createdAt = Math.floor(Date.now() / 1000); + const keys = app.soloAgents.map((agent) => agent.pubkey); + app.report.setupReceiverTime = createdAt; + const creation = app.sign({ + kind: 9007, + created_at: createdAt, + content: "", + tags: [["h", chat], ...keys.map((key) => ["p", key])], + }); + const message = app.sign({ + kind: 9, + created_at: createdAt, + content: "Opening ownership transfer", + tags: [["h", chat], ...keys.map((key) => ["p", key])], + }); + if (opening) { + app.report.setupCreation = creation; + await page.addInitScript( + ({ scope, creation, message, keys }) => { + localStorage.setItem( + `buzz-outbox-v1:${scope}`, + JSON.stringify([ + { + event: creation, + signed: creation, + delivery: "accepted", + recovery: { + key: `solo-initial-admins:${creation.tags[0][1]}`, + value: JSON.stringify(keys), + }, + }, + { event: message, signed: message, delivery: "failed" }, + ]), + ); + }, + { + scope: `https://primary.example:${app.viewer}`, + creation, + message, + keys, + }, + ); + } else { + // Model absent members, then their relay-confirmed roles. The real reader + // verifies each relay-signed roster; no client membership state is injected. + await page.route("**/api/relay/primary/query", async (route) => { + const response = await route.fetch(); + const events = await response.json(); + await route.fulfill({ + response, + json: events.map((event) => { + if ( + event.kind !== 39002 || + !event.tags.some(([tag, value]) => tag === "d" && value === chat) + ) + return event; + const tags = event.tags.filter( + ([tag, key]) => tag !== "p" || !keys.includes(key), + ); + for (const key of keys) { + const grant = app.report.publications.find( + ({ event }) => + event.kind === 9000 && + event.tags.some( + ([tag, value]) => tag === "p" && value === key, + ), + ); + if (grant) + tags.push([ + "p", + key, + "", + grant.event.tags.find(([tag]) => tag === "role")[1], + ]); + } + return app.signRelay({ + ...event, + tags, + created_at: + event.created_at + 100 + app.report.publications.length, + }); + }), + }); + }); + } + let release; + const held = new Promise((resolve) => { + release = resolve; + }); + let signingStarted = false; + await page.route("**/member-administration-sign", async (route) => { + const response = await route.fetch(); + expect(response.status()).toBe(200); + signingStarted = true; + await held; + await route.fulfill({ response }); + }); + try { + await page.goto(app.origin); + await openPage(page, "Messages"); + await page + .getByRole("button", { name: "Project updates", exact: true }) + .click(); + let outbox; + if (opening) { + await openChannelDetails(page); + const panel = page.getByRole("complementary", { + name: "Channel settings", + exact: true, + }); + await panel.getByText("Diagnostics", { exact: true }).click(); + const summary = panel + .locator("summary") + .filter({ hasText: /^Outbox ·/ }); + await summary.click(); + outbox = summary.locator(".."); + await outbox + .getByRole("listitem") + .filter({ hasText: message.content }) + .getByRole("button", { name: "Retry", exact: true }) + .click(); + } else { + await page.evaluate( + async ({ chat, keys }) => { + const session = window.fixtureRelay.snapshot().session; + await session.agentChoices.refresh("templates"); + window.ownershipAddition = "pending"; + void session.channelWrites.addAgents(chat, keys).then( + () => { + window.ownershipAddition = "complete"; + }, + (error) => { + window.ownershipAddition = String(error); + }, + ); + }, + { chat, keys }, + ); + } + await expect.poll(() => signingStarted).toBe(true); + const profile = app.transferSoloAgent(keys[1]); + await page.evaluate(async (key) => { + await window.fixtureRelay + .snapshot() + .session.read([{ kinds: [0], authors: [key], limit: 1 }], { + fresh: true, + }); + }, keys[1]); + await expect + .poll(() => + page.evaluate((key) => { + const profiles = window.fixtureRelay.snapshot().session.profiles; + return { id: profiles.event(key)?.id, owner: profiles.owner(key) }; + }, keys[1]), + ) + .toEqual({ id: profile.id, owner: profile.tags[0][1] }); + release(); + if (opening) { + await expect + .poll( + async () => + app.report.publications.some(({ event }) => event.kind === 9) || + ( + await page.evaluate( + (id) => + window.fixtureRelay + .snapshot() + .session.outbox.snapshot() + .find((item) => item.event.id === id)?.error ?? "", + message.id, + ) + ).includes("not verified as owned"), + ) + .toBe(true); + } else { + await expect + .poll(() => page.evaluate(() => window.ownershipAddition)) + .toBe("complete"); + } + const grants = app.report.publications + .filter(({ event }) => event.kind === 9000) + .map(({ event }) => ({ + key: event.tags.find(([tag]) => tag === "p")[1], + role: event.tags.find(([tag]) => tag === "role")[1], + })); + await info.attach("received-transfer-grants", { + body: JSON.stringify({ profile, grants }, null, 2), + contentType: "application/json", + }); + expect(grants).toEqual( + opening + ? [{ key: keys[0], role: "admin" }] + : [ + { key: keys[0], role: "admin" }, + { key: keys[1], role: "bot" }, + ], + ); + if (opening) { + expect( + app.report.publications.filter(({ event }) => event.kind === 9), + ).toHaveLength(0); + await expect( + outbox.getByRole("listitem").filter({ hasText: message.content }), + ).toContainText("Not sent"); + expect( + await page.evaluate( + (id) => + window.fixtureRelay + .snapshot() + .session.outbox.snapshot() + .find((item) => item.event.id === id)?.error, + message.id, + ), + ).toContain("not verified as owned"); + } + await page.screenshot({ + path: info.outputPath("RECEIVED_OWNERSHIP_TRANSFER.png"), + }); + } finally { + release(); + } + }); From 931a81c057fea20a2ae188f00fdcbd294a11b959 Mon Sep 17 00:00:00 2001 From: Taylor Ho Date: Tue, 17 Nov 2026 11:08:24 -0800 Subject: [PATCH 14/17] fix(solo): refresh ownership before automatic admin grants Read each new grant target through the fresh strongly consistent profile boundary, and reject cached authority when the fresh response has no matching signed head. Preserve recorded opening grants and exact saved invitation retries. Co-authored-by: Carl Signed-off-by: Taylor Ho --- src/features/relay/channel-writes.ts | 34 ++++++--- .../relay/session-agent-admission.test.ts | 71 +++++++++++++++++-- .../relay/solo-admins.integration.test.ts | 45 +++++++++++- 3 files changed, 134 insertions(+), 16 deletions(-) diff --git a/src/features/relay/channel-writes.ts b/src/features/relay/channel-writes.ts index e9ac74612b..7ea9d6b3ba 100644 --- a/src/features/relay/channel-writes.ts +++ b/src/features/relay/channel-writes.ts @@ -49,7 +49,7 @@ export function createChannelWrites( agents?: { selectable: () => readonly string[]; archived: (pubkey: string) => boolean; - profiles?: Pick; + profiles?: Pick; viewer?: string; }, relayAuthor?: string, @@ -488,7 +488,6 @@ export function createChannelWrites( unique.some((key) => !original.members?.includes(key) && !known.has(key)) ) throw new Error("Choose an agent from your agent library."); - let profilesReady: Promise | undefined; // Additions are published and acknowledged in turn; the roster is then // confirmed with one exact read rather than a gate after every command. const added: string[] = []; @@ -531,9 +530,7 @@ export function createChannelWrites( !previous && original.viewerRole === "owner" ) { - profilesReady ??= agents?.profiles?.ensure(unique); - await profilesReady; - owned = await soloAgentOwnership(agents?.profiles, agents?.viewer, key); + owned = await freshOwnership(key); } const roleTags = original.channelType === "solo" @@ -564,6 +561,26 @@ export function createChannelWrites( if (original?.channelType === "solo") await refresh(id, { members: unique }); } + /** Cached discovery is not evidence for a new automatic Admin grant. */ + async function freshOwnership(key: string) { + const events = await discovery.read( + [{ kinds: [0], authors: [key], limit: 1, consistency: "strong" }], + { signal, fresh: true, priority: "foreground" }, + ); + const owned = await soloAgentOwnership( + agents?.profiles, + agents?.viewer, + key, + ); + return () => + owned() && + events.some( + (event) => + event.kind === 0 && + event.pubkey === key && + event.id === agents?.profiles?.event?.(key)?.id, + ); + } /** Solo chats this device is starting, until they can take events. */ const starts = new Map>(); const adminSetups = new Map>(); @@ -589,7 +606,6 @@ export function createChannelWrites( "Chat admin setup was abandoned. Send a new message to continue.", ); const recovery = saved.recovery; - let profilesReady: Promise | undefined; await promoteSoloAdmins( saved, { @@ -603,11 +619,7 @@ export function createChannelWrites( discovery, relayAuthor, signal, - async (key, targets) => { - profilesReady ??= agents?.profiles?.ensure(targets); - await profilesReady; - return soloAgentOwnership(agents?.profiles, agents?.viewer, key); - }, + freshOwnership, ); signal.throwIfAborted(); await finishRecovery(saved.event.id, recovery); diff --git a/src/features/relay/session-agent-admission.test.ts b/src/features/relay/session-agent-admission.test.ts index 85f1d339f1..97185feeb9 100644 --- a/src/features/relay/session-agent-admission.test.ts +++ b/src/features/relay/session-agent-admission.test.ts @@ -25,6 +25,7 @@ function setup( let denied = false; let foreignRoster = false; let libraryFailure = false; + let profileResponse: "missing" | "unavailable" | undefined; let afterPublish = () => {}; let omitMembership = false; const archived: string[] = []; @@ -110,6 +111,11 @@ function setup( publish, }, query: async (filters) => { + if ( + profileResponse === "unavailable" && + filters.some((filter) => filter.kinds?.includes(0)) + ) + throw new Error("Profile read unavailable"); if ( holdRoster && filters.some( @@ -130,8 +136,9 @@ function setup( roster(agent, child, [viewer.pubkey, agent.pubkey], clock + 1), ]; const events = [ - eventDto(await agentProfile), - eventDto(await secondProfile), + ...(profileResponse === "missing" + ? [] + : [eventDto(await agentProfile), eventDto(await secondProfile)]), signed(relay, { kind: 13535, created_at: clock, @@ -160,7 +167,7 @@ function setup( child, agent: agent.pubkey, secondAgent, - async transferAgent() { + async transferAgent(receive = true) { const profile = await ownedProfile(agent, other); agentProfile = Promise.resolve( signed(agent, { @@ -170,6 +177,7 @@ function setup( created_at: clock + 10, }), ); + if (!receive) return; await owner.session.read( [{ kinds: [0], authors: [agent.pubkey], limit: 1 }], { fresh: true }, @@ -190,6 +198,9 @@ function setup( failLibraryRefresh: () => { libraryFailure = true; }, + profileResponse: (response: "missing" | "unavailable") => { + profileResponse = response; + }, afterPublish: (callback: () => void) => { afterPublish = callback; }, @@ -258,6 +269,55 @@ it.each(["other", "missing"] as const)( }, ); +it("refreshes cached ownership before choosing a new Solo agent's role", async () => { + const test = setup("private", "owner"); + try { + await test.ready(); + await test.owner.session.profiles.ensure([test.agent]); + const cached = test.owner.session.profiles.event?.(test.agent); + expect(cached).toBeDefined(); + await test.transferAgent(false); + expect(test.owner.session.profiles.event?.(test.agent)).toBe(cached); + await test.owner.session.channelWrites.addAgents(test.child, [test.agent]); + expect(test.publish).toHaveBeenCalledOnce(); + expect(test.publish.mock.calls[0]?.[0].tags).toContainEqual([ + "role", + "bot", + ]); + expect(test.owner.session.profiles.event?.(test.agent)).not.toBe(cached); + } finally { + test.owner.dispose(); + } +}); + +it.each(["missing", "unavailable"] as const)( + "does not use cached ownership for a later addition when the profile read is %s", + async (response) => { + const test = setup("private", "owner"); + try { + await test.ready(); + await test.owner.session.profiles.ensure([test.agent]); + test.profileResponse(response); + const adding = test.owner.session.channelWrites.addAgents(test.child, [ + test.agent, + ]); + if (response === "unavailable") { + await expect(adding).rejects.toThrow("Profile read unavailable"); + expect(test.publish).not.toHaveBeenCalled(); + } else { + await adding; + expect(test.publish).toHaveBeenCalledOnce(); + expect(test.publish.mock.calls[0]?.[0].tags).toContainEqual([ + "role", + "bot", + ]); + } + } finally { + test.owner.dispose(); + } + }, +); + it("chooses each new agent's role separately in a mixed-ownership Solo addition", async () => { const test = setup("private", "owner"); try { @@ -409,7 +469,10 @@ it.each([ ).not.toContain(test.agent); const first = test.publish.mock.calls[0]?.[0]; expect(first?.tags).toContainEqual(["role", addedRole]); - if ("transferred" in options) await test.transferAgent(); + if ("transferred" in options) { + await test.transferAgent(); + test.profileResponse("unavailable"); + } test.setViewerRole(retryRole); test.setDenied(false); await test.owner.session.channelWrites.addAgents(test.child, [ diff --git a/src/features/relay/solo-admins.integration.test.ts b/src/features/relay/solo-admins.integration.test.ts index ef08c057fc..9671b0cb1d 100644 --- a/src/features/relay/solo-admins.integration.test.ts +++ b/src/features/relay/solo-admins.integration.test.ts @@ -27,6 +27,8 @@ function setup() { ); let beforeLock = async () => {}; const profileOverrides = new Map(); + let omitProfiles = false; + let failProfiles = false; let journal: readonly OutgoingEvent[] = []; const events = new Map(); const roles = new Map(); @@ -54,6 +56,8 @@ function setup() { channelIdentity: true as const, media: () => undefined, query: async (filters: readonly ReadFilter[]) => { + if (failProfiles && filters.some((filter) => filter.kinds?.includes(0))) + throw new Error("Profile read unavailable"); const roster = signed(relay, { kind: 39002, content: "", @@ -63,7 +67,7 @@ function setup() { ], }); return [ - ...(await profiles).map((profile) => + ...(omitProfiles ? [] : await profiles).map((profile) => eventDto(profileOverrides.get(profile.pubkey) ?? profile), ), ...events.values(), @@ -140,6 +144,7 @@ function setup() { async transferAgent( owner: Awaited>, index: number, + receive = true, ) { const agent = agentKeys[index]; assert.exists(agent); @@ -153,12 +158,19 @@ function setup() { created_at: previous.created_at + 1, }); profileOverrides.set(agent.pubkey, changed); + if (!receive) return; await owner.session.read( [{ kinds: [0], authors: [agent.pubkey], limit: 1 }], { fresh: true }, ); expect(owner.session.profiles.event?.(agent.pubkey)?.id).toBe(changed.id); }, + omitProfiles: () => { + omitProfiles = true; + }, + failProfiles: () => { + failProfiles = true; + }, beforeLock: (run: () => Promise) => { beforeLock = run; }, @@ -368,6 +380,37 @@ it("abandons expired setup while signing is held without granting or releasing i } }); +it.each(["transferred", "missing", "unavailable"] as const)( + "refreshes cached ownership before opening grants when the relay profile is %s", + async (change) => { + const h = setup(); + const owner = await h.open(); + await owner.session.profiles.ensure(h.agents); + const cached = owner.session.profiles.event?.(h.agents[0]); + assert.exists(cached); + if (change === "transferred") await h.transferAgent(owner, 0, false); + else if (change === "missing") h.omitProfiles(); + else h.failProfiles(); + expect(owner.session.profiles.event?.(h.agents[0])).toBe(cached); + const { creation, message } = h.start(owner); + await creation.ready; + await expect( + owner.session.channelWrites.prepareOpening(h.channel), + ).rejects.toThrow( + change === "unavailable" + ? "Profile read unavailable" + : "not verified as owned", + ); + expect(h.adminPublish).not.toHaveBeenCalled(); + expect(h.events.has(message)).toBe(false); + expect( + owner.session.outbox + ?.snapshot() + .some((item) => item.recovery?.key === soloAdminKey(h.channel)), + ).toBe(true); + }, +); + it("checks the current profile inside the shared publication lock after signing", async () => { const h = setup(); const owner = await h.open(); From cd09311f757fc9e8b04e323ed8e27c6951bef8c9 Mon Sep 17 00:00:00 2001 From: Taylor Ho Date: Tue, 17 Nov 2026 11:42:43 -0800 Subject: [PATCH 15/17] test(channels): format merged access fixture Apply the pinned formatter to the merged Solo and DM roster expression so CI can continue past its static check. Co-authored-by: Carl Signed-off-by: Taylor Ho --- src/bundled/channels/ChannelMembersDialog.test.tsx | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/bundled/channels/ChannelMembersDialog.test.tsx b/src/bundled/channels/ChannelMembersDialog.test.tsx index dd0a0f5e28..ff1a9eea76 100644 --- a/src/bundled/channels/ChannelMembersDialog.test.tsx +++ b/src/bundled/channels/ChannelMembersDialog.test.tsx @@ -310,8 +310,8 @@ async function setup( roster(relay, forkId, forkMembers, clock), ] : []; - return [currentRoster(), ...fork, ...stableEvents].filter( - (event) => filters.some((filter) => matchesEvent(event, filter)), + return [currentRoster(), ...fork, ...stableEvents].filter((event) => + filters.some((filter) => matchesEvent(event, filter)), ); }); const readAgentLibrary = vi.fn( From a8f953d3fab582e053cf9e12025f15f6d6d0dedc Mon Sep 17 00:00:00 2001 From: Taylor Ho Date: Tue, 17 Nov 2026 13:45:37 -0800 Subject: [PATCH 16/17] fix(outbox): keep removed setup receipts out of stale writes Treat a known journal row as an update in the same IndexedDB transaction, including during legacy migration. A delayed creation echo cannot re-create a receipt removed by another window. Co-authored-by: Carl Signed-off-by: Taylor Ho --- src/features/relay/outbox-storage.ts | 30 ++++++- tests/browser/outbox-storage.spec.mjs | 109 ++++++++++++++++++++++++++ 2 files changed, 136 insertions(+), 3 deletions(-) diff --git a/src/features/relay/outbox-storage.ts b/src/features/relay/outbox-storage.ts index fc1cb502a3..f02f57932d 100644 --- a/src/features/relay/outbox-storage.ts +++ b/src/features/relay/outbox-storage.ts @@ -52,6 +52,7 @@ export async function purgeOutboxStorage(scope: string) { export function browserOutboxStorage(scope: string): OutboxStorage { let database: Promise | undefined; let persisted = new Map(); + let legacyIds = new Set(); let ownershipRevision = 0; const forgotten = new Map(); const open = () => (database ??= openDatabase()); @@ -63,6 +64,7 @@ export function browserOutboxStorage(scope: string): OutboxStorage { forget(id) { forgotten.set(id, ++ownershipRevision); persisted.delete(id); + legacyIds.delete(id); }, async load(options) { const db = await open(); @@ -99,10 +101,14 @@ export function browserOutboxStorage(scope: string): OutboxStorage { }, ); // A first save migrates legacy records into the per-event store. - if (!options?.readOnly) + if (!options?.readOnly) { persisted = migrated ? new Map(records.map((item) => [item.event.id, item])) : new Map(); + legacyIds = new Set( + migrated ? [] : records.map((item) => item.event.id), + ); + } return records; }, async save(operations, options) { @@ -114,6 +120,8 @@ export function browserOutboxStorage(scope: string): OutboxStorage { durability: "strict", }); const events = tx.objectStore("events"); + const partitions = tx.objectStore("partitions"); + const migration = legacyIds.size ? partitions.get(scope) : undefined; for (const [id, operation] of next) { const old = persisted.get(id); if ( @@ -129,17 +137,33 @@ export function browserOutboxStorage(scope: string): OutboxStorage { old.guarded === operation.guarded ) continue; - events.put({ scope, id, operation }); + if (id === options?.force || (!old && !legacyIds.has(id))) { + events.put({ scope, id, operation }); + } else { + // Another window may have removed this row. Check in the same + // transaction as the update, including while migrating legacy rows. + const key = events.getKey([scope, id]); + key.onsuccess = () => { + if ( + key.result !== undefined || + (!old && migration?.result !== true) + ) + events.put({ scope, id, operation }); + }; + } } for (const id of persisted.keys()) if (!next.has(id)) events.delete([scope, id]); - tx.objectStore("partitions").put(true, scope); + for (const id of legacyIds) + if (!next.has(id)) events.delete([scope, id]); + partitions.put(true, scope); tx.oncomplete = () => { // A read can relinquish an ID while this transaction is pending. // Do not let completion reclaim deletion ownership of that ID. persisted = new Map( [...next].filter(([id]) => (forgotten.get(id) ?? 0) <= revision), ); + legacyIds.clear(); resolve(); }; tx.onabort = () => diff --git a/tests/browser/outbox-storage.spec.mjs b/tests/browser/outbox-storage.spec.mjs index 38d1f7bf43..85309ff3e0 100644 --- a/tests/browser/outbox-storage.spec.mjs +++ b/tests/browser/outbox-storage.spec.mjs @@ -51,6 +51,115 @@ test("forgetting a stale receipt relinquishes its journal deletion ownership", a expect(ids).toEqual(["next", "old"]); }); +for (const journal of ["indexeddb", "legacy"]) + test(`a late creation echo respects durable setup removal (${journal})`, async ({ + page, + context, + sourceOrigin, + }) => { + await context.route(`${sourceOrigin}/outbox-storage-test`, (route) => + route.fulfill({ contentType: "text/html", body: "" }), + ); + await page.goto(`${sourceOrigin}/outbox-storage-test`); + const { finalizeEvent } = await import("nostr-tools"); + const member = "a".repeat(64); + const creation = finalizeEvent( + { + kind: 9007, + created_at: 1, + content: "", + tags: [ + ["h", "chat"], + ["p", member], + ], + }, + new Uint8Array(32).fill(7), + ); + const result = await page.evaluate( + async ({ creation, member, journal }) => { + const { browserOutboxStorage, purgeOutboxStorage } = await import( + "/src/features/relay/outbox-storage.ts" + ); + const { createOutbox } = await import("/src/features/relay/outbox.ts"); + const { soloAdminRecovery } = await import( + "/src/features/relay/solo-admins.ts" + ); + const recovery = soloAdminRecovery("chat", [member], [member]); + const scope = `setup-removal-${crypto.randomUUID()}`; + const aStore = browserOutboxStorage(scope); + const bStore = browserOutboxStorage(scope); + const operation = { + event: creation, + signed: creation, + recovery, + delivery: "accepted", + }; + if (journal === "legacy") + localStorage.setItem( + `buzz-outbox-v1:${scope}`, + JSON.stringify([operation]), + ); + else await aStore.save([operation]); + const unexpected = async () => { + throw new Error("Unexpected delivery"); + }; + const writer = { sign: unexpected, publish: unexpected }; + const a = createOutbox(creation.pubkey, writer, aStore); + const b = createOutbox(creation.pubkey, writer, bStore); + try { + await Promise.all([a.ready, b.ready]); + if ( + !a.outbox.snapshot()[0]?.recovery || + !b.outbox.snapshot()[0]?.recovery + ) + throw new Error("Both windows must hold the saved setup"); + b.observe([creation]); + await b.outbox.dismiss(creation.id, recovery); + const afterDismiss = (await bStore.load({ readOnly: true })).length; + a.observe([creation]); + let ran = false; + const publication = await a.outbox + .withRecovery(creation.id, recovery, async () => { + ran = true; + }) + .then( + () => "completed", + (error) => error.message, + ); + const completion = await a.outbox + .finishRecovery(creation.id, recovery) + .then( + () => "completed", + (error) => error.message, + ); + return { + afterDismiss, + ran, + publication, + completion, + remaining: (await bStore.load({ readOnly: true })).length, + }; + } finally { + a.dispose(); + b.dispose(); + await purgeOutboxStorage(scope); + } + }, + { creation, member, journal }, + ); + expect(result).toEqual({ + afterDismiss: 0, + ran: false, + publication: expect.stringContaining( + "removed or changed in another window", + ), + completion: expect.stringContaining( + "removed or changed in another window", + ), + remaining: 0, + }); + }); + for (const mode of ["dismiss-first", "adopt-first", "peer-accepted"]) test(`receipt adoption serializes queue consumption with dismissal (${mode})`, async ({ page, From 7797070c006f4b3162d55187a864d37290e118e4 Mon Sep 17 00:00:00 2001 From: Taylor Ho Date: Tue, 17 Nov 2026 13:45:51 -0800 Subject: [PATCH 17/17] fix(solo): let users abandon blocked opening admin setup Label setup in Outbox and confirm abandonment once the chat is created. Retain the chat and granted roles and let the user retry the original opening message. Keep the existing grant deadline and clarify recovery in help. Co-authored-by: Carl Signed-off-by: Taylor Ho --- docs/buzz-help.md | 12 +- docs/solo/README.md | 8 +- src/bundled/channels/OutboxStatus.test.tsx | 63 ++++++-- src/bundled/channels/OutboxStatus.tsx | 146 ++++++++++++------ src/features/relay/channel-writes.ts | 2 +- src/features/relay/outbox.ts | 2 +- src/features/relay/solo-admins.test.ts | 57 +++---- src/features/relay/solo-admins.ts | 75 ++++----- tests/browser/solo-admin-abandonment.spec.mjs | 44 ++++-- .../browser/solo-ownership-transfer.spec.mjs | 35 +++++ 10 files changed, 293 insertions(+), 151 deletions(-) diff --git a/docs/buzz-help.md b/docs/buzz-help.md index 073aa54ba4..452713dcdd 100644 --- a/docs/buzz-help.md +++ b/docs/buzz-help.md @@ -436,12 +436,12 @@ and are asked to sign in again in Buzz. later to a Solo chat you own also join as admins, whether from the composer or Chat access. Other people's agents get ordinary participation; later additions use Bot. Existing members keep their saved roles. - If admin setup is interrupted, Retry on the opening message - continues it without restoring later demotions or removals. If setup expires, - choose **Abandon admin setup** in Outbox to keep the chat and current roles. - This stops unfinished setup in other windows too; it does not undo grants - already accepted by the relay. You can send a new message, or start a new chat - for automatic Admin setup. Solo conversations continue at the chat's top level + If admin setup is interrupted, **Retry** on the opening message attempts to + finish it without restoring later demotions or removals. If setup is blocked, + choose **Abandon admin setup** in Outbox as soon as the chat exists. This keeps + the chat and current roles and stops unfinished setup in other windows. Then + retry the opening message, or send a new one if the original has expired. + Solo conversations continue at the chat's top level rather than requiring a new thread for each reply. Where available, use **Model and effort** in the composer before sending; Solo keeps those choices for that chat until you reset them in the same control, even if its available diff --git a/docs/solo/README.md b/docs/solo/README.md index 55b498976a..bca6662f8b 100644 --- a/docs/solo/README.md +++ b/docs/solo/README.md @@ -112,12 +112,12 @@ behavior on the label, so a rename touches copy only. admin targets across interruptions; retries reconstruct the same grants and confirm their recorded IDs before sending. A recorded grant stays complete after a later demotion or removal. Expired, unrecorded grants are never re-dated. - Outbox offers **Abandon admin setup** for the expired, delivered create: explicit - abandonment retires its recovery receipt while keeping the chat and granted + Outbox offers **Abandon admin setup** once the create is delivered. Confirming + retires its recovery receipt while keeping the chat and granted roles. Grant publication and retirement share the receipt’s durable ownership lock, so another window’s unfinished signature cannot publish after abandonment. - It sends no message automatically; the user sends a new message with current roles - or starts a new chat for automatic Admin setup. This needs no relay update + After confirming, retry the opening message with current roles or send a new + message if its signed timestamp has expired. This needs no relay update and does not migrate existing members' roles or change tool-created grants. - The Buzz tools' `channel_create` with `solo` sends the same create for any caller, including the standalone stdio server: signed by the caller, with the diff --git a/src/bundled/channels/OutboxStatus.test.tsx b/src/bundled/channels/OutboxStatus.test.tsx index d9ddd16508..a150dc8ccd 100644 --- a/src/bundled/channels/OutboxStatus.test.tsx +++ b/src/bundled/channels/OutboxStatus.test.tsx @@ -8,6 +8,7 @@ import { render, screen, waitFor, + within, } from "@testing-library/react"; import { HELD_RETRY_REFUSED, @@ -62,6 +63,33 @@ function show(item: OutgoingEvent) { return { retry, add, acknowledge }; } +it("labels a setup with unconfirmed creation and withholds abandonment and removal", () => { + const viewer = keypair(); + const agent = keypair().pubkey; + const event = signed(viewer, { + kind: 9007, + content: "", + tags: [ + ["h", "chat"], + ["p", agent], + ], + }); + show({ + event, + delivery: "unknown", + recovery: soloAdminRecovery("chat", [agent], [agent]), + }); + expect( + screen.getByText("Opening agent admin setup · Unconfirmed"), + ).toBeVisible(); + expect( + screen.queryByRole("button", { name: "Abandon admin setup" }), + ).not.toBeInTheDocument(); + expect( + screen.queryByRole("button", { name: "Remove from outbox" }), + ).not.toBeInTheDocument(); +}); + it("does not offer generic retry for guarded invitations from either profile or composer", () => { const { retry } = show({ ...invitation, guarded: true }); expect( @@ -625,20 +653,37 @@ it("abandons expired admin setup durably through Outbox and releases the chat ga />, ); fireEvent.click(screen.getByText("Outbox · 1 items")); + const remove = () => + screen.getByRole("button", { name: "Abandon admin setup" }); + await screen.findByRole("button", { name: "Abandon admin setup" }); + expect(screen.getByText(/Opening agent admin setup · Sent/)).toBeVisible(); + expect( + screen.queryByRole("button", { name: "Remove from outbox" }), + ).not.toBeInTheDocument(); + fireEvent.click(remove()); + let confirmation = screen.getByRole("alertdialog", { + name: "Abandon admin setup?", + }); + expect( + within(confirmation).getByText(/Retry your opening message/), + ).toBeVisible(); + fireEvent.click( + within(confirmation).getByRole("button", { name: "Cancel" }), + ); + expect(outbox.snapshot().some((item) => item.recovery)).toBe(true); clock.mockReturnValue(now); await expect(session.channelWrites.prepareOpening(channel)).rejects.toThrow( "expired", ); - fireEvent.click(screen.getByRole("button", { name: "Remove from outbox" })); - await screen.findByRole("button", { name: "Abandon admin setup" }); - expect(outbox.snapshot().some((item) => item.recovery)).toBe(true); - expect( - screen.getByText(/Send a new message to continue with the current roles/), - ).toBeVisible(); - const remove = () => - screen.getByRole("button", { name: "Abandon admin setup" }); failRemoval = true; fireEvent.click(remove()); + confirmation = screen.getByRole("alertdialog", { + name: "Abandon admin setup?", + }); + const confirm = within(confirmation).getByRole("button", { + name: "Abandon admin setup", + }); + fireEvent.click(confirm); expect(await screen.findByRole("alert")).toHaveTextContent( "Storage unavailable", ); @@ -647,7 +692,7 @@ it("abandons expired admin setup durably through Outbox and releases the chat ga "expired", ); failRemoval = false; - fireEvent.click(remove()); + fireEvent.click(confirm); await waitFor(() => expect(outbox.snapshot()).toHaveLength(0)); expect(records.some((item) => item.recovery)).toBe(false); expect(session.channels.get?.(channel)?.members).toContain(agent.pubkey); diff --git a/src/bundled/channels/OutboxStatus.tsx b/src/bundled/channels/OutboxStatus.tsx index 5118efb431..7a74fe1ea5 100644 --- a/src/bundled/channels/OutboxStatus.tsx +++ b/src/bundled/channels/OutboxStatus.tsx @@ -1,13 +1,18 @@ import { Button } from "../../shared/design-system/ui/Button"; +import { AlertDialog } from "../../shared/design-system/ui/AlertDialog"; import { isWorkflowOperation } from "../../features/workflows/protocol"; -import { useState, useSyncExternalStore } from "react"; +import { useRef, useState, useSyncExternalStore } from "react"; import type { RelayProfiler } from "../../features/relay/profiling"; import { RelayTimings } from "./RelayTimings"; import { PRODUCT_FEEDBACK_KIND } from "../../features/relay/product-feedback"; -import { HELD_RETRY_REFUSED, type Outbox } from "../../features/relay/outbox"; +import { + HELD_RETRY_REFUSED, + type Outbox, + type OutboxRecovery, +} from "../../features/relay/outbox"; import type { RelaySession } from "../../features/relay/session"; import { isBatchAddition } from "../../features/channel-members/members"; -import { isExpiredSoloAdminSetup } from "../../features/relay/solo-admins"; +import { soloAdminSetup } from "../../features/relay/solo-admins"; /** A batch names everyone its Retry re-adds. */ function additionLabel(tags: readonly (readonly string[])[]) { @@ -33,12 +38,31 @@ export function OutboxStatus({ outbox.snapshot, ) .filter((item) => item.event.kind !== PRODUCT_FEEDBACK_KIND) - .map((item) => ({ ...item, abandonSetup: isExpiredSoloAdminSetup(item) })); + .map((item) => { + const setup = soloAdminSetup(item); + const abandonSetup = + item.delivery === "accepted" || item.delivery === "seen" + ? setup?.recovery + : undefined; + return { ...item, setup, abandonSetup }; + }); const [error, setError] = useState(); + const [abandon, setAbandon] = useState<{ + id: string; + recovery: OutboxRecovery; + }>(); + const [abandoning, setAbandoning] = useState(false); + const summary = useRef(null); + const abandonButton = useRef(null); + const cancel = useRef(null); + const closeAbandon = () => { + setError(undefined); + setAbandon(undefined); + }; return (
    - Outbox · {operations.length} items + Outbox · {operations.length} items

    Removing an item from the outbox does not delete a sent message.

      (
    • - {item.abandonSetup + {item.setup ? "Opening agent admin setup" : item.event.kind === 9000 ? additionLabel(item.event.tags) @@ -136,53 +160,87 @@ export function OutboxStatus({ (item.delivery === "failed" || item.delivery === "unknown") && ( {HELD_RETRY_REFUSED} )}{" "} - {item.abandonSetup && ( - - Admin setup expired. Abandoning keeps this chat and any roles - already granted. Send a new message to continue with the current - roles. - - )}{" "} - {item.delivery !== "sending" && ( + {(!item.setup || item.abandonSetup || item.delivery === "failed") && + item.delivery !== "sending" && ( + + )} +
    • + ))} +
    + {abandon && ( + + abandonButton.current?.isConnected + ? abandonButton.current + : summary.current + } + pending={abandoning} + onClose={closeAbandon} + actions={ + <> + - )} - - ))} - - {error &&

    {error}

    } + + } + > + {error &&

    {error}

    } +
    + )} + {!abandon && error &&

    {error}

    }
    ); diff --git a/src/features/relay/channel-writes.ts b/src/features/relay/channel-writes.ts index 7ea9d6b3ba..dcfe01bfe8 100644 --- a/src/features/relay/channel-writes.ts +++ b/src/features/relay/channel-writes.ts @@ -603,7 +603,7 @@ export function createChannelWrites( const saved = await source.recovery(soloAdminKey(id)); if (!saved?.recovery) throw new Error( - "Chat admin setup was abandoned. Send a new message to continue.", + "Chat admin setup ended in another window. Retry this message to continue.", ); const recovery = saved.recovery; await promoteSoloAdmins( diff --git a/src/features/relay/outbox.ts b/src/features/relay/outbox.ts index c84bdcb679..5a9784980d 100644 --- a/src/features/relay/outbox.ts +++ b/src/features/relay/outbox.ts @@ -962,7 +962,7 @@ export function createOutbox( // dependent publication and successful recovery completion. if (!shared && dismissAbsent) return; throw new Error( - "This operation was removed or changed in another window. Send a new message to continue.", + "This operation was removed or changed in another window. Retry the message to continue.", ); } await run(); diff --git a/src/features/relay/solo-admins.test.ts b/src/features/relay/solo-admins.test.ts index c91e5af8d0..f4df5582a6 100644 --- a/src/features/relay/solo-admins.test.ts +++ b/src/features/relay/solo-admins.test.ts @@ -1,6 +1,6 @@ import { assert, expect, it, vi } from "vitest"; import { - isExpiredSoloAdminSetup, + soloAdminSetup, ownedSoloAgents, promoteSoloAdmins, soloAdminRecovery, @@ -226,43 +226,32 @@ it("rejects recovery that grants a nonmember admin, without signing", async () = expect(h.writer.sign).not.toHaveBeenCalled(); }); -it("limits abandonment to a valid delivered and expired opening-admin receipt", () => { +it("recognizes a valid opening-admin receipt before delivery or expiry", () => { const h = setup(); const recovery = h.creation.recovery; - const createdAt = h.creation.event.created_at; assert.exists(recovery); - assert.exists(createdAt); - const clock = vi - .spyOn(Date, "now") - .mockReturnValue(Date.now() + 16 * 60 * 1000); - try { - expect(isExpiredSoloAdminSetup(h.creation)).toBe(true); - for (const item of [ - { ...h.creation, delivery: "unknown" as const }, - { ...h.creation, recovery: undefined }, - { - ...h.creation, - recovery: { key: "another-owner", value: recovery.value }, - }, - { - ...h.creation, - recovery: { key: recovery.key, value: "invalid JSON" }, - }, - { - ...h.creation, - recovery: { - key: recovery.key, - value: JSON.stringify([keypair().pubkey]), - }, + expect(soloAdminSetup(h.creation)?.recovery).toEqual(recovery); + expect(soloAdminSetup({ ...h.creation, delivery: "unknown" })).toBeDefined(); + for (const item of [ + { ...h.creation, recovery: undefined }, + { + ...h.creation, + recovery: { key: "another-owner", value: recovery.value }, + }, + { + ...h.creation, + recovery: { key: recovery.key, value: "invalid JSON" }, + }, + { + ...h.creation, + recovery: { + key: recovery.key, + value: JSON.stringify([keypair().pubkey]), }, - { ...h.creation, event: { ...h.creation.event, kind: 9000 } }, - ]) - expect(isExpiredSoloAdminSetup(item)).toBe(false); - clock.mockReturnValue((createdAt + 14 * 60) * 1000); - expect(isExpiredSoloAdminSetup(h.creation)).toBe(false); - } finally { - clock.mockRestore(); - } + }, + { ...h.creation, event: { ...h.creation.event, kind: 9000 } }, + ]) + expect(soloAdminSetup(item)).toBeUndefined(); }); it("invalidates a verified ownership guard when its head is replaced or evicted", async () => { diff --git a/src/features/relay/solo-admins.ts b/src/features/relay/solo-admins.ts index 6e6fc53feb..6f44b47c65 100644 --- a/src/features/relay/solo-admins.ts +++ b/src/features/relay/solo-admins.ts @@ -62,34 +62,38 @@ export function soloAdminRecovery( return { key: soloAdminKey(channel), value: JSON.stringify(unique) }; } -/** Only explicit abandonment of a delivered, expired setup may waive its gate. - * No unrecorded grant can start after this deadline; recorded roles stay put. */ -export function isExpiredSoloAdminSetup(item: OutgoingEvent): boolean { +/** Recognize a saved setup independently of its delivery state. */ +export function soloAdminSetup(item: OutgoingEvent) { + try { + return readSoloAdminSetup(item); + } catch { + return; + } +} + +function readSoloAdminSetup(item: OutgoingEvent) { const create = item.event; const channel = create.tags.find(([tag]) => tag === "h")?.[1]; if ( create.kind !== 9007 || !channel || - !["accepted", "seen"].includes(item.delivery) || - item.recovery?.key !== soloAdminKey(channel) || - !(Date.now() / 1000 - (create.created_at ?? Infinity) >= 15 * 60) + item.recovery?.key !== soloAdminKey(channel) ) - return false; - try { - const admins: unknown = JSON.parse(item.recovery.value); - return ( - Array.isArray(admins) && - admins.length > 0 && - admins.every((key) => typeof key === "string" && key !== create.pubkey) && - soloAdminRecovery( - channel, - create.tags.flatMap(([tag, key]) => (tag === "p" && key ? [key] : [])), - admins, - )?.value === item.recovery.value - ); - } catch { - return false; - } + return; + const admins: unknown = JSON.parse(item.recovery.value); + if ( + Array.isArray(admins) && + admins.length > 0 && + admins.every( + (key): key is string => typeof key === "string" && key !== create.pubkey, + ) && + soloAdminRecovery( + channel, + create.tags.flatMap(([tag, key]) => (tag === "p" && key ? [key] : [])), + admins, + )?.value === item.recovery.value + ) + return { channel, admins, recovery: item.recovery }; } /** Reconstruct the exact same promotions after interruption. Their timestamp @@ -110,25 +114,12 @@ export async function promoteSoloAdmins( owned?: (key: string, targets: readonly string[]) => Promise<() => boolean>, ) { const create = creation.event; - const channel = create.tags.find(([tag]) => tag === "h")?.[1]; - const admins: unknown = JSON.parse(creation.recovery?.value ?? "null"); - if ( - create.kind !== 9007 || - !channel || - creation.recovery?.key !== soloAdminKey(channel) || - !Array.isArray(admins) || - !admins.length || - admins.some((key) => typeof key !== "string" || key === create.pubkey) || - soloAdminRecovery( - channel, - create.tags.flatMap(([tag, key]) => (tag === "p" && key ? [key] : [])), - admins, - )?.value !== creation.recovery.value - ) - throw new Error("The saved chat admin setup is invalid."); + const setup = readSoloAdminSetup(creation); + if (!setup) throw new Error("The saved chat admin setup is invalid."); + const { channel, admins } = setup; const read = (filters: Parameters[0]) => reader.read(filters, { signal, fresh: true, priority: "foreground" }); - for (const admin of admins as string[]) { + for (const admin of admins) { signal.throwIfAborted(); const template = { ...memberAdministrationTemplate(channel, create.pubkey, { @@ -157,11 +148,11 @@ export async function promoteSoloAdmins( throw new Error( "Chat admin setup expired. Abandon setup in Outbox to continue with current roles, or start a new chat.", ); - const ownership = await owned?.(admin, admins as string[]); + const ownership = await owned?.(admin, admins); const checkOwnership = () => { if (!ownership?.()) throw new Error( - "An opening agent is not verified as owned by the chat creator. Check chat access before retrying.", + "An opening agent is not verified as owned by the chat creator. Retry this message or choose Abandon admin setup in Outbox to continue with current roles.", ); }; checkOwnership(); @@ -185,7 +176,7 @@ export async function promoteSoloAdmins( )?.[3]; if (!role || !["member", "bot", "admin"].includes(role)) throw new Error( - "An opening agent's access changed. Check chat access before retrying.", + "An opening agent's access changed. Choose Abandon admin setup in Outbox to continue with current roles.", ); checkOwnership(); const signed = await writer.sign(template, signal); diff --git a/tests/browser/solo-admin-abandonment.spec.mjs b/tests/browser/solo-admin-abandonment.spec.mjs index d2f696e9d4..2e2469f118 100644 --- a/tests/browser/solo-admin-abandonment.spec.mjs +++ b/tests/browser/solo-admin-abandonment.spec.mjs @@ -149,6 +149,12 @@ for (const mode of ["cross-window", "same-window", "failed-storage"]) const scope = `https://primary.example:${app.viewer}`; app.report.setupReceiverTime = createdAt + 895; await page.clock.setFixedTime(new Date((createdAt + 899) * 1000)); + if (mode === "same-window") { + await page.setViewportSize({ width: 840, height: 900 }); + await page.addInitScript(() => { + localStorage.setItem("buzz-font-scale.v1", "1.5"); + }); + } await page.addInitScript( ({ scope, creation, message, recovery }) => { localStorage.setItem( @@ -184,20 +190,20 @@ for (const mode of ["cross-window", "same-window", "failed-storage"]) const row = a.getByRole("listitem").filter({ hasText: "Opening work" }); await row.getByRole("button", { name: "Retry", exact: true }).click(); await expect.poll(() => signingStarted).toBe(true); - await page.clock.setFixedTime(new Date((createdAt + 900) * 1000)); + if (mode !== "same-window") + await page.clock.setFixedTime(new Date((createdAt + 900) * 1000)); other = mode === "same-window" ? page : await context.newPage(); if (other !== page) { app.watchPageErrors(other); await other.clock.setFixedTime(new Date((createdAt + 900) * 1000)); } const b = other === page ? a : await openOutbox(other, app.origin); - if (mode === "same-window") { - // The view was opened before expiry: first click exposes explicit consent. - await b - .getByRole("button", { name: "Remove from outbox", exact: true }) - .first() - .click(); - } + const setup = b.getByRole("listitem").filter({ + hasText: "Opening agent admin setup", + }); + await expect( + setup.getByRole("button", { name: "Remove from outbox" }), + ).toHaveCount(0); if (mode === "failed-storage") await other.evaluate( ({ scope, id }) => { @@ -212,11 +218,29 @@ for (const mode of ["cross-window", "same-window", "failed-storage"]) }, { scope, id: creation.id }, ); - await b + const abandon = setup.getByRole("button", { + name: "Abandon admin setup", + exact: true, + }); + await abandon.click(); + const confirmation = other.getByRole("alertdialog", { + name: "Abandon admin setup?", + }); + if (mode === "same-window") { + const cancel = confirmation.getByRole("button", { + name: "Cancel", + exact: true, + }); + await expect(cancel).toBeFocused(); + await cancel.click(); + await expect(abandon).toBeFocused(); + await abandon.click(); + } + await confirmation .getByRole("button", { name: "Abandon admin setup", exact: true }) .click(); if (mode === "failed-storage") - await expect(b.getByRole("alert")).toBeVisible(); + await expect(confirmation.getByRole("alert")).toBeVisible(); else await expect( b.getByRole("button", { name: "Abandon admin setup", exact: true }), diff --git a/tests/browser/solo-ownership-transfer.spec.mjs b/tests/browser/solo-ownership-transfer.spec.mjs index 256c3cb770..ef29b864a5 100644 --- a/tests/browser/solo-ownership-transfer.spec.mjs +++ b/tests/browser/solo-ownership-transfer.spec.mjs @@ -6,6 +6,7 @@ const channel = "11111111-1111-4111-8111-111111111111"; const chat = "33333333-3333-4333-8333-333333333333"; test.use({ productionBroker: true, + colorScheme: "dark", pluginFixtures: true, openingAdminSetup: true, channelLifecycle: true, @@ -237,6 +238,40 @@ for (const opening of [true, false]) message.id, ), ).toContain("not verified as owned"); + const setup = outbox.getByRole("listitem").filter({ + hasText: "Opening agent admin setup", + }); + await setup.screenshot({ + path: info.outputPath("OPENING_ADMIN_SETUP_OUTBOX.png"), + }); + await setup + .getByRole("button", { name: "Abandon admin setup" }) + .click(); + const confirmation = page.getByRole("alertdialog", { + name: "Abandon admin setup?", + }); + await confirmation.screenshot({ + path: info.outputPath("ABANDON_ADMIN_SETUP.png"), + }); + await confirmation + .getByRole("button", { name: "Abandon admin setup" }) + .click(); + await expect(setup).toHaveCount(0); + await outbox + .getByRole("listitem") + .filter({ hasText: message.content }) + .getByRole("button", { name: "Retry", exact: true }) + .click(); + await expect + .poll(() => + app.report.publications + .filter(({ event }) => event.kind === 9) + .map(({ event }) => event), + ) + .toEqual([message]); + expect( + app.report.publications.filter(({ event }) => event.kind === 9000), + ).toHaveLength(1); } await page.screenshot({ path: info.outputPath("RECEIVED_OWNERSHIP_TRANSFER.png"),