diff --git a/browser-host/relay-authority.test.mjs b/browser-host/relay-authority.test.mjs index f2a1905fd0..48a57ef6c5 100644 --- a/browser-host/relay-authority.test.mjs +++ b/browser-host/relay-authority.test.mjs @@ -80,6 +80,24 @@ it.each([ } }, ); +it.each([ + [{ self }, true], + [{ self, supported_extensions: ["nip-ar"] }, true], + // Without `self` no list can be verified. + [{ pubkey: self }, false], +])( + "offers pin commands where the relay names itself: %j", + async (nip11, supported) => { + const h = await harness(() => Response.json(nip11)); + try { + const transport = await h.connect(); + expect(transport.writer.kinds.includes(40010)).toBe(supported); + expect(transport.writer.kinds.includes(40011)).toBe(supported); + } finally { + await h.close(); + } + }, +); it.each([ ["explicit self", { self, pubkey: contact }, self, self], ["self without contact", { self }, self, self], diff --git a/browser-host/relay-broker-live.test.mjs b/browser-host/relay-broker-live.test.mjs index 6ae191baf7..1cc52a537e 100644 --- a/browser-host/relay-broker-live.test.mjs +++ b/browser-host/relay-broker-live.test.mjs @@ -1997,6 +1997,71 @@ test.each([ }, ); +test.each([ + [40010, 400], + [40011, 400], + // Other kinds keep the unconfirmed answer. + [9000, 503], +])( + "a relay without pins refuses kind %i, answered %i", + async (kind, status) => { + const h = await harness(); + let traffic; + try { + browserFetch(h.base); + const transport = await connectBrokerTransport(h.base); + traffic = transport.subscribe(callbacks); + await until(() => h.requests.length >= 1 && !!traffic.identity()); + const channel = "00000000-0000-4000-8000-000000000001"; + const event = await transport.writer.sign( + { + kind, + content: "", + created_at: Math.floor(Date.now() / 1000), + tags: + kind === 9000 + ? [ + ["h", channel], + ["p", "a".repeat(64)], + ] + : [ + ["h", channel], + ["e", "a".repeat(64)], + ["client-id", "local"], + ], + }, + new AbortController().signal, + ); + const result = fetch(`${h.base}/api/relay/publish`, { + method: "POST", + headers: { + "Content-Type": "application/json", + "X-Buzz-Live-ID": traffic.identity(), + }, + body: JSON.stringify(event), + }); + await until(() => h.publications.length === 1); + await h.sockets[0].receive([ + "OK", + event.id, + false, + "restricted: unknown event kind", + ]); + const response = await result; + expect(response.status).toBe(status); + expect(await response.json()).toEqual( + status === 400 + ? { error: "restricted: unknown event kind" } + : { error: "Socket publication could not be confirmed", sent: false }, + ); + } finally { + traffic?.dispose(); + vi.unstubAllGlobals(); + await h.close(); + } + }, +); + test("publication diagnostics distinguish missing and mismatched live owner without dispatch", async () => { const logger = getLogger("relay-broker"); const reporters = [...logger.options.reporters]; diff --git a/browser-host/relay-broker.mjs b/browser-host/relay-broker.mjs index d1c72f4cbc..9f348fbcef 100644 --- a/browser-host/relay-broker.mjs +++ b/browser-host/relay-broker.mjs @@ -361,6 +361,9 @@ async function relayAuthority(fetch, relay) { searchSort: Array.isArray(nip11.supported_extensions) && nip11.supported_extensions.includes("buzz-search-sort"), + // NIP-PM is not advertised: a relay without it refuses the commands. Its + // lists are verified by `self`, so without it no pin can be shown. + pins: nip11.self === author, ...(readSnapshotCommunity(nip11.read_state_snapshot) ? { readStateCommunity: readSnapshotCommunity(nip11.read_state_snapshot) } : {}), @@ -575,6 +578,36 @@ export function validReport(event) { ].includes(target[2]) ); } +/** A pin (40010) or unpin (40011): one channel and one message, as native + * `valid_pin_command`; the relay decides who may pin what. */ +export function validPinCommand(event) { + if ( + ![40010, 40011].includes(event?.kind) || + event.content !== "" || + !Number.isSafeInteger(event.created_at) || + event.created_at < 0 || + !Array.isArray(event.tags) || + !event.tags.every( + (tag) => + Array.isArray(tag) && + tag.length === 2 && + tag.every((value) => typeof value === "string") && + ["h", "e", "client-id"].includes(tag[0]), + ) + ) + return false; + const named = (name) => event.tags.filter((tag) => tag[0] === name); + const [channel] = named("h"); + const [target] = named("e"); + return ( + named("h").length === 1 && + channel[1].length > 0 && + channel[1].length <= 256 && + named("e").length === 1 && + /^[0-9a-f]{64}$/.test(target[1]) && + named("client-id").length <= 1 + ); +} /** Channel-local NIP-09 removal; the relay enforces authorship of each target. */ export function validMessageDeletion(event) { if ( @@ -1737,6 +1770,7 @@ export function relayBrokerPlugin({ ...((await getAuthority(relay)).artifactSupport ? [45010] : []), ...WORKFLOW_KINDS, ...((await getAuthority(relay)).channelCreation ? [9007] : []), + ...((await getAuthority(relay)).pins ? [40010, 40011] : []), ], channelLifecycle: true, channelDetails: true, @@ -3172,6 +3206,12 @@ export function relayBrokerPlugin({ error: "Report rejected", sent: false, }); + } else if ([40010, 40011].includes(filters?.kind)) { + if (!validPinCommand(filters)) + return json(res, 400, { + error: "Invalid pin command", + sent: false, + }); } else if (filters?.kind === 20002) { if (!validTypingTemplate(filters)) return json(res, 400, { @@ -3288,10 +3328,13 @@ export function relayBrokerPlugin({ failure.refusal?.startsWith("conflict:"); // Answer a proven validation refusal as the relay's HTTP API does, // 400 with its bounded text, so every publish path shows the same - // reason. The text goes to this client only, never to the log. + // reason. The text goes to this client only, never to the log. A + // relay without NIP-PM refuses pin commands as `restricted:`. if ( failure?.sent === false && - failure.reason?.startsWith("invalid:") && + (failure.reason?.startsWith("invalid:") || + ([40010, 40011].includes(filters.kind) && + failure.reason?.startsWith("restricted:"))) && !( readPublishing && failure.refusal === READ_STATE_TIMESTAMP_REFUSAL diff --git a/browser-host/relay-broker.test.mjs b/browser-host/relay-broker.test.mjs index ac3cacf050..8e1143f18a 100644 --- a/browser-host/relay-broker.test.mjs +++ b/browser-host/relay-broker.test.mjs @@ -4,6 +4,7 @@ import { createUpstream, validFilters, validMessageTemplate, + validPinCommand, } from "./relay-broker.mjs"; test("read broker accepts non-channel finite reads without relaxing filter budgets", () => { @@ -230,3 +231,33 @@ test("workflow list batches alone may exceed four filters, with 128 unique chann ]) assert.equal(validFilters(invalid), false); }); + +test("pin commands name one channel and one message, with only a client id besides", () => { + const pin = { + kind: 40010, + created_at: 1, + content: "", + tags: [ + ["h", "channel"], + ["e", "a".repeat(64)], + ["client-id", "local"], + ], + }; + assert.equal(validPinCommand(pin), true); + assert.equal(validPinCommand({ ...pin, kind: 40011 }), true); + for (const invalid of [ + { ...pin, kind: 9 }, + { ...pin, content: "x" }, + { ...pin, tags: pin.tags.slice(1) }, + { ...pin, tags: [pin.tags[0], pin.tags[2]] }, + { ...pin, tags: [...pin.tags, ["h", "other"]] }, + { ...pin, tags: [...pin.tags, ["e", "b".repeat(64)]] }, + { ...pin, tags: [...pin.tags, ["client-id", "again"]] }, + { ...pin, tags: [...pin.tags, ["p", "c".repeat(64)]] }, + { ...pin, tags: [["h", ""], pin.tags[1]] }, + { ...pin, tags: [["h", "x".repeat(257)], pin.tags[1]] }, + { ...pin, tags: [pin.tags[0], ["e", "A".repeat(64)]] }, + { ...pin, tags: [pin.tags[0], ["e", "a".repeat(64), "relay"]] }, + ]) + assert.equal(validPinCommand(invalid), false); +}); diff --git a/browser-host/workflow-broker.test.mjs b/browser-host/workflow-broker.test.mjs index 3c3fd9fe21..38c13515c8 100644 --- a/browser-host/workflow-broker.test.mjs +++ b/browser-host/workflow-broker.test.mjs @@ -397,7 +397,7 @@ it("existing backend signs only canonical workflow sign/publish with exact own e live = await openBrokerSocket(t); expect(t.writer.kinds).toEqual([ 30315, 30030, 7, 9, 40003, 42000, 9000, 9001, 30078, 30175, 30177, 30178, - 40100, 1984, 30620, 46020, 5, + 40100, 1984, 30620, 46020, 5, 40010, 40011, ]); for (const input of [ template(), diff --git a/crates/agent-controller/src/app_agent.rs b/crates/agent-controller/src/app_agent.rs index 632e6c9717..c105dc78ef 100644 --- a/crates/agent-controller/src/app_agent.rs +++ b/crates/agent-controller/src/app_agent.rs @@ -15,13 +15,13 @@ use std::path::{Path, PathBuf}; /// (9), a channel member change (9000, 9001), edit (9002), creation (9007), /// deletion (9008), join (9021) or leave (9022), typing (20002), an edit of its /// own message (40003), a shared note (30023), a channel canvas (40100), a -/// request to open a DM (41010), a repository announcement (30617) or an -/// artifact revision (45010). The relay decides which channel changes and -/// artifact edits it may make. Its profile (0) is the app's, and -/// its memory (30174) is written by `memory`. -const KINDS: [u16; 17] = [ - 5, 7, 9, 9000, 9001, 9002, 9007, 9008, 9021, 9022, 20002, 30023, 30617, 40003, 40100, 41010, - 45010, +/// pin or unpin (40010, 40011), a request to open a DM (41010), a repository +/// announcement (30617) or an artifact revision (45010). The relay decides +/// which channel changes, pins and artifact edits it may make. Its profile (0) +/// is the app's, and its memory (30174) is written by `memory`. +const KINDS: [u16; 19] = [ + 5, 7, 9, 9000, 9001, 9002, 9007, 9008, 9021, 9022, 20002, 30023, 30617, 40003, 40010, 40011, + 40100, 41010, 45010, ]; /// Content of a live channel Canvas (40100), in UTF-8 bytes. Mirrors diff --git a/crates/agent-controller/src/app_agent/tests.rs b/crates/agent-controller/src/app_agent/tests.rs index b9869f7fe5..98e45d74f9 100644 --- a/crates/agent-controller/src/app_agent/tests.rs +++ b/crates/agent-controller/src/app_agent/tests.rs @@ -406,8 +406,8 @@ fn signs_only_bounded_kinds_with_the_saved_attestation() { let key = agent.read_key(&credentials).unwrap(); let saved: Vec = serde_json::from_str(&agent.auth).unwrap(); for kind in [ - 5, 7, 9, 9000, 9001, 9002, 9007, 9008, 9021, 9022, 20002, 30023, 30617, 40003, 40100, - 41010, 45010, + 5, 7, 9, 9000, 9001, 9002, 9007, 9008, 9021, 9022, 20002, 30023, 30617, 40003, 40010, + 40011, 40100, 41010, 45010, ] { let tags = vec![ vec!["auth".to_owned(), "forged".to_owned()], diff --git a/docs/buzz-help.md b/docs/buzz-help.md index f74ba87c2d..a00e0bde85 100644 --- a/docs/buzz-help.md +++ b/docs/buzz-help.md @@ -96,6 +96,12 @@ if that desktop app is up and running. - **Messages.** Hover or right-click a message to react, **Reply**, copy a link, forward it, or start a chat about it. On an agent's reply, **View activity** shows what it did. +- **Pins.** **Pin to channel** (**Pin to DM** in a DM) in a message's More + menu adds it to the pin list, up to 250; the pin button in the header lists + them. Solo chats have no pins. + Anyone who can post can pin or unpin any message. Forum posts can't be + pinned. A community that doesn't take pins refuses them, and Buzz says so. + Agents pin with the `pin` tool. - **Composer.** **#** links a channel. On desktop, **!** gives your agents a folder and **/** a skill. Attach files by pasting or dragging them in. - **Drafts.** Every message box open on a conversation shares its draft. A box diff --git a/src-tauri/src/credential_service/policy.rs b/src-tauri/src/credential_service/policy.rs index 65257a04b6..c952b9a61b 100644 --- a/src-tauri/src/credential_service/policy.rs +++ b/src-tauri/src/credential_service/policy.rs @@ -14,9 +14,10 @@ pub(super) enum Verdict { } /// Everyday work: messages and their edits, pins, bookmarks, schedules and -/// reminders (9, 40002–40008), reactions (7), shared notes (30023), forum posts, -/// votes and comments (45001–45003), presence and typing (20001–20003), read -/// state (30078) and user status (30315), the identity's own lists (10000, +/// reminders (9, 40002–40008), channel pin commands (40010, 40011), reactions +/// (7), shared notes (30023), forum posts, votes and comments (45001–45003), +/// presence and typing (20001–20003), read state (30078) and user status +/// (30315), the identity's own lists (10000, /// 10001, 10003, 10030, 30000, 30003, 30030), canvases (40100), artifacts /// (45010), git patches, pull requests, issues and statuses (1617–1633), DM /// open and hide (41010, 41012), archive requests (9035, 9036), workflow @@ -25,8 +26,8 @@ pub(super) enum Verdict { const ORDINARY: &[u16] = &[ 7, 9, 1617, 1618, 1619, 1621, 1630, 1631, 1632, 1633, 9035, 9036, 10000, 10001, 10003, 10030, 20001, 20002, 20003, 24200, 30000, 30003, 30023, 30030, 30078, 30174, 30315, 40002, 40003, - 40004, 40005, 40006, 40007, 40008, 40100, 41010, 41012, 43001, 43002, 43003, 43004, 43005, - 43006, 45001, 45002, 45003, 45010, 46020, + 40004, 40005, 40006, 40007, 40008, 40010, 40011, 40100, 41010, 41012, 43001, 43002, 43003, + 43004, 43005, 43006, 45001, 45002, 45003, 45010, 46020, ]; /// Changes to who the identity is, what it controls or what others see about diff --git a/src-tauri/src/credential_service/tests.rs b/src-tauri/src/credential_service/tests.rs index 81c752365f..6155decb84 100644 --- a/src-tauri/src/credential_service/tests.rs +++ b/src-tauri/src/credential_service/tests.rs @@ -950,7 +950,9 @@ fn the_policy_binds_each_proof_to_the_community() { #[test] fn every_kind_has_one_class() { let classes = |kind| classify(kind, &[], NOW, NOW, RELAY); - for kind in [7, 9, 30174, 20001, 24200, 40002, 41010, 45010, 46020, 1621] { + for kind in [ + 7, 9, 30174, 20001, 24200, 40002, 40010, 40011, 41010, 45010, 46020, 1621, + ] { assert_eq!(classes(kind), Verdict::Sign, "{kind}"); } for kind in [ diff --git a/src-tauri/src/relay.rs b/src-tauri/src/relay.rs index 4905aa80d2..aca55a213b 100644 --- a/src-tauri/src/relay.rs +++ b/src-tauri/src/relay.rs @@ -466,6 +466,10 @@ fn validate_event(community: &str, event: &EventTemplate) -> Result<()> { { return Err("Invalid agent presence".into()); } + } else if matches!(event.kind, 40010 | 40011) { + if !valid_pin_command(event) { + return Err("Invalid pin command".into()); + } } else if matches!(event.kind, 9030..=9032) { if !valid_member_command(event) { return Err("Invalid member change".into()); @@ -596,6 +600,26 @@ fn valid_reaction_deletion(event: &EventTemplate) -> bool { .any(|tag| tag[0] == "e" && hex_key(&tag[1])) } +/** A pin (40010) or unpin (40011): one channel and one message, as the + * broker's `validPinCommand`; the relay decides who may pin what. */ +fn valid_pin_command(event: &EventTemplate) -> bool { + let tag = |name: &str| { + event + .tags + .iter() + .filter(|tag| tag.first().map(String::as_str) == Some(name)) + .collect::>() + }; + event.content.is_empty() + && event + .tags + .iter() + .all(|tag| tag.len() == 2 && matches!(tag[0].as_str(), "h" | "e" | "client-id")) + && matches!(tag("h").as_slice(), [h] if !h[1].is_empty() && h[1].len() <= 256) + && matches!(tag("e").as_slice(), [e] if hex_key(&e[1])) + && tag("client-id").len() <= 1 +} + /** Keep the shared kind-5 writer aligned with the broker's channel-local deletion shape. */ fn valid_message_deletion(event: &EventTemplate) -> bool { if event.kind != 5 diff --git a/src-tauri/src/relay/tests.rs b/src-tauri/src/relay/tests.rs index 6d03ca0dbc..201d1f0009 100644 --- a/src-tauri/src/relay/tests.rs +++ b/src-tauri/src/relay/tests.rs @@ -5167,3 +5167,50 @@ fn huddle_end_requires_one_parent_and_a_distinct_room() { assert!(validate_event("https://relay.test", &event).is_err()); } } + +#[test] +fn pin_commands_name_one_channel_and_one_message() { + let pin = |tags: Vec>| EventTemplate { + kind: 40010, + created_at: 1, + content: "".into(), + tags: tags + .into_iter() + .map(|tag| tag.into_iter().map(str::to_owned).collect()) + .collect(), + }; + let target = "a".repeat(64); + let valid = vec![ + vec!["h", "channel"], + vec!["e", &target], + vec!["client-id", "x"], + ]; + assert!(validate_event("https://relay.test", &pin(valid.clone())).is_ok()); + let mut unpin = pin(valid.clone()); + unpin.kind = 40011; + assert!(validate_event("https://relay.test", &unpin).is_ok()); + let mut content = pin(valid.clone()); + content.content = "x".into(); + assert!(validate_event("https://relay.test", &content).is_err()); + let upper = "A".repeat(64); + let long = "x".repeat(257); + for tags in [ + vec![vec!["e", &target]], + vec![vec!["h", "channel"]], + vec![vec!["h", "channel"], vec!["h", "other"], vec!["e", &target]], + vec![vec!["h", "channel"], vec!["e", &target], vec!["e", &target]], + vec![vec!["h", "channel"], vec!["e", &upper]], + vec![vec!["h", ""], vec!["e", &target]], + vec![vec!["h", &long], vec!["e", &target]], + vec![vec!["h", "channel"], vec!["e", &target, "relay"]], + vec![vec!["h", "channel"], vec!["e", &target], vec!["p", &target]], + vec![ + vec!["h", "channel"], + vec!["e", &target], + vec!["client-id", "x"], + vec!["client-id", "y"], + ], + ] { + assert!(validate_event("https://relay.test", &pin(tags)).is_err()); + } +} diff --git a/src/bundled/channels/ChannelsPage.tsx b/src/bundled/channels/ChannelsPage.tsx index 8ccc844988..f70cd7e3d4 100644 --- a/src/bundled/channels/ChannelsPage.tsx +++ b/src/bundled/channels/ChannelsPage.tsx @@ -2188,6 +2188,7 @@ function ChannelWorkspace({ outbox={queries.outbox} profiling={queries.profiling} memberAdditions={queries.memberAdditions} + pins={queries} /> ) : ( diff --git a/src/bundled/channels/OutboxStatus.test.tsx b/src/bundled/channels/OutboxStatus.test.tsx index 2eca4f4545..ca6327a210 100644 --- a/src/bundled/channels/OutboxStatus.test.tsx +++ b/src/bundled/channels/OutboxStatus.test.tsx @@ -28,6 +28,12 @@ import { eventDto, type RelayEvent } from "../../features/relay/events"; import type { RelayWriter } from "../../features/relay/transport"; import { createRelayProfiler } from "../../features/relay/profiling"; import { soloChatLinkMessage } from "../../features/solo/share"; +import { + EXPIRED_PIN_RECOVERY, + PIN_KIND, + pinLists, + type PinSource, +} from "../../features/relay/pins"; import { OutboxStatus } from "./OutboxStatus"; afterEach(cleanup); @@ -63,6 +69,57 @@ function show(item: OutgoingEvent) { return { retry, add, acknowledge }; } +it("offers no retry for a pin command refused as too old and reads its list again", async () => { + const read = vi.fn(async () => []); + const pins = { + relayAuthor: "a".repeat(64), + workflowAuthority: "a".repeat(64), + read, + readPage: async () => ({ events: [], relayCount: 0 }), + subscribeLive: () => () => {}, + live: { snapshot: () => ({ heads: [] }), subscribe: () => () => {} }, + } satisfies PinSource; + // A view keeps this channel's list. + pinLists(pins).subscribe("room", () => {}); + await waitFor(() => expect(read).toHaveBeenCalledTimes(1)); + const retry = vi.fn(); + const items = [ + { + event: { + id: "pin", + kind: PIN_KIND, + content: "", + tags: [ + ["h", "room"], + ["e", "1".repeat(64)], + ], + }, + delivery: "unknown", + error: "Retry blocked: invalid: event timestamp too far from server time", + } as OutgoingEvent, + ]; + render( + items, + subscribe: () => () => {}, + retry, + dismiss: vi.fn(), + } as unknown as Outbox + } + profiling={createRelayProfiler()} + memberAdditions={{ add: vi.fn(async () => {}) }} + pins={pins} + />, + ); + fireEvent.click(screen.getByText("Outbox · 1 items")); + expect(screen.getByText(EXPIRED_PIN_RECOVERY)).toBeInTheDocument(); + expect(screen.queryByRole("button", { name: "Retry" })).toBeNull(); + await waitFor(() => expect(read).toHaveBeenCalledTimes(2)); + expect(retry).not.toHaveBeenCalled(); +}); + it("labels a setup with unconfirmed creation and withholds abandonment and removal", () => { const viewer = keypair(); const agent = keypair().pubkey; diff --git a/src/bundled/channels/OutboxStatus.tsx b/src/bundled/channels/OutboxStatus.tsx index 734720e654..b6c116456c 100644 --- a/src/bundled/channels/OutboxStatus.tsx +++ b/src/bundled/channels/OutboxStatus.tsx @@ -14,6 +14,8 @@ import { type AbandonableSetup, } from "../../features/solo/AdminSetupRecovery"; import { migrationSource } from "../../features/relay/migration"; +import { refusedPinCommand, type PinSource } from "../../features/relay/pins"; +import { RefusedPin } from "../../features/messages/RefusedPin"; /** A batch names everyone its Retry re-adds. */ function additionLabel(tags: readonly (readonly string[])[]) { @@ -28,10 +30,13 @@ export function OutboxStatus({ outbox, profiling, memberAdditions, + pins, }: { outbox: Outbox; profiling: RelayProfiler; memberAdditions: Pick; + /** Reads a pin list again after its command is refused as too old. */ + pins?: PinSource | undefined; }) { const operations = useSyncExternalStore( outbox.subscribe, @@ -82,6 +87,7 @@ export function OutboxStatus({ {!isWorkflowOperation(item.event) && !item.guarded && !item.held && + !refusedPinCommand(item) && (item.delivery === "failed" || item.delivery === "unknown" || // A kept batch still names someone unsettled. @@ -154,6 +160,9 @@ export function OutboxStatus({ (item.delivery === "failed" || item.delivery === "unknown") && ( {HELD_RETRY_REFUSED} )}{" "} + {refusedPinCommand(item) && ( + + )}{" "} {(!item.setup || item.abandonSetup || item.delivery === "failed") && item.delivery !== "sending" && ( } + /> + ); + if ( + pins.status === "loading" || + (pinned.status === "loading" && !pinned.rows.length && pins.ids.length) + ) + return ( +

+ Loading pinned messages… +

+ ); + if (!pinned.rows.length) + return ( + } + title="No pinned messages" + {...(pinnable && { + description: "Pin a message from its More menu to keep it here.", + })} + /> + ); + return ( + <> + {/* A failed refresh retries in the background, keeping these rows. */} + {error && ( +

+ {error} +

+ )} +
    + {pinned.rows.map((row) => { + const name = resolveName( + row.authorId, + profiles.get(row.authorId)?.name ?? row.authorId.slice(0, 10), + ); + return ( +
  • + + {canUnpin && pinnable && ( +
  • + ); + })} +
+ + ); +} + +export function registerPins(ctx: Context) { + function Panel({ channelContext, close }: PanelProps) { + const state = useSyncExternalStore(ctx.relay.subscribe, ctx.relay.snapshot); + const ready = + !!channelContext && + state.status === "ready" && + state.scope === channelContext.scope; + return ( +
+
+ ); + } + ctx.panels.register({ + id: "pins", + title: "Pinned", + matches: () => false, + channelLauncher: (props) => , + channelPlacement: "side", + component: Panel, + }); +} diff --git a/src/buzz-mcp/tools.test.ts b/src/buzz-mcp/tools.test.ts index 6a8a77d9c2..3df0abf628 100644 --- a/src/buzz-mcp/tools.test.ts +++ b/src/buzz-mcp/tools.test.ts @@ -774,6 +774,39 @@ it("tags a community emoji reaction and refuses a shortcode outside the palette" expect(published).toHaveLength(2); }); +it("pins and unpins a message in its own channel", async () => { + const { client, published } = fake([ + ...community, + event({ id: root, pubkey: bob }), + ]); + expect(await callTool(client, {}, "pin", { id: root })).toContain("pinned"); + expect(await callTool(client, {}, "pin", { id: root, off: true })).toContain( + "unpinned", + ); + expect(published).toEqual([ + { + kind: 40010, + content: "", + tags: [ + ["h", "chan"], + ["e", root], + ["client-id", expect.any(String)], + ], + }, + { + kind: 40011, + content: "", + tags: [ + ["h", "chan"], + ["e", root], + ["client-id", expect.any(String)], + ], + }, + ]); + // Each command is its own event. + expect(published[0]?.tags.at(-1)).not.toEqual(published[1]?.tags.at(-1)); +}); + it("reads no emoji sets for a message without a shortcode", async () => { const { client } = fake(community); await callTool(client, { channel: "chan" }, "send", { diff --git a/src/buzz-mcp/tools.ts b/src/buzz-mcp/tools.ts index c310e71835..ae9ace26c1 100644 --- a/src/buzz-mcp/tools.ts +++ b/src/buzz-mcp/tools.ts @@ -268,6 +268,12 @@ export const TOOLS: readonly Tool[] = [ { id: str, emoji: str, off: { type: "boolean" } }, ["id", "emoji"], ), + tool( + "pin", + "Pin a message to its channel for everyone; off unpins it.", + { id: str, off: { type: "boolean" } }, + ["id"], + ), tool("read", "Read a thread (default: current) or a channel's latest.", { channel: str, thread: str, @@ -888,6 +894,23 @@ const HANDLERS: Readonly> = { return "removed"; }, + async pin(tools, args) { + const id = required(args, "id"); + const channel = tag(await tools.event(id), "h"); + if (!channel) throw new Error(`${id} is not a channel message.`); + await tools.client.publish({ + kind: args.off === true ? 40011 : 40010, + content: "", + tags: [ + ["h", channel], + ["e", id], + // NIP-PM: each new command is a distinct event. + ["client-id", crypto.randomUUID()], + ], + }); + return args.off === true ? "unpinned" : "pinned"; + }, + async read(tools, args) { const { client, context } = tools; // A session that kept an older tool list may still search through read. diff --git a/src/features/messages/MessageManagement.test.tsx b/src/features/messages/MessageManagement.test.tsx index f47bdcf672..6d15580f69 100644 --- a/src/features/messages/MessageManagement.test.tsx +++ b/src/features/messages/MessageManagement.test.tsx @@ -33,10 +33,13 @@ import { createRelaySession } from "../relay/session"; import { followUpRecovery } from "./follow-up-storage"; import { readJournal, type ReadJournal } from "../relay/read-state-storage"; import { + OLD_EVENT_NOT_FOUND, PublishRejected, type OutboxStorage, type OutgoingEvent, } from "../relay/outbox"; +import { EXPIRED_PIN_RECOVERY, UNSUPPORTED_PIN_RECOVERY } from "../relay/pins"; +import { acceptPublish } from "../relay/transport"; import { keypair, message, @@ -83,7 +86,16 @@ async function fixture( { outboxStorage = { load: () => [], save() {} }, viewer = keypair(), - }: { outboxStorage?: OutboxStorage; viewer?: Key } = {}, + pins, + channelTags = [], + }: { + outboxStorage?: OutboxStorage; + /** Extra `t` tags on the room's metadata, as for a DM or Solo chat. */ + channelTags?: string[][]; + viewer?: Key; + /** With a relay that supports pins, the ids its list names. */ + pins?: (original: RelayEvent) => string[]; + } = {}, ) { let role = viewerRole, rosterTime = 1700000000; @@ -179,6 +191,8 @@ async function fixture( : {}), viewer: viewer.pubkey, relayAuthor: relay.pubkey, + // The explicit NIP-11 `self` that pin lists are verified by. + archiveAuthority: relay.pubkey, media: () => undefined, ...(withAttachments ? { @@ -197,7 +211,7 @@ async function fixture( if (shareRead && filter.ids?.includes(original.id)) return shareRead; if (filter.kinds?.includes(39000) || filter.kinds?.includes(39002)) return [ - metadata(relay, "room", "Room"), + metadata(relay, "room", "Room", undefined, channelTags), signed(relay, { ...roster(relay, "room", [viewer.pubkey, peer.pubkey]), created_at: rosterTime, @@ -208,6 +222,15 @@ async function fixture( ], }), ]; + if (pins && filter.kinds?.includes(30623)) + return [ + signed(relay, { + kind: 30623, + content: "", + created_at: 1700000000, + tags: [["d", "room"], ...pins(original).map((id) => ["e", id])], + }), + ]; if (filter.kinds?.includes(0)) return [ ...(originalMention && filter.authors?.includes(peer.pubkey) @@ -229,7 +252,7 @@ async function fixture( return []; }, writer: { - kinds: [9, 40003, 5], + kinds: [9, 40003, 5, ...(pins ? [40010, 40011] : [])], async sign(template) { return signed(viewer, template); }, @@ -821,6 +844,201 @@ const savedFollows = () => .filter((key) => key.startsWith("buzz.thread-follows.v1:")) .map((key) => localStorage.getItem(key)); +it.each([ + ["a DM", [["t", "dm"]], "Pin to DM"], + [ + "a Solo chat", + [ + ["t", "stream"], + ["t", "buzz.solo"], + ], + undefined, + ], +] satisfies [string, string[][], string | undefined][])( + "names the pin for %s", + async (_, channelTags, label) => { + const h = await fixture( + false, + false, + false, + false, + false, + undefined, + false, + undefined, + "member", + { pins: () => [], channelTags }, + ); + // The menu decides once the room is listed with its type. + await waitFor(() => + expect( + h.owner.session.channels + .list() + .channels.find((channel) => channel.id === "room")?.channelType, + ).toBe(channelTags[0]?.[1] === "dm" ? "dm" : "solo"), + ); + if (label) await screen.findByRole("menuitem", { name: label }); + const items = screen + .getAllByRole("menuitem") + .map((item) => item.textContent ?? ""); + expect(items.filter((text) => text.startsWith("Pin to"))).toEqual( + label ? [label] : [], + ); + }, +); + +it("pins from the message menu, and offers unpin for a pinned message", async () => { + const h = await fixture( + false, + false, + false, + false, + false, + undefined, + false, + undefined, + "member", + { + pins: () => [], + }, + ); + fireEvent.click( + await screen.findByRole("menuitem", { name: "Pin to channel" }), + ); + await waitFor(() => expect(h.publications).toHaveLength(1)); + const { event } = h.publication(0); + expect(event.kind).toBe(40010); + expect(event.content).toBe(""); + expect(event.tags.filter(([name]) => name !== "client-id")).toEqual([ + ["h", "room"], + ["e", h.original.id], + ]); + cleanup(); + for (const owner of owners.splice(0)) owner.dispose(); + await fixture( + false, + false, + false, + false, + false, + undefined, + false, + undefined, + "member", + { + pins: (original) => [original.id], + }, + ); + expect( + await screen.findByRole("menuitem", { name: "Unpin from channel" }), + ).toBeInTheDocument(); +}); + +it.each([ + [ + "the relay", + // As the transport reports the relay's refusal. + () => + acceptPublish( + Response.json( + { error: "invalid: event timestamp too far from server time" }, + { status: 400 }, + ), + "pin", + ), + ], + [ + "this device", + () => Promise.reject(new PublishRejected(OLD_EVENT_NOT_FOUND)), + ], +])( + "resends an unanswered pin as itself, then stops when %s refuses it as too old and reads the list again", + async (_, refusal) => { + let listReads = 0; + const h = await fixture( + false, + false, + false, + false, + false, + undefined, + false, + undefined, + "member", + { + pins: () => { + listReads++; + return []; + }, + }, + ); + fireEvent.click( + await screen.findByRole("menuitem", { name: "Pin to channel" }), + ); + await waitFor(() => expect(h.publications).toHaveLength(1)); + // No answer: the outcome is unknown, and Retry sends the same event. + await act(async () => + h.publication(0).result.reject(new Error("Connection lost")), + ); + fireEvent.click( + await screen.findByRole("button", { name: "Retry message update" }), + ); + await waitFor(() => expect(h.publications).toHaveLength(2)); + expect(h.publication(1).event.id).toBe(h.publication(0).event.id); + const reads = listReads; + await act(async () => + h + .publication(1) + .result.reject(await refusal().catch((error: unknown) => error)), + ); + expect(await screen.findByText(EXPIRED_PIN_RECOVERY)).toBeInTheDocument(); + // Still unknown: the refusal does not say whether the pin was applied. + expect(h.owner.session.outbox?.snapshot()[0]?.delivery).toBe("unknown"); + await waitFor(() => expect(listReads).toBe(reads + 1)); + expect( + screen.queryByRole("button", { name: "Retry message update" }), + ).toBeNull(); + expect(screen.queryByText(/Retry sends/)).toBeNull(); + expect(h.publications).toHaveLength(2); + }, +); + +it("says a community without pins refused one, and offers no retry", async () => { + const h = await fixture( + false, + undefined, + undefined, + undefined, + undefined, + undefined, + false, + undefined, + "member", + { pins: () => [] }, + ); + fireEvent.click( + await screen.findByRole("menuitem", { name: "Pin to channel" }), + ); + await waitFor(() => expect(h.publications).toHaveLength(1)); + const refusal = await acceptPublish( + Response.json({ error: "restricted: unknown event kind" }, { status: 400 }), + "pin", + ).catch((error: unknown) => error); + await act(async () => h.publication(0).result.reject(refusal)); + expect(await screen.findByText(UNSUPPORTED_PIN_RECOVERY)).toBeInTheDocument(); + expect(h.owner.session.outbox?.snapshot()[0]?.delivery).toBe("failed"); + expect( + screen.queryByRole("button", { name: "Retry message update" }), + ).toBeNull(); + expect(h.publications).toHaveLength(1); +}); + +it("offers no pin action when the host cannot send pin commands", async () => { + await fixture(false); + await screen.findByRole("menuitem", { name: "Follow thread" }); + expect(screen.queryByRole("menuitem", { name: /pin/i })).toBeNull(); +}); + it("follows a thread without replying and keeps the saved choice", async () => { localStorage.clear(); const h = await fixture(false, true); diff --git a/src/features/messages/MessageManagement.tsx b/src/features/messages/MessageManagement.tsx index 3866242ff0..1c6afd3ada 100644 --- a/src/features/messages/MessageManagement.tsx +++ b/src/features/messages/MessageManagement.tsx @@ -4,6 +4,8 @@ import { EnvelopeIcon, EnvelopeOpenIcon, PencilSimpleIcon, + PinIcon, + PinOffIcon, TrashIcon, } from "../../shared/design-system/icons"; import { @@ -29,7 +31,10 @@ import type { RelaySession } from "../relay/session"; import type { MessageAttention } from "../relay/unread"; import type { AgentOwnerAuthorization } from "../relay/messages"; import type { OutgoingEvent } from "../relay/outbox"; +import { PIN_KIND, refusedPinCommand, UNPIN_KIND } from "../relay/pins"; +import { RefusedPin } from "./RefusedPin"; import { followUpQueue } from "./follow-up-queue"; +import { usePinnedMessages } from "./use-pins"; import { MessageEditScope, useMessageEditScope } from "./MessageEditScope"; import { useAfterMessageMenuClose } from "./MessageActionBar"; import { lastEditableMessage, useCloseAfterPaint } from "./useMessageEdit"; @@ -592,6 +597,12 @@ function ManagedMessageItems({ row.channelId, (channel) => !!channel && !channel.readOnly && !channel.cached, ); + // A Solo chat has one person, so it offers no pins. + const solo = useListedChannel( + session.channels, + row.channelId, + (channel) => channel?.channelType === "solo", + ); const threadRootId = row.threadRootId ?? row.id; const following = useSyncExternalStore(session.unread.subscribeSync, () => session.unread.following(row.channelId, threadRootId), @@ -602,6 +613,13 @@ function ManagedMessageItems({ ? row.authorId : undefined, ); + const canPin = + !!management && + writable && + !archived && + !solo && + !!session.outbox?.supports(PIN_KIND); + const pins = usePinnedMessages(session, canPin ? row.channelId : undefined); if (!management) return null; const busy = management.operations.some( (item) => @@ -625,6 +643,39 @@ function ManagedMessageItems({ afterClose ? afterClose(action) : action(); return ( <> + {canPin && pins.status === "ready" && ( + + ["sending", "accepted"].includes(item.delivery) && + [PIN_KIND, UNPIN_KIND].includes(item.event.kind) && + item.event.tags.some( + ([name, id]) => name === "e" && id === row.id, + ), + )} + onClick={() => { + management.report(undefined); + try { + session.messages.pin( + row.channelId, + row.id, + !pins.set.has(row.id), + ); + } catch (cause) { + management.report( + cause instanceof Error + ? cause.message + : "Could not update the pin. Try again.", + ); + } + }} + > + + {pins.set.has(row.id) ? : } + + {`${pins.set.has(row.id) ? "Unpin from" : "Pin to"} ${dm ? "DM" : "channel"}`} + + )} {canEdit && ( (item.event.kind === 40003 || + item.event.kind === PIN_KIND || + item.event.kind === UNPIN_KIND || (item.event.kind === 5 && item.event.tags.some( ([name, kind]) => @@ -857,17 +910,31 @@ export function MessageManagementStatus() { role="status" >

- {item.event.kind === 40003 ? "Message edit" : "Message deletion"}:{" "} - {item.error ?? "Delivery could not be confirmed."} + {item.event.kind === 40003 + ? "Message edit" + : item.event.kind === PIN_KIND + ? "Pin" + : item.event.kind === UNPIN_KIND + ? "Unpin" + : "Message deletion"} + : {item.error ?? "Delivery could not be confirmed."}

{item.event.kind === 40003 &&

{item.event.content}

} - {item.delivery === "unknown" && ( + {refusedPinCommand(item) ? (

- This may already have reached the conversation. Retry sends the - same operation; dismissing does not undo it. +

+ ) : ( + <> + {item.delivery === "unknown" && ( +

+ This may already have reached the conversation. Retry sends + the same operation; dismissing does not undo it. +

+ )} + + )} -