Skip to content

Commit 25f6318

Browse files
wpfleger96npub1mn7jgtj4w2pd0g0zeuhxsa6jy6p0rewxz4kujt98my82ahfmp72sxjexk7
andauthored
fix(onboarding): skip community profile setup for existing relay members (#2300)
Signed-off-by: Will Pfleger <[email protected]> Co-authored-by: npub1mn7jgtj4w2pd0g0zeuhxsa6jy6p0rewxz4kujt98my82ahfmp72sxjexk7 <dcfd242e557282d7a1e2cf2e6877522682f1e5c6156dc92ca7d90eaedd3b0f95@sprout-oss.stage.blox.sqprod.co>
1 parent a5c5bcc commit 25f6318

5 files changed

Lines changed: 378 additions & 6 deletions

File tree

‎desktop/src/app/App.tsx‎

Lines changed: 46 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -20,6 +20,9 @@ import { useMachineOnboardingState } from "@/features/onboarding/machineOnboardi
2020
import {
2121
type FirstCommunityPage,
2222
useCommunityOnboarding,
23+
markCommunityOnboardingComplete,
24+
resolveProfileCheckAction,
25+
isTransactionStillConnecting,
2326
} from "@/features/onboarding/communityOnboarding";
2427
import { CommunityOnboardingFlow } from "@/features/onboarding/ui/CommunityOnboardingFlow";
2528
import {
@@ -43,6 +46,7 @@ import { CommunityApplyErrorScreen } from "@/features/communities/ui/CommunityAp
4346
import { CommunityChangeOverlay } from "@/features/communities/ui/CommunityChangeOverlay";
4447
import { createBuzzQueryClient } from "@/shared/api/queryClient";
4548
import { isSharedIdentity as isSharedIdentityCmd } from "@/shared/api/tauri";
49+
import { getProfile } from "@/shared/api/tauriProfiles";
4650
import {
4751
type AddCommunityDeepLinkPayload,
4852
listenForDeepLinks,
@@ -279,6 +283,14 @@ function CommunityApp({
279283
} = useCommunities();
280284
const communityOnboarding = useCommunityOnboarding();
281285
const connectingTransactionRef = useRef<string | null>(null);
286+
// Tracks the ID of the profile-check request that has been launched for the
287+
// current connecting transaction. Prevents the effect from launching a
288+
// second request if it re-runs while a fetch is in flight.
289+
const profileCheckTransactionRef = useRef<string | null>(null);
290+
// Always reflects the live transaction object so async callbacks can perform
291+
// an atomic check of both ID and stage before mutating state.
292+
const transactionRef = useRef(communityOnboarding.transaction);
293+
transactionRef.current = communityOnboarding.transaction;
282294
const [isCommunityChangeOpen, setIsCommunityChangeOpen] = useState(false);
283295
const [resumeFirstCommunityPage, setResumeFirstCommunityPage] =
284296
useState<FirstCommunityPage | null>(null);
@@ -384,17 +396,47 @@ function CommunityApp({
384396
useEffect(() => {
385397
if (transaction?.stage !== "connecting") {
386398
connectingTransactionRef.current = null;
399+
profileCheckTransactionRef.current = null;
387400
}
388401
}, [transaction?.stage]);
389402
const targetIsReady =
390403
transaction?.communityId === activeCommunity?.id &&
391404
community.isReady &&
392405
community.appliedKey === communityKey;
393406
useEffect(() => {
394-
if (transaction?.stage === "connecting" && targetIsReady) {
395-
communityOnboarding.update({ stage: "profile", error: undefined });
396-
}
397-
}, [communityOnboarding.update, targetIsReady, transaction?.stage]);
407+
if (transaction?.stage !== "connecting" || !targetIsReady) return;
408+
const transactionId = transaction.id;
409+
const relayUrl = transaction.relayUrl;
410+
if (profileCheckTransactionRef.current === transactionId) return;
411+
profileCheckTransactionRef.current = transactionId;
412+
413+
// resolveProfileCheckAction resolves exactly once (Promise.race + timer
414+
// cleared on settle), so no settled flag is needed here.
415+
void resolveProfileCheckAction(getProfile, 10_000).then((result) => {
416+
// Atomic staleness guard via isTransactionStillConnecting: the
417+
// transaction must still be the same one that launched this request
418+
// AND still be in connecting. Covers cancel+replacement (B's ID !== A's)
419+
// and cancel-without-replacement (transactionRef.current is null).
420+
if (!isTransactionStillConnecting(transactionRef.current, transactionId))
421+
return;
422+
423+
if (result.action === "skip") {
424+
markCommunityOnboardingComplete(result.profile.pubkey, relayUrl);
425+
communityOnboarding.clear();
426+
} else {
427+
communityOnboarding.update(
428+
{ stage: "profile", error: undefined },
429+
transactionId,
430+
);
431+
}
432+
});
433+
}, [
434+
communityOnboarding,
435+
targetIsReady,
436+
transaction?.stage,
437+
transaction?.id,
438+
transaction?.relayUrl,
439+
]);
398440
// During "entering" the transaction stays alive as a curtain: the app mounts
399441
// underneath (already pointed at the Welcome channel route) while the
400442
// onboarding screen covers it, then fades once Welcome reports ready.

‎desktop/src/features/onboarding/communityOnboarding.test.mjs‎

Lines changed: 195 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3,8 +3,11 @@ import test from "node:test";
33

44
import {
55
clearCommunityOnboardingTransaction,
6+
isTransactionStillConnecting,
67
loadCommunityOnboardingTransaction,
78
markCommunityOnboardingComplete,
9+
resolveProfileCheckAction,
10+
shouldSkipCommunityOnboarding,
811
startCommunityOnboarding,
912
updateCommunityOnboardingTransaction,
1013
updateCurrentCommunityOnboardingTransaction,
@@ -147,3 +150,195 @@ test("completion is scoped by relay and pubkey and preserves legacy gate", () =>
147150
);
148151
assert.equal(storage.getItem("buzz-onboarding-complete.v1:pubkey"), "true");
149152
});
153+
154+
// ── shouldSkipCommunityOnboarding ────────────────────────────────────────────
155+
156+
/** Minimal Profile stub — only the fields the helper inspects. */
157+
function makeProfile(hasProfileEvent, overrides = {}) {
158+
return {
159+
pubkey: "aabbcc",
160+
displayName: null,
161+
avatarUrl: null,
162+
about: null,
163+
nip05Handle: null,
164+
ownerPubkey: null,
165+
hasProfileEvent,
166+
...overrides,
167+
};
168+
}
169+
170+
test("shouldSkipCommunityOnboarding_hasProfileEvent_returnsTrue", () => {
171+
assert.equal(
172+
shouldSkipCommunityOnboarding(makeProfile(true)),
173+
true,
174+
"existing kind:0 ⇒ skip onboarding",
175+
);
176+
});
177+
178+
test("shouldSkipCommunityOnboarding_noProfileEvent_returnsFalse", () => {
179+
assert.equal(
180+
shouldSkipCommunityOnboarding(makeProfile(false)),
181+
false,
182+
"no kind:0 ⇒ show profile step",
183+
);
184+
});
185+
186+
test("shouldSkipCommunityOnboarding_fetchError_returnsFalse", () => {
187+
// fetch error is represented as null — must never block onboarding
188+
assert.equal(
189+
shouldSkipCommunityOnboarding(null),
190+
false,
191+
"fetch error ⇒ show profile step (safe fallback)",
192+
);
193+
});
194+
195+
// ── resolveProfileCheckAction — async orchestration ──────────────────────────
196+
197+
/**
198+
* Returns a fake scheduleTimeout that captures registered callbacks so tests
199+
* can fire or skip them manually without real timers.
200+
*/
201+
function makeScheduler() {
202+
const callbacks = [];
203+
return {
204+
schedule: (fn, _ms) => callbacks.push(fn),
205+
fireTimeout: () => {
206+
const fn = callbacks.shift();
207+
if (fn) fn();
208+
},
209+
pendingCount: () => callbacks.length,
210+
};
211+
}
212+
213+
test("resolveProfileCheckAction_hasProfileEvent_returnsSkipWithProfile", async () => {
214+
const profile = makeProfile(true, { pubkey: "aabbcc" });
215+
const result = await resolveProfileCheckAction(
216+
() => Promise.resolve(profile),
217+
10_000,
218+
makeScheduler().schedule,
219+
);
220+
assert.equal(result.action, "skip");
221+
assert.equal(result.profile.pubkey, "aabbcc");
222+
});
223+
224+
test("resolveProfileCheckAction_noProfileEvent_returnsShowProfile", async () => {
225+
const result = await resolveProfileCheckAction(
226+
() => Promise.resolve(makeProfile(false)),
227+
10_000,
228+
makeScheduler().schedule,
229+
);
230+
assert.equal(result.action, "show-profile");
231+
});
232+
233+
test("resolveProfileCheckAction_fetchRejects_returnsShowProfile", async () => {
234+
const result = await resolveProfileCheckAction(
235+
() => Promise.reject(new Error("network error")),
236+
10_000,
237+
makeScheduler().schedule,
238+
);
239+
assert.equal(result.action, "show-profile");
240+
});
241+
242+
test("resolveProfileCheckAction_timeout_returnsShowProfile", async () => {
243+
// Fetch never settles; scheduler fires the timeout immediately.
244+
const scheduler = makeScheduler();
245+
const result = await resolveProfileCheckAction(
246+
() => new Promise(() => {}), // hangs forever
247+
10_000,
248+
(fn, ms) => {
249+
scheduler.schedule(fn, ms);
250+
// Fire synchronously so the test does not wait for a real timer.
251+
scheduler.fireTimeout();
252+
},
253+
);
254+
assert.equal(
255+
result.action,
256+
"show-profile",
257+
"timeout ⇒ show-profile (never strands onboarding)",
258+
);
259+
});
260+
261+
test("resolveProfileCheckAction_lateSuccessAfterTimeout_doesNotSkip", async () => {
262+
// Fetch resolves AFTER the timeout has already fired.
263+
// resolveProfileCheckAction must return show-profile from the timeout path,
264+
// and the late fetch result must have no effect.
265+
let resolveFetch;
266+
const fetchPromise = new Promise((resolve) => {
267+
resolveFetch = resolve;
268+
});
269+
270+
const scheduler = makeScheduler();
271+
const resultPromise = resolveProfileCheckAction(
272+
() => fetchPromise,
273+
10_000,
274+
scheduler.schedule,
275+
);
276+
277+
// Fire the timeout — race settles with the timeout rejection.
278+
scheduler.fireTimeout();
279+
280+
// Now resolve the fetch with a kind:0 profile.
281+
resolveFetch(makeProfile(true));
282+
283+
const result = await resultPromise;
284+
assert.equal(
285+
result.action,
286+
"show-profile",
287+
"late success after timeout must not complete onboarding",
288+
);
289+
});
290+
291+
// ── isTransactionStillConnecting — stale-transaction guard ───────────────────
292+
293+
/**
294+
* Builds a minimal transaction stub for testing the guard predicate.
295+
* Only `id` and `stage` are inspected by isTransactionStillConnecting.
296+
*/
297+
function makeTransaction(id, stage) {
298+
return {
299+
id,
300+
stage,
301+
source: "add-community",
302+
relayUrl: "wss://relay.example",
303+
communityName: "test",
304+
createdAt: new Date().toISOString(),
305+
updatedAt: new Date().toISOString(),
306+
};
307+
}
308+
309+
test("isTransactionStillConnecting_matchingIdAndStage_returnsTrue", () => {
310+
assert.equal(
311+
isTransactionStillConnecting(makeTransaction("tx-a", "connecting"), "tx-a"),
312+
true,
313+
"same id + connecting stage → guard passes",
314+
);
315+
});
316+
317+
test("isTransactionStillConnecting_replacedTransaction_returnsFalse", () => {
318+
// Transaction B replaced A while the fetch was in flight.
319+
// The callback for A must not clear B.
320+
assert.equal(
321+
isTransactionStillConnecting(makeTransaction("tx-b", "connecting"), "tx-a"),
322+
false,
323+
"different id (replacement) → guard rejects stale success",
324+
);
325+
});
326+
327+
test("isTransactionStillConnecting_cancelWithNoReplacement_returnsFalse", () => {
328+
// User cancelled without starting a new transaction; ref is null.
329+
assert.equal(
330+
isTransactionStillConnecting(null, "tx-a"),
331+
false,
332+
"null ref (cancel without replacement) → guard rejects stale success",
333+
);
334+
});
335+
336+
test("isTransactionStillConnecting_stagePastConnecting_returnsFalse", () => {
337+
// Fallback already advanced the transaction to 'profile' before the skip
338+
// result arrived — double-completion must not occur.
339+
assert.equal(
340+
isTransactionStillConnecting(makeTransaction("tx-a", "profile"), "tx-a"),
341+
false,
342+
"stage advanced past connecting → guard rejects late action",
343+
);
344+
});

‎desktop/src/features/onboarding/communityOnboarding.tsx‎

Lines changed: 85 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@ import {
33
normalizeRelayUrl,
44
} from "@/features/communities/communityStorage";
55
import { setLocalStorageItemWithRecovery } from "@/shared/lib/localStorageQuota";
6+
import type { Profile } from "@/shared/api/types";
67

78
const STORAGE_KEY = "buzz-community-onboarding-transaction.v1";
89

@@ -227,6 +228,90 @@ export function markCommunityOnboardingComplete(
227228
storage.setItem(`buzz-onboarding-complete.v1:${pubkey}`, "true");
228229
}
229230

231+
/**
232+
* Returns true when a relay-profile check result means the user should skip
233+
* community onboarding entirely and land directly in the app.
234+
*
235+
* A profile fetch error is represented as `null` and always returns false so
236+
* that the fallback (show the profile step) applies — the skip must never
237+
* block or strand onboarding.
238+
*/
239+
export function shouldSkipCommunityOnboarding(
240+
profile: Profile | null,
241+
): boolean {
242+
return profile !== null && profile.hasProfileEvent === true;
243+
}
244+
245+
/**
246+
* Outcome of a profile-check attempt during the connecting → profile
247+
* transition. Produced by `resolveProfileCheckAction`.
248+
*
249+
* - `{ action: "skip", profile }` — kind:0 exists; mark complete and enter
250+
* the app. The resolved `Profile` is included so callers have the pubkey
251+
* for `markCommunityOnboardingComplete` without a second fetch.
252+
* - `{ action: "show-profile" }` — no kind:0, or the fetch failed / timed
253+
* out; show the profile setup step.
254+
*/
255+
export type ProfileCheckAction =
256+
| { action: "skip"; profile: Profile }
257+
| { action: "show-profile" };
258+
259+
/**
260+
* Returns true when a live transaction snapshot still represents the
261+
* same connecting request that launched the profile check.
262+
*
263+
* Extracted as a pure predicate so the stale-result guard in App.tsx can
264+
* be unit-tested without mounting a component.
265+
*/
266+
export function isTransactionStillConnecting(
267+
live: CommunityOnboardingTransaction | null | undefined,
268+
transactionId: string,
269+
): boolean {
270+
return live?.id === transactionId && live.stage === "connecting";
271+
}
272+
273+
/**
274+
* Runs a bounded profile fetch and returns the action to take at the
275+
* `connecting → profile` transition.
276+
*
277+
* Accepts `fetchProfile`, `timeoutMs`, and `scheduleTimeout` as parameters so
278+
* callers (and tests) can supply controlled implementations. `scheduleTimeout`
279+
* must return a cancellation handle (like `window.setTimeout`) so the timer
280+
* can be cleared when the fetch settles before the deadline.
281+
*
282+
* Any fetch error or timeout → `{ action: "show-profile" }` (never strands
283+
* onboarding).
284+
*/
285+
export async function resolveProfileCheckAction(
286+
fetchProfile: () => Promise<Profile>,
287+
timeoutMs: number,
288+
scheduleTimeout: (
289+
fn: () => void,
290+
ms: number,
291+
) => ReturnType<typeof setTimeout> = (fn, ms) => window.setTimeout(fn, ms),
292+
): Promise<ProfileCheckAction> {
293+
let timerId: ReturnType<typeof setTimeout> | undefined;
294+
try {
295+
const profile = await Promise.race([
296+
fetchProfile(),
297+
new Promise<never>(
298+
(_, reject) =>
299+
(timerId = scheduleTimeout(
300+
() => reject(new Error("profile-check-timeout")),
301+
timeoutMs,
302+
)),
303+
),
304+
]);
305+
return shouldSkipCommunityOnboarding(profile)
306+
? { action: "skip", profile }
307+
: { action: "show-profile" };
308+
} catch {
309+
return { action: "show-profile" };
310+
} finally {
311+
if (timerId !== undefined) clearTimeout(timerId);
312+
}
313+
}
314+
230315
import * as React from "react";
231316

232317
type CommunityOnboardingContextValue = {

0 commit comments

Comments
 (0)