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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
46 changes: 46 additions & 0 deletions browser-host/relay-broker.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -332,6 +332,10 @@ async function relayAuthority(fetch, relay) {
searchSort:
Array.isArray(nip11.supported_extensions) &&
nip11.supported_extensions.includes("buzz-search-sort"),
// NIP-CI: the relay admits consented conversation imports.
conversationImport:
Array.isArray(nip11.supported_extensions) &&
nip11.supported_extensions.includes("nip-ci"),
...(readSnapshotCommunity(nip11.read_state_snapshot)
? { readStateCommunity: readSnapshotCommunity(nip11.read_state_snapshot) }
: {}),
Expand Down Expand Up @@ -511,6 +515,38 @@ export function validMessageTemplate(event) {
})()
);
}
/** NIP-CI proposal, consent, withdrawal or completion: one channel, JSON
* content within 16 KiB, and a proposal reference on everything but the
* proposal itself. The relay decides membership and session rules. */
export function validImportRecordTemplate(event) {
if (
!event ||
!(event.kind >= 42110 && event.kind <= 42113) ||
typeof event.content !== "string" ||
Buffer.byteLength(event.content) > 16 * 1024 ||
!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"),
) ||
event.tags.filter((tag) => tag[0] === "h" && tag[1]).length !== 1
)
return false;
try {
const body = JSON.parse(event.content);
if (!body || typeof body !== "object" || body.v !== 1) return false;
} catch {
return false;
}
const references = event.tags.filter((tag) => tag[0] === "e");
return event.kind === 42110
? !references.length
: references.length === 1 && /^[0-9a-f]{64}$/.test(references[0][1]);
}
/** NIP-56 message report: exactly one author and one typed message target. */
export function validReport(event) {
if (
Expand Down Expand Up @@ -1548,6 +1584,10 @@ export function relayBrokerPlugin({
9,
40003,
42000,
42110,
42111,
42112,
42113,
9000,
9001,
30078,
Expand Down Expand Up @@ -2758,6 +2798,12 @@ export function relayBrokerPlugin({
error: "Malformed catalog publication",
sent: false,
});
} else if (filters?.kind >= 42110 && filters?.kind <= 42113) {
if (!validImportRecordTemplate(filters))
return json(res, 400, {
error: "Conversation import record rejected",
sent: false,
});
} else if (filters?.kind === 45010) {
// NIP-AR artifacts; the relay enforces write permission.
} else if (filters?.kind === 1984) {
Expand Down
41 changes: 41 additions & 0 deletions browser-host/relay-broker.test.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import assert from "node:assert/strict";
import {
createUpstream,
validFilters,
validImportRecordTemplate,
validMessageTemplate,
} from "./relay-broker.mjs";

Expand Down Expand Up @@ -230,3 +231,43 @@ test("workflow list batches alone may exceed four filters, with 128 unique chann
])
assert.equal(validFilters(invalid), false);
});

test("broker signs only well-formed conversation import records", () => {
const channel = "f0".repeat(16);
const proposal = "1".repeat(64);
const record = (kind, tags, content = '{"v":1}') => ({
kind,
content,
created_at: 1_740_000_000,
tags,
});
assert.equal(
validImportRecordTemplate(record(42110, [["h", channel]])),
true,
);
assert.equal(
validImportRecordTemplate(
record(42111, [
["e", proposal],
["h", channel],
]),
),
true,
);
for (const bad of [
record(42110, [
["h", channel],
["e", proposal],
]),
record(42112, [["h", channel]]),
record(42113, [
["e", "x"],
["h", channel],
]),
record(42111, [["e", proposal]]),
record(42110, [["h", channel]], '{"v":2}'),
record(42110, [["h", channel]], "not json"),
record(9, [["h", channel]]),
])
assert.equal(validImportRecordTemplate(bad), false);
});
8 changes: 4 additions & 4 deletions browser-host/workflow-broker.test.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -228,8 +228,8 @@ it("real broker scoped history signs exact GET path/cursor and captured principa
const other = await connectBrokerTransport(h.base, undefined, "secondary");
expect(h.calls).toHaveLength(0);
expect(first.writer.kinds).toEqual([
30315, 30030, 7, 9, 40003, 42000, 9000, 9001, 30078, 30175, 30177, 30178,
40100, 1984, 45010, 30620, 46020, 5,
30315, 30030, 7, 9, 40003, 42000, 42110, 42111, 42112, 42113, 9000, 9001,
30078, 30175, 30177, 30178, 40100, 1984, 45010, 30620, 46020, 5,
]);
await first.workflows.runs(id, cursor, signal());
await other.workflows.runs(id, undefined, signal());
Expand Down Expand Up @@ -396,8 +396,8 @@ it("existing backend signs only canonical workflow sign/publish with exact own e
const t = await connectBrokerTransport(h.base);
live = await openBrokerSocket(t);
expect(t.writer.kinds).toEqual([
30315, 30030, 7, 9, 40003, 42000, 9000, 9001, 30078, 30175, 30177, 30178,
40100, 1984, 45010, 30620, 46020, 5,
30315, 30030, 7, 9, 40003, 42000, 42110, 42111, 42112, 42113, 9000, 9001,
30078, 30175, 30177, 30178, 40100, 1984, 45010, 30620, 46020, 5,
]);
for (const input of [
template(),
Expand Down
8 changes: 8 additions & 0 deletions docs/buzz-help.md
Original file line number Diff line number Diff line change
Expand Up @@ -78,6 +78,14 @@ the interface unless an available tool actually supports that action.
- **Sharing a Solo chat** grants access to its conversation history, not only
the next message. Copying its link alone does not grant access. Check the
intended people and destination before changing access.
- **Conversation import** brings history from another tool into a direct
message or channel when an import plugin is installed and the community's
relay supports it. Nothing is imported until every participant accepts the
proposal card in the conversation; each person then publishes only their own
messages, at their original times. Buzz confirms each step in its own dialog
and shows verified names and key fingerprints. Imported messages are marked
with their source and do not count as unread or send notifications. People
without a verified Buzz identity are left out.

## Choosing and customizing agents

Expand Down
30 changes: 30 additions & 0 deletions src-tauri/src/relay.rs
Original file line number Diff line number Diff line change
Expand Up @@ -390,6 +390,10 @@ fn validate_event(community: &str, event: &EventTemplate) -> Result<()> {
if !valid_member_command(event) {
return Err("Invalid member change".into());
}
} else if matches!(event.kind, 42110..=42113) {
if !valid_import_record(event) {
return Err("Malformed conversation import record".into());
}
} else if !matches!(
event.kind,
0 | 7 | 9 | 1984 | 9000 | 9001 | 20001 | 30030 | 30177 | 30315 | 40003 | 42000 | 45010
Expand All @@ -399,6 +403,32 @@ fn validate_event(community: &str, event: &EventTemplate) -> Result<()> {
Ok(())
}

/** Match the broker's import record shape (`validImportRecordTemplate` in
* `browser-host/relay-broker.mjs`); the relay decides consent and authority. */
fn valid_import_record(event: &EventTemplate) -> bool {
if event.content.len() > 16 * 1024
|| !event.tags.iter().all(|tag| tag.len() >= 2)
|| event
.tags
.iter()
.filter(|tag| tag[0] == "h" && !tag[1].is_empty())
.count()
!= 1
|| serde_json::from_str::<serde_json::Value>(&event.content)
.ok()
.and_then(|body| body.get("v").and_then(serde_json::Value::as_u64))
!= Some(1)
{
return false;
}
let references: Vec<_> = event.tags.iter().filter(|tag| tag[0] == "e").collect();
if event.kind == 42110 {
references.is_empty()
} else {
matches!(references.as_slice(), [tag] if hex_key(&tag[1]))
}
}

/** Match the broker's NIP-43 member command shape (`memberCommand` in
* `src/features/communities/admin-protocol.ts`); the relay decides authority. */
fn valid_member_command(event: &EventTemplate) -> bool {
Expand Down
43 changes: 43 additions & 0 deletions src-tauri/src/relay/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -152,6 +152,49 @@ fn agent_presence_signs_only_a_status_and_agent_keys() {
}
}

#[test]
fn import_records_sign_only_the_broker_shape() {
let record = |kind: u16, content: &str, tags: &[&[&str]]| EventTemplate {
kind,
created_at: 1,
content: content.into(),
tags: tags
.iter()
.map(|tag| tag.iter().map(|value| value.to_string()).collect())
.collect(),
};
let proposal = "a".repeat(64);
let h: &[&str] = &["h", "channel"];
let e: &[&str] = &["e", &proposal];
let body = r#"{"v":1}"#;
for accepted in [
record(42110, body, &[h, &["p", &proposal]]),
record(42111, body, &[h, e]),
record(42112, body, &[h, e]),
record(42113, body, &[h, e]),
] {
assert!(validate_event("https://relay.test", &accepted).is_ok());
}
let upper = "A".repeat(64);
let large = format!(r#"{{"v":1,"pad":"{}"}}"#, "x".repeat(16 * 1024));
for rejected in [
record(42110, body, &[h, e]),
record(42111, body, &[h]),
record(42111, body, &[h, e, e]),
record(42111, body, &[h, &["e", &upper]]),
record(42111, body, &[e]),
record(42111, body, &[h, h, e]),
record(42111, body, &[&["h", ""], e]),
record(42111, body, &[h, e, &["p"]]),
record(42111, r#"{"v":2}"#, &[h, e]),
record(42111, "[1]", &[h, e]),
record(42111, "not json", &[h, e]),
record(42111, &large, &[h, e]),
] {
assert!(validate_event("https://relay.test", &rejected).is_err());
}
}

#[test]
fn member_commands_sign_only_the_broker_shape() {
let command = |kind: u16, content: &str, tags: &[&[&str]]| EventTemplate {
Expand Down
4 changes: 4 additions & 0 deletions src/app/App.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@ import { Dialog } from "../shared/design-system/ui/Dialog";
import { UpdateNotice } from "../features/updates/UpdateNotice";
import { RejectedLinkNotice } from "../features/navigation/RejectedLinkNotice";
import { CreationReview } from "../bundled/agents/CreationReview";
import { ConversationImportReview } from "../features/conversation-import/ConversationImportReview";
import { UpdateReview } from "../bundled/agents/UpdateReview";
import { InterruptedNotice } from "../features/agents/InterruptedNotice";
import {
Expand Down Expand Up @@ -635,6 +636,9 @@ function ConnectedAppContent({ services }: { services: AppServices }) {
<RejectedLinkNotice links={services.rejectedLinks} />
<InterruptedNotice agents={services.agents} />
<CreationReview agents={services.agents} />
<ConversationImportReview
reviews={services.conversationImportReviews}
/>
<UpdateReview agents={services.agents} />
{!settings && startup === "recovery" ? (
<RecoveryScreen plugins={plugins} />
Expand Down
2 changes: 2 additions & 0 deletions src/app/conversation-features.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,10 +3,12 @@ import emojiManifest from "../bundled/emoji/manifest.json";
import * as emoji from "../bundled/emoji";
import mentionsManifest from "../bundled/mentions/manifest.json";
import * as mentions from "../bundled/mentions";
import * as conversationImport from "../features/conversation-import/feature";

// Host-owned features use the shared contribution lifecycle, without catalog
// entries or saved enablement. Keep their keys for composer and huddle consumers.
export const conversationFeatures: readonly BundledPlugin[] = [
{ manifest: { ...emojiManifest, apiVersion: 1 }, module: emoji },
{ manifest: { ...mentionsManifest, apiVersion: 1 }, module: mentions },
{ manifest: conversationImport.manifest, module: conversationImport },
];
20 changes: 9 additions & 11 deletions src/app/pages.integration.test.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -281,26 +281,24 @@ test("the app runtime exposes ready bundled pages and removes them on disable",
.snapshot()
.some((panel) => panel.pluginId === "buzz.agent-activity"),
);
assert.equal(services.conversation.accessories.snapshot().length, 2);
assert.deepEqual(
// The host's conversation import banner is a built-in accessory.
const pluginAccessories = () =>
services.conversation.accessories
.snapshot()
.map(({ id, placement }) => [id, placement]),
.filter((item) => item.pluginId !== "buzz.conversation-import");
assert.equal(pluginAccessories().length, 2);
assert.deepEqual(
pluginAccessories().map(({ id, placement }) => [id, placement]),
[
["activity", "message"],
["typing-presentation", undefined],
],
);
assert.equal(
services.conversation.accessories.snapshot()[0].pluginId,
"buzz.agent-activity",
);
assert.equal(pluginAccessories()[0].pluginId, "buzz.agent-activity");
await services.plugins.change("disable", "buzz.agent-activity");
assert.equal(services.conversation.accessories.snapshot().length, 0);
assert.equal(pluginAccessories().length, 0);
await services.plugins.change("enable", "buzz.agent-activity");
await vi.waitFor(() =>
assert.equal(services.conversation.accessories.snapshot().length, 2),
);
await vi.waitFor(() => assert.equal(pluginAccessories().length, 2));

await services.plugins.change("enable", "buzz.bestie");
await vi.waitFor(() =>
Expand Down
11 changes: 11 additions & 0 deletions src/app/services.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,6 @@
import { ArtifactStorageService } from "../features/artifact-storage/service";
import { createConversationImportHost } from "../features/conversation-import/service";
import { createImportReviews } from "../features/conversation-import/reviews";
import { createAdminAccess } from "../bundled/admin-access";
import { nativeRelayStaff } from "../features/relay-staff/native";
import { createLocalAgentActivity } from "../features/agents/local-activity";
Expand Down Expand Up @@ -99,6 +101,13 @@ export function createServices() {
});
const relay = communities.relay;
const artifactStorage = new ArtifactStorageService(ctx);
const conversationImportReviews = createImportReviews();
const conversationImport = createConversationImportHost(
ctx,
relay,
conversationImportReviews,
);
ctx.effect(() => () => conversationImportReviews.dispose());
// Expose v2 only with the complete label/projection/frame/Destination/guard slice.
new SoloNavigationService(ctx, relay, plugins);
// The one recovery point for federated sign-in; see onSignedIn.
Expand Down Expand Up @@ -225,6 +234,8 @@ export function createServices() {
shortcutBindings,
conversation,
artifactStorage,
conversationImport,
conversationImportReviews,
settingsCards,
adminAccess,
pages,
Expand Down
4 changes: 3 additions & 1 deletion src/features/agents/service.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import { withoutImported } from "../conversation-import/protocol";
import type {} from "../navigation/service";
import { appClient, readFile } from "../../buzz-mcp/app-client";
import { respond } from "../../buzz-mcp/rpc";
Expand Down Expand Up @@ -5152,7 +5153,8 @@ export class AgentsService extends Service implements Agents {
if (connected) Object.assign(connection, { epoch: 1, since });
const heard = (agent: Agent) => originOf(agent.relay) === origin;
const stopEvents = session.subscribeLive(
(batch) => this.runners.dispatch(batch, heard, since),
// Imported history never triggers agents.
(batch) => this.runners.dispatch(withoutImported(batch), heard, since),
{ replay: true },
);
const stopStatus = session.live.subscribe(() => {
Expand Down
Loading