Skip to content

Commit 74f3f29

Browse files
tlongwell-blocknpub12gtutshhh76rx0jx697f32f9tffd4hhp3hx58fp4x6u4uemkm7sqf8f757
andauthored
feat(desktop): ensure starter channels during onboarding (#1937)
Signed-off-by: npub12gtutshhh76rx0jx697f32f9tffd4hhp3hx58fp4x6u4uemkm7sqf8f757 <5217c5c2f7bfb4333e46d17c98a9255a52dadee18dcd43a43536b95e6776dfa0@sprout-oss.stage.blox.sqprod.co> Co-authored-by: npub12gtutshhh76rx0jx697f32f9tffd4hhp3hx58fp4x6u4uemkm7sqf8f757 <5217c5c2f7bfb4333e46d17c98a9255a52dadee18dcd43a43536b95e6776dfa0@sprout-oss.stage.blox.sqprod.co>
1 parent 2b015cb commit 74f3f29

20 files changed

Lines changed: 904 additions & 448 deletions

‎desktop/src-tauri/Cargo.lock‎

Lines changed: 1 addition & 0 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

‎desktop/src-tauri/Cargo.toml‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -105,7 +105,7 @@ bzip2 = "0.6"
105105
chrono = { version = "0.4", features = ["serde"] }
106106
tauri-plugin-global-shortcut = "2"
107107
tauri-plugin-notification = "2.3.3"
108-
uuid = { version = "1", features = ["v4"] }
108+
uuid = { version = "1", features = ["v4", "v5"] }
109109
png = "0.18"
110110
arboard = "3"
111111
image = { version = "0.25", default-features = false, features = ["jpeg", "png", "webp", "gif"] }

‎desktop/src-tauri/src/commands/channels.rs‎

Lines changed: 173 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -5,12 +5,32 @@ use crate::{
55
events,
66
models::{ChannelDetailInfo, ChannelInfo, ChannelMembersResponse},
77
nostr_convert,
8-
relay::{query_relay, submit_event, submit_event_with_keys},
8+
relay::{query_relay, relay_api_base_url_with_override, submit_event, submit_event_with_keys},
99
};
1010

1111
// ── Reads (pure-nostr via /query) ────────────────────────────────────────────
1212

1313
const DIRECTORY_PAGE_SIZE: usize = 500;
14+
const STARTER_CHANNEL_NAMESPACE: uuid::Uuid = uuid::uuid!("3ce33bea-8f09-5f1b-9c85-8a7d2659e6b0");
15+
16+
struct StarterChannelSpec {
17+
slug: &'static str,
18+
name: &'static str,
19+
description: &'static str,
20+
}
21+
22+
const STARTER_CHANNELS: &[StarterChannelSpec] = &[
23+
StarterChannelSpec {
24+
slug: "general",
25+
name: "general",
26+
description: "General conversation and community updates.",
27+
},
28+
StarterChannelSpec {
29+
slug: "welcome-everyone",
30+
name: "welcome-everyone",
31+
description: "Say hi, ask a question, or share what brought you here.",
32+
},
33+
];
1434

1535
fn advance_directory_cursor(filter: &mut serde_json::Value, page: &[nostr::Event]) {
1636
let last = page
@@ -445,6 +465,84 @@ fn parse_channel_uuid(channel_id: &str) -> Result<uuid::Uuid, String> {
445465
uuid::Uuid::parse_str(channel_id).map_err(|_| format!("invalid channel UUID: {channel_id}"))
446466
}
447467

468+
fn normalize_channel_name(name: &str) -> String {
469+
name.trim().to_ascii_lowercase()
470+
}
471+
472+
fn starter_channel_uuid(relay_scope: &str, slug: &str) -> uuid::Uuid {
473+
let name = format!("starter-channel:v1:{}:{}", relay_scope.trim(), slug);
474+
uuid::Uuid::new_v5(&STARTER_CHANNEL_NAMESPACE, name.as_bytes())
475+
}
476+
477+
fn is_duplicate_channel_rejection(error: &str) -> bool {
478+
error.contains("relay rejected event:") && error.contains("duplicate: channel already exists")
479+
}
480+
481+
fn is_matching_starter_channel(channel: &ChannelInfo, spec: &StarterChannelSpec) -> bool {
482+
normalize_channel_name(&channel.name) == normalize_channel_name(spec.name)
483+
&& channel.channel_type == "stream"
484+
&& channel.visibility == "open"
485+
&& channel.archived_at.is_none()
486+
}
487+
488+
fn has_all_starter_channels(channels: &[ChannelInfo]) -> bool {
489+
STARTER_CHANNELS.iter().all(|spec| {
490+
channels
491+
.iter()
492+
.any(|channel| is_matching_starter_channel(channel, spec))
493+
})
494+
}
495+
496+
async fn ensure_starter_channel_memberships(
497+
state: &AppState,
498+
keys: &nostr::Keys,
499+
channels: &mut [ChannelInfo],
500+
) -> Result<(), String> {
501+
for spec in STARTER_CHANNELS {
502+
let Some(channel) = channels
503+
.iter_mut()
504+
.find(|channel| is_matching_starter_channel(channel, spec))
505+
else {
506+
continue;
507+
};
508+
509+
if channel.is_member {
510+
continue;
511+
}
512+
513+
let channel_uuid = parse_channel_uuid(&channel.id)?;
514+
let builder = events::build_join(channel_uuid)?;
515+
submit_event_with_keys(builder, state, keys, None).await?;
516+
channel.is_member = true;
517+
}
518+
519+
Ok(())
520+
}
521+
522+
async fn fetch_starter_channel_metadata(
523+
state: &AppState,
524+
channel_ids: &[String],
525+
) -> Result<Vec<ChannelInfo>, String> {
526+
if channel_ids.is_empty() {
527+
return Ok(Vec::new());
528+
}
529+
530+
let events = query_relay(
531+
state,
532+
&[serde_json::json!({
533+
"kinds": [39000],
534+
"#d": channel_ids,
535+
"limit": channel_ids.len(),
536+
})],
537+
)
538+
.await?;
539+
540+
events
541+
.iter()
542+
.map(|ev| nostr_convert::channel_info_from_event(ev, None, Some(false)))
543+
.collect()
544+
}
545+
448546
#[tauri::command]
449547
pub async fn create_channel(
450548
name: String,
@@ -510,6 +608,80 @@ pub async fn create_channel(
510608
.ok_or_else(|| "channel created but metadata not yet available".to_string())
511609
}
512610

611+
#[tauri::command]
612+
pub async fn ensure_starter_channels(
613+
state: State<'_, AppState>,
614+
) -> Result<Vec<ChannelInfo>, String> {
615+
let mut existing_channels = get_channels(state.clone()).await?;
616+
let relay_scope = relay_api_base_url_with_override(&state);
617+
let creator_keys = state.signing_keys()?;
618+
let creator_pubkey = creator_keys.public_key().to_hex();
619+
let mut starter_ids = Vec::with_capacity(STARTER_CHANNELS.len());
620+
let mut created_ids = std::collections::HashSet::new();
621+
622+
for spec in STARTER_CHANNELS {
623+
if existing_channels
624+
.iter()
625+
.any(|channel| is_matching_starter_channel(channel, spec))
626+
{
627+
continue;
628+
}
629+
630+
let channel_uuid = starter_channel_uuid(&relay_scope, spec.slug);
631+
let channel_uuid_string = channel_uuid.to_string();
632+
starter_ids.push(channel_uuid_string.clone());
633+
let builder = events::build_create_channel(
634+
channel_uuid,
635+
spec.name,
636+
"open",
637+
"stream",
638+
Some(spec.description),
639+
None,
640+
)?;
641+
642+
match submit_event_with_keys(builder, &state, &creator_keys, None).await {
643+
Ok(_) => {
644+
state.mark_pending_owned_channel(&creator_pubkey, &channel_uuid_string);
645+
created_ids.insert(channel_uuid_string.clone());
646+
}
647+
Err(error) if is_duplicate_channel_rejection(&error) => {
648+
state.mark_pending_owned_channel(&creator_pubkey, &channel_uuid_string);
649+
}
650+
Err(error) => return Err(error),
651+
}
652+
}
653+
654+
for _ in 0..3 {
655+
let metadata = fetch_starter_channel_metadata(&state, &starter_ids).await?;
656+
for mut channel in metadata {
657+
if created_ids.contains(&channel.id) {
658+
channel.is_member = true;
659+
}
660+
if !existing_channels
661+
.iter()
662+
.any(|existing| existing.id == channel.id)
663+
{
664+
existing_channels.push(channel);
665+
}
666+
}
667+
if has_all_starter_channels(&existing_channels) {
668+
break;
669+
}
670+
tokio::time::sleep(std::time::Duration::from_millis(150)).await;
671+
}
672+
673+
if !has_all_starter_channels(&existing_channels) {
674+
existing_channels = get_channels(state.clone()).await?;
675+
}
676+
677+
if !has_all_starter_channels(&existing_channels) {
678+
return Err("starter channels created but metadata not yet available".to_string());
679+
}
680+
681+
ensure_starter_channel_memberships(&state, &creator_keys, &mut existing_channels).await?;
682+
Ok(existing_channels)
683+
}
684+
513685
#[derive(serde::Deserialize)]
514686
#[serde(rename_all = "camelCase")]
515687
pub struct UpdateChannelInput {

‎desktop/src-tauri/src/commands/channels_tests.rs‎

Lines changed: 61 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -240,3 +240,64 @@ fn pending_owner_mark_uses_signer_captured_before_identity_swap() {
240240
let post_swap_pubkey = state.keys.lock().expect("lock keys").public_key().to_hex();
241241
assert!(!state.is_pending_owned_channel(&post_swap_pubkey, "chan-1"));
242242
}
243+
244+
#[test]
245+
fn starter_channel_uuid_is_stable_and_scoped() {
246+
let first = starter_channel_uuid("https://relay-a.example", "general");
247+
let second = starter_channel_uuid("https://relay-a.example", "general");
248+
let other_slug = starter_channel_uuid("https://relay-a.example", "welcome-everyone");
249+
let other_relay = starter_channel_uuid("https://relay-b.example", "general");
250+
251+
assert_eq!(first, second);
252+
assert_ne!(first, other_slug);
253+
assert_ne!(first, other_relay);
254+
}
255+
256+
#[test]
257+
fn duplicate_channel_rejection_is_ensure_success_only() {
258+
assert!(is_duplicate_channel_rejection(
259+
"relay rejected event: duplicate: channel already exists"
260+
));
261+
assert!(!is_duplicate_channel_rejection(
262+
"relay rejected event: auth: not authorized"
263+
));
264+
assert!(!is_duplicate_channel_rejection(
265+
"duplicate: unrelated local error"
266+
));
267+
}
268+
269+
#[test]
270+
fn starter_match_requires_open_unarchived_stream_by_normalized_name() {
271+
let spec = &STARTER_CHANNELS[0];
272+
let mut channel = ChannelInfo {
273+
id: "chan-1".to_string(),
274+
name: " General ".to_string(),
275+
channel_type: "stream".to_string(),
276+
visibility: "open".to_string(),
277+
description: "".to_string(),
278+
topic: None,
279+
purpose: None,
280+
member_count: 0,
281+
member_pubkeys: Vec::new(),
282+
last_message_at: None,
283+
archived_at: None,
284+
participants: Vec::new(),
285+
participant_pubkeys: Vec::new(),
286+
is_member: true,
287+
ttl_seconds: None,
288+
ttl_deadline: None,
289+
};
290+
291+
assert!(is_matching_starter_channel(&channel, spec));
292+
293+
channel.visibility = "private".to_string();
294+
assert!(!is_matching_starter_channel(&channel, spec));
295+
296+
channel.visibility = "open".to_string();
297+
channel.channel_type = "forum".to_string();
298+
assert!(!is_matching_starter_channel(&channel, spec));
299+
300+
channel.channel_type = "stream".to_string();
301+
channel.archived_at = Some("2026-07-16T00:00:00Z".to_string());
302+
assert!(!is_matching_starter_channel(&channel, spec));
303+
}

‎desktop/src-tauri/src/lib.rs‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -789,6 +789,7 @@ pub fn run() {
789789
nip44_decrypt_from_self,
790790
get_channels,
791791
create_channel,
792+
ensure_starter_channels,
792793
open_dm,
793794
hide_dm,
794795
get_channel_details,

‎desktop/src/features/channels/ui/ChannelPane.tsx‎

Lines changed: 13 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -57,7 +57,10 @@ import { Button } from "@/shared/ui/button";
5757
import { buildMainTimelineEntries } from "@/features/messages/lib/threadPanel";
5858
import { useRenderScopedReactionHydration } from "@/features/messages/lib/useRenderScopedReactionHydration";
5959
import type { TimelineMessage } from "@/features/messages/types";
60-
import { isWelcomeChannel } from "@/features/onboarding/welcome";
60+
import {
61+
isWelcomeChannel,
62+
isWelcomeExperienceChannel as isWelcomeExperience,
63+
} from "@/features/onboarding/welcome";
6164
import { KIND_SYSTEM_MESSAGE } from "@/shared/constants/kinds";
6265
import { useIsThreadPanelOverlay } from "@/shared/hooks/use-mobile";
6366
import { channelChrome } from "@/shared/layout/chromeLayout";
@@ -203,7 +206,7 @@ export const ChannelPane = React.memo(function ChannelPane({
203206
const huddleMemberPubkeysPending =
204207
agentPubkeysPending && hasOtherDmParticipant(activeChannel, currentPubkey);
205208
const isActiveWelcomeChannel =
206-
activeChannel !== null && isWelcomeChannel(activeChannel);
209+
activeChannel !== null && isWelcomeExperience(activeChannel);
207210
useComposerHeightPadding(
208211
timelineScrollRef,
209212
composerWrapperRef,
@@ -438,7 +441,7 @@ export const ChannelPane = React.memo(function ChannelPane({
438441
}
439442

440443
const actions = [];
441-
if (isWelcomeChannel(activeChannel)) {
444+
if (isWelcomeExperience(activeChannel)) {
442445
if (onBrowseChannels) {
443446
actions.push({
444447
icon: <HashSearch aria-hidden className="h-6 w-6" />,
@@ -447,7 +450,6 @@ export const ChannelPane = React.memo(function ChannelPane({
447450
testId: "welcome-intro-action-browse-channels",
448451
});
449452
}
450-
451453
if (onCreateChannel) {
452454
actions.push({
453455
icon: <Plus aria-hidden className="h-6 w-6" />,
@@ -456,7 +458,6 @@ export const ChannelPane = React.memo(function ChannelPane({
456458
testId: "welcome-intro-action-create-channel",
457459
});
458460
}
459-
460461
if (onAddAgent) {
461462
actions.push({
462463
icon: <Bot aria-hidden className="h-6 w-6" />,
@@ -469,12 +470,15 @@ export const ChannelPane = React.memo(function ChannelPane({
469470
testId: "welcome-intro-action-create-agent",
470471
});
471472
}
472-
473473
return {
474474
actions,
475-
channelKindLabel: "private welcome channel",
475+
channelKindLabel: isWelcomeChannel(activeChannel)
476+
? "private welcome channel"
477+
: getChannelIntroKind(activeChannel),
476478
channelName: activeChannel.name,
477-
description: null,
479+
description: isWelcomeChannel(activeChannel)
480+
? null
481+
: getChannelIntroDescription(activeChannel),
478482
icon: <Sparkles aria-hidden className="h-7 w-7" />,
479483
};
480484
}
@@ -514,9 +518,8 @@ export const ChannelPane = React.memo(function ChannelPane({
514518
onCreateChannel,
515519
onOpenMembers,
516520
]);
517-
518521
const visibleMessages = React.useMemo(() => {
519-
if (!isWelcomeChannel(activeChannel)) {
522+
if (!isWelcomeExperience(activeChannel)) {
520523
return messages;
521524
}
522525

‎desktop/src/features/channels/useWelcomeAgentCreate.ts‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@ import * as React from "react";
22

33
import { requestOpenCreateAgent } from "@/features/agents/openCreateAgentEvent";
44
import { useSendMessageMutation } from "@/features/messages/hooks";
5-
import { isWelcomeChannel } from "@/features/onboarding/welcome";
5+
import { isWelcomeExperienceChannel } from "@/features/onboarding/welcome";
66
import type { Channel, Identity } from "@/shared/api/types";
77

88
type WelcomeGuideAgent = {
@@ -31,7 +31,7 @@ export function useWelcomeAgentCreate({
3131
const openAddAgent = React.useCallback(
3232
(openRegularPicker: () => void, options?: { beforeSend?: () => void }) => {
3333
setError(null);
34-
if (isWelcomeChannel(activeChannel)) {
34+
if (isWelcomeExperienceChannel(activeChannel)) {
3535
beforeSendRef.current = options?.beforeSend ?? null;
3636
setIsOpen(true);
3737
return;

0 commit comments

Comments
 (0)