Repository navigation
Expand file tree
/
Copy pathApp.tsx
More file actions
811 lines (751 loc) · 28 KB
/
Copy pathApp.tsx
File metadata and controls
811 lines (751 loc) · 28 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
import { isTauri } from "@tauri-apps/api/core";
import { emit } from "@tauri-apps/api/event";
import { QueryClientProvider } from "@tanstack/react-query";
import { RouterProvider } from "@tanstack/react-router";
import {
type ReactNode,
useCallback,
useEffect,
useLayoutEffect,
useReducer,
useRef,
useState,
} from "react";
import { router } from "@/app/router";
import {
completeCommunityViewTransition,
replaceCommunityDestinationRoute,
} from "@/app/communityViewTransition";
import { deriveShellRoute } from "@/app/AppShell.helpers";
import { ThemeGrainientBackground } from "@/app/ThemeGrainientBackground";
import { CommunityThemeController } from "@/shared/theme/CommunityThemeController";
import { useReloadShortcut } from "@/app/useReloadShortcut";
import { useCloseWindowShortcut } from "@/app/useCloseWindowShortcut";
import { KnownAgentPubkeysProvider } from "@/features/agents/useKnownAgentPubkeys";
import { huddleWindowChannelId } from "@/features/huddle/lib/huddleWindow";
import { useAppOnboardingState } from "@/features/onboarding/hooks";
import { useMachineOnboardingState } from "@/features/onboarding/machineOnboarding";
import {
type FirstCommunityPage,
useCommunityOnboarding,
markCommunityOnboardingComplete,
resolveProfileCheckAction,
isTransactionStillConnecting,
} from "@/features/onboarding/communityOnboarding";
import { CommunityOnboardingFlow } from "@/features/onboarding/ui/CommunityOnboardingFlow";
import {
MachineOnboardingFlow,
type MachineOnboardingPage,
} from "@/features/onboarding/ui/MachineOnboardingFlow";
import { OnboardingFlow } from "@/features/onboarding/ui/OnboardingFlow";
import { PendingInviteGate } from "@/features/onboarding/ui/PendingInviteGate";
import { KeyringLockedScreen } from "@/features/onboarding/ui/KeyringLockedScreen";
import { RelaunchRequiredScreen } from "@/features/onboarding/ui/RelaunchRequiredScreen";
import { ResetFailedScreen } from "@/features/onboarding/ui/ResetFailedScreen";
import { loadCommunityDiscoveryAfterLeave } from "@/features/communities/communityStorage";
import { useCommunityInit } from "@/features/communities/useCommunityInit";
import { useNestNotifications } from "@/features/communities/useNestNotifications";
import { useCommunities } from "@/features/communities/useCommunities";
import {
loadCommunityDestination,
markPendingCommunityRestore,
saveCommunityDestination,
} from "@/features/communities/communityNavigationStorage";
import {
onAddCommunityPrefillAvailable,
requestAddCommunityPrefill,
} from "@/features/communities/addCommunityPrefill";
import { WelcomeSetup } from "@/features/communities/ui/WelcomeSetup";
import { CommunityApplyErrorScreen } from "@/features/communities/ui/CommunityApplyErrorScreen";
import { CommunityChangeOverlay } from "@/features/communities/ui/CommunityChangeOverlay";
import { setAvatarProfileSyncQueryClient } from "@/features/profile/avatarProfileSync";
import { seedProjectSnapshot } from "@/features/projects/projectSnapshot";
import { EncryptedBackupProvider } from "@/features/settings/EncryptedBackupProvider";
import { createBuzzQueryClient } from "@/shared/api/queryClient";
import { hydrateChannelHeads } from "@/features/messages/lib/channelHeadCache";
import { useIdentityQuery } from "@/shared/api/hooks";
import { isSharedIdentity as isSharedIdentityCmd } from "@/shared/api/tauri";
import { getProfile } from "@/shared/api/tauriProfiles";
import {
type AddCommunityDeepLinkPayload,
listenForDeepLinks,
} from "@/shared/deep-link";
import { cn } from "@/shared/lib/cn";
import { BuzzMark } from "@/shared/ui/buzz-logo/BuzzMark";
import { FlappingBee } from "@/shared/ui/buzz-logo/FlappingBee";
import { FuzzyLogo } from "@/shared/ui/buzz-logo/FuzzyLogo";
import { StartupWindowDragRegion } from "@/shared/ui/StartupWindowDragRegion";
const LOADING_TEXT = "Setting up your community...";
// Minimum time the cold-boot splash stays on screen. A real boot resolves the
// community in well under 100ms, and the native window setup plus first paint
// can take longer than that — without a hold, the bee is unmounted before it is
// ever visible. The hold runs as an overlay above the already-mounted app, so
// time-to-interactive is unchanged; only the reveal waits.
const BOOT_SPLASH_MIN_VISIBLE_MS = 1_200;
const BOOT_SPLASH_FADE_MS = 200;
const INITIAL_RENDER_READY_EVENT = "initial-render-ready";
type BootSplashPhase = "holding" | "fading" | "done";
function useInitialRenderReady() {
useLayoutEffect(() => {
if (!isTauri()) {
return;
}
void emit(INITIAL_RENDER_READY_EVENT);
}, []);
}
// E2E runs skip the hold (it would slow every spec's boot and block pointer
// actionability); a spec can opt back in via __BUZZ_E2E__.bootSplashHoldMs.
function bootSplashHoldMs(): number {
const e2e = (
window as Window & {
__BUZZ_E2E__?: { bootSplashHoldMs?: number };
}
).__BUZZ_E2E__;
if (e2e) {
return e2e.bootSplashHoldMs ?? 0;
}
return BOOT_SPLASH_MIN_VISIBLE_MS;
}
function useBootSplashHold(): BootSplashPhase {
const [phase, setPhase] = useState<BootSplashPhase>(() =>
bootSplashHoldMs() > 0 ? "holding" : "done",
);
useEffect(() => {
const holdMs = bootSplashHoldMs();
if (holdMs <= 0) {
return;
}
const fadeTimer = window.setTimeout(() => setPhase("fading"), holdMs);
const doneTimer = window.setTimeout(
() => setPhase("done"),
holdMs + BOOT_SPLASH_FADE_MS,
);
return () => {
window.clearTimeout(fadeTimer);
window.clearTimeout(doneTimer);
};
}, []);
return phase;
}
// Animated Buzz mark for the loading gates. The static BuzzMark renders in
// normal flow and sizes the box — it's plain SVG (no JS/SMIL), so it paints on
// the very first frame even before scripting starts, avoiding a blank flash on
// hard reload. The animated FuzzyLogo is layered on top and takes over once it
// begins playing.
function BeeLoader({
ariaLabel,
className,
tintClassName = "text-foreground",
}: {
ariaLabel: string;
className?: string;
tintClassName?: string;
}) {
return (
<div className={cn("relative", tintClassName, className)}>
<BuzzMark className="block h-auto w-full" />
<FuzzyLogo
ariaLabel={ariaLabel}
className="absolute inset-0 h-full! w-full! [&>svg]:h-full [&>svg]:w-full [&>svg]:max-w-full"
fuzz
loop
loopRestSeconds={0}
/>
</div>
);
}
// Cold boot gate: the theme-adaptive grainient background with a single
// centered Buzz bee flying over it — the same static mark as before, now with
// its wings flapping (ported from the Buzz website's wing-flap). Replaces the
// old "Setting up your community" text, which stays as an sr-only caption.
function AppLoadingGate() {
return (
<div
className="buzz-setup-loading-shell flex min-h-dvh flex-col items-center justify-center overflow-hidden px-6 py-10"
data-testid="app-loading-gate"
role="status"
>
<StartupWindowDragRegion />
<ThemeGrainientBackground />
<span className="sr-only">{LOADING_TEXT}</span>
<FlappingBee className="relative z-10 h-auto w-28" />
</div>
);
}
// Quiet gate for switching between already-set-up communities: visually empty
// unless the switch takes long, so fast switches don't flash the boot splash.
function CommunitySwitchGate() {
const [showSpinner, setShowSpinner] = useState(false);
useEffect(() => {
const timer = window.setTimeout(() => setShowSpinner(true), 300);
return () => window.clearTimeout(timer);
}, []);
return (
<div
className="flex min-h-dvh items-center justify-center bg-background"
data-testid="community-switch-gate"
role="status"
>
<StartupWindowDragRegion />
<span className="sr-only">Switching community…</span>
{showSpinner ? (
<BeeLoader
ariaLabel="Switching community…"
className="h-auto w-20"
tintClassName="text-muted-foreground"
/>
) : null}
</div>
);
}
function CommunityQueryProvider({
children,
pubkey,
relayUrl,
}: {
children: ReactNode;
pubkey: string | null;
relayUrl: string | null;
}) {
// Seeding persisted channel heads is part of constructing the client, not a
// gate in front of the app: the splash, AppReady, and relay preconnect mount
// immediately, and only the channel query waits on the cache load (see
// channelHeadHydration). It must start here rather than in an effect —
// React Query fires a child's queryFn when it subscribes, before any parent
// effect runs — and StrictMode's dev-only double initializer just issues one
// redundant read on a discarded client. The provider is keyed on the
// community, so one client maps to one {pubkey, relayUrl} scope.
const [queryClient] = useState(() => {
const client = createBuzzQueryClient();
if (pubkey && relayUrl) {
seedProjectSnapshot(client, { pubkey, relayUrl });
void hydrateChannelHeads(client, { pubkey, relayUrl });
}
return client;
});
useEffect(() => setAvatarProfileSyncQueryClient(queryClient), [queryClient]);
useEffect(() => {
const e2eWindow = window as Window & {
__BUZZ_E2E__?: unknown;
__BUZZ_E2E_QUERY_CLIENT__?: typeof queryClient;
};
if (!e2eWindow.__BUZZ_E2E__) {
return;
}
e2eWindow.__BUZZ_E2E_QUERY_CLIENT__ = queryClient;
return () => {
if (e2eWindow.__BUZZ_E2E_QUERY_CLIENT__ === queryClient) {
delete e2eWindow.__BUZZ_E2E_QUERY_CLIENT__;
}
};
}, [queryClient]);
return (
<QueryClientProvider client={queryClient}>{children}</QueryClientProvider>
);
}
/**
* Watches the community-scoped identity query and fires once the active
* pubkey changes after mount — i.e. an in-app key import through the
* relay-scoped onboarding flow, which writes the new identity to the
* community query client only. The parent uses the signal to rebuild the
* entire community boundary (query client, AppReady subtree, module
* singletons via useCommunityInit) so a replacement identity never inherits
* the previous identity's cached queries or draft-store bucket.
*/
function CommunityIdentityReplacementSentinel({
onIdentityReplaced,
}: {
onIdentityReplaced: () => void;
}) {
const identityQuery = useIdentityQuery();
const pubkey = identityQuery.data?.pubkey ?? null;
const baselinePubkeyRef = useRef<string | null>(null);
useEffect(() => {
if (!pubkey) return;
if (baselinePubkeyRef.current === null) {
baselinePubkeyRef.current = pubkey;
return;
}
if (baselinePubkeyRef.current !== pubkey) {
baselinePubkeyRef.current = pubkey;
onIdentityReplaced();
}
}, [pubkey, onIdentityReplaced]);
return null;
}
function AppReady({
continueOnboarding,
isSharedIdentity,
isCommunitySwitch,
}: {
continueOnboarding: boolean;
isSharedIdentity: boolean;
isCommunitySwitch: boolean;
}) {
const onboarding = useAppOnboardingState(isSharedIdentity);
if (onboarding.stage === "reset-failed") {
return <ResetFailedScreen />;
}
if (onboarding.stage === "keyring-locked") {
return <KeyringLockedScreen />;
}
if (onboarding.stage === "relaunch-required") {
return <RelaunchRequiredScreen />;
}
if (
onboarding.stage === "onboarding" ||
(continueOnboarding && onboarding.stage === "blocking")
) {
return (
<OnboardingFlow
actions={onboarding.flow.actions}
identityLost={onboarding.identityLost}
initialProfile={onboarding.flow.initialProfile}
key={onboarding.currentPubkey ?? "anonymous"}
/>
);
}
if (onboarding.stage === "blocking") {
return isCommunitySwitch ? <CommunitySwitchGate /> : <AppLoadingGate />;
}
return (
<EncryptedBackupProvider
onOpenSettings={() =>
void router.navigate({
to: "/settings",
search: { section: "profile" },
})
}
>
<KnownAgentPubkeysProvider>
<RouterProvider router={router} />
</KnownAgentPubkeysProvider>
</EncryptedBackupProvider>
);
}
function CommunityApp({
continueOnboarding,
currentPubkey,
onBackToMachineConfig,
sharedIdentity,
}: {
continueOnboarding: boolean;
currentPubkey: string | null;
onBackToMachineConfig: () => void;
sharedIdentity: boolean;
}) {
const {
activeCommunity,
communities,
reinitKey,
addCommunity,
clearCommunities,
removeCommunity,
switchCommunity,
reconnectCommunity,
} = useCommunities();
const communityOnboarding = useCommunityOnboarding();
const connectingTransactionRef = useRef<string | null>(null);
// Tracks the ID of the profile-check request that has been launched for the
// current connecting transaction. Prevents the effect from launching a
// second request if it re-runs while a fetch is in flight.
const profileCheckTransactionRef = useRef<string | null>(null);
// Always reflects the live transaction object so async callbacks can perform
// an atomic check of both ID and stage before mutating state.
const transactionRef = useRef(communityOnboarding.transaction);
transactionRef.current = communityOnboarding.transaction;
const [isCommunityChangeOpen, setIsCommunityChangeOpen] = useState(false);
const [resumeFirstCommunityPage, setResumeFirstCommunityPage] =
useState<FirstCommunityPage | null>(null);
const isFindingCommunityAfterLeave =
activeCommunity === null && loadCommunityDiscoveryAfterLeave();
// Surface nest-related backend events (repos-dir errors, legacy migration)
// as toasts. Mounted before useCommunityInit so the listeners are registered
// ahead of the first apply_workspace call.
useNestNotifications();
// Increments when the community-scoped identity is replaced in-app (key
// import through the relay onboarding flow). Machine-level identity changes
// already reach this component through the currentPubkey prop; this covers
// imports that only the community query client observes.
const [signerEpoch, bumpSignerEpoch] = useReducer(
(epoch: number) => epoch + 1,
0,
);
// Composite key: changes when the community ID changes, when the active
// community's config is updated (relayUrl/token), or when the signing
// identity is replaced. Keying CommunityQueryProvider and AppReady on the
// signer guarantees a replacement identity never sees the previous
// identity's query cache, React state, or draft-store bucket.
const communityKey = `${activeCommunity?.id ?? "none"}-${reinitKey}-${currentPubkey ?? "anonymous"}-${signerEpoch}`;
// Latch once the community key deviates from its cold-boot value: from then
// on, loading phases are in-app switches and get the quiet gate instead of
// the full "Setting up your community" splash.
const initialCommunityKeyRef = useRef(communityKey);
const hasSwitchedCommunityRef = useRef(false);
if (communityKey !== initialCommunityKeyRef.current) {
hasSwitchedCommunityRef.current = true;
}
const isCommunitySwitch = hasSwitchedCommunityRef.current;
const isContinuingOnboarding = continueOnboarding && !isCommunitySwitch;
const community = useCommunityInit(
activeCommunity,
communityKey,
sharedIdentity,
isFindingCommunityAfterLeave,
);
const transitionCommunity = useCallback(
async (targetCommunityId: string) => {
const activeCommunityId = activeCommunity?.id;
if (targetCommunityId === activeCommunityId) return;
if (activeCommunityId) {
const route = deriveShellRoute(router.state.location.pathname);
saveCommunityDestination(
activeCommunityId,
route.selectedView === "channel" && route.selectedChannelId
? { kind: "channel", channelId: route.selectedChannelId }
: { kind: "home" },
);
await router.navigate({ to: "/", replace: true });
markPendingCommunityRestore(targetCommunityId);
const destination = loadCommunityDestination(targetCommunityId);
if (destination?.kind === "channel") {
replaceCommunityDestinationRoute(
destination.channelId,
router.history,
);
}
}
switchCommunity(targetCommunityId);
},
[activeCommunity?.id, switchCommunity],
);
const handleCommunityOnboardingConnect = useCallback(async () => {
const transaction = communityOnboarding.transaction;
if (transaction?.stage !== "connecting") return;
if (connectingTransactionRef.current === transaction.id) return;
connectingTransactionRef.current = transaction.id;
if (transaction.communityId) {
await transitionCommunity(transaction.communityId);
return;
}
const previousCommunityId = activeCommunity?.id;
const relayAlreadyExists = communities.some(
(community) => community.relayUrl === transaction.relayUrl,
);
const id = addCommunity({
id: crypto.randomUUID(),
name: transaction.communityName,
relayUrl: transaction.relayUrl,
token: transaction.token,
reposDir: transaction.reposDir,
pubkey: currentPubkey ?? undefined,
addedAt: new Date().toISOString(),
});
communityOnboarding.update({
communityId: id,
previousCommunityId,
addedCommunity: !relayAlreadyExists,
error: undefined,
});
await transitionCommunity(id);
reconnectCommunity();
}, [
activeCommunity?.id,
addCommunity,
communities,
communityOnboarding,
currentPubkey,
reconnectCommunity,
transitionCommunity,
]);
const handleCommunityOnboardingCancel = useCallback(async () => {
const transaction = communityOnboarding.transaction;
communityOnboarding.clear();
if (!transaction?.communityId) return;
if (!transaction.addedCommunity) {
if (transaction.previousCommunityId) {
await transitionCommunity(transaction.previousCommunityId);
}
return;
}
if (communities.length === 1) {
if (transaction.source === "first-community") {
setResumeFirstCommunityPage(transaction.firstCommunityPage ?? "join");
}
clearCommunities();
return;
}
if (transaction.previousCommunityId) {
await transitionCommunity(transaction.previousCommunityId);
}
removeCommunity(transaction.communityId);
}, [
clearCommunities,
communities.length,
communityOnboarding,
removeCommunity,
transitionCommunity,
]);
const bootSplashPhase = useBootSplashHold();
const transaction = communityOnboarding.transaction;
useEffect(() => {
if (transaction?.stage !== "connecting") {
connectingTransactionRef.current = null;
profileCheckTransactionRef.current = null;
}
}, [transaction?.stage]);
const targetIsReady =
transaction?.communityId === activeCommunity?.id &&
community.isReady &&
community.appliedKey === communityKey;
useEffect(() => {
if (transaction?.stage !== "connecting" || !targetIsReady) return;
const transactionId = transaction.id;
const relayUrl = transaction.relayUrl;
if (profileCheckTransactionRef.current === transactionId) return;
profileCheckTransactionRef.current = transactionId;
// resolveProfileCheckAction resolves exactly once (Promise.race + timer
// cleared on settle), so no settled flag is needed here.
void resolveProfileCheckAction(getProfile, 10_000).then((result) => {
// Atomic staleness guard via isTransactionStillConnecting: the
// transaction must still be the same one that launched this request
// AND still be in connecting. Covers cancel+replacement (B's ID !== A's)
// and cancel-without-replacement (transactionRef.current is null).
if (!isTransactionStillConnecting(transactionRef.current, transactionId))
return;
if (result.action === "skip") {
markCommunityOnboardingComplete(result.profile.pubkey, relayUrl);
communityOnboarding.clear();
} else {
communityOnboarding.update(
{ stage: "profile", error: undefined },
transactionId,
);
}
});
}, [
communityOnboarding,
targetIsReady,
transaction?.stage,
transaction?.id,
transaction?.relayUrl,
]);
// During "entering" the transaction stays alive as a curtain: the app mounts
// underneath (already pointed at the Welcome channel route) while the
// onboarding screen covers it, then fades once Welcome reports ready.
//
// The flow must keep ONE stable position in the element tree across every
// stage. Rendering it from a different slot when the stage flips to
// "entering" would remount it — React state resets and the "Meet your
// starter team" screen visibly restarts mid-handoff.
const isEnteringCurtain = transaction?.stage === "entering";
// The app mounts (and starts loading data) beneath the splash overlay; the
// overlay just keeps the bee on screen long enough to be seen, then fades.
// Community switches keep their quiet gate.
const showBootSplashOverlay =
bootSplashPhase !== "done" && !isCommunitySwitch && !isContinuingOnboarding;
let appContent: ReactNode = null;
if (!transaction) {
if (community.needsSetup) {
// Show welcome setup for first-run users with no communities
appContent = (
<WelcomeSetup
initialPage={resumeFirstCommunityPage ?? undefined}
onBack={
isFindingCommunityAfterLeave ? undefined : onBackToMachineConfig
}
/>
);
} else if ("error" in community && community.error) {
// Surface apply failures so the user can retry or change community.
appContent = (
<>
<CommunityApplyErrorScreen
error={community.error}
onChangeCommunity={() => setIsCommunityChangeOpen(true)}
onRetry={reconnectCommunity}
/>
{isCommunityChangeOpen ? (
<CommunityChangeOverlay
onClose={() => setIsCommunityChangeOpen(false)}
/>
) : null}
</>
);
}
}
// Wait for this exact community config to be applied to the backend before
// rendering anything that connects to the relay. The appliedKey check avoids
// a one-render race where React sees the new active community while the
// Tauri backend is still configured for the previous one.
const communityApplied =
community.isReady && community.appliedKey === communityKey;
useLayoutEffect(() => {
if (communityApplied) {
completeCommunityViewTransition();
}
}, [communityApplied]);
if (appContent === null && (!transaction || isEnteringCurtain)) {
appContent = communityApplied ? (
<CommunityQueryProvider
key={communityKey}
pubkey={community.identityPubkey}
relayUrl={activeCommunity?.relayUrl ?? null}
>
<CommunityIdentityReplacementSentinel
onIdentityReplaced={bumpSignerEpoch}
/>
<CommunityThemeController />
<AppReady
continueOnboarding={isContinuingOnboarding}
isCommunitySwitch={isCommunitySwitch}
key={communityKey}
isSharedIdentity={sharedIdentity}
/>
{showBootSplashOverlay ? (
<div
aria-hidden="true"
className={cn(
"fixed inset-0 z-50 transition-opacity",
bootSplashPhase === "fading" ? "opacity-0" : "opacity-100",
)}
data-testid="boot-splash-overlay"
style={{ transitionDuration: `${BOOT_SPLASH_FADE_MS}ms` }}
>
<AppLoadingGate />
</div>
) : null}
</CommunityQueryProvider>
) : isCommunitySwitch || isContinuingOnboarding ? (
<CommunitySwitchGate />
) : (
<AppLoadingGate />
);
}
return (
<>
{appContent}
{transaction ? (
<div
className={isEnteringCurtain ? "fixed inset-0 z-50" : undefined}
data-testid={
isEnteringCurtain ? "onboarding-entering-curtain" : undefined
}
>
<CommunityOnboardingFlow
onCancel={handleCommunityOnboardingCancel}
onConnect={handleCommunityOnboardingConnect}
/>
</div>
) : null}
</>
);
}
function MachineBootstrap({ sharedIdentity }: { sharedIdentity: boolean }) {
const { activeCommunity } = useCommunities();
const communityOnboarding = useCommunityOnboarding();
const machine = useMachineOnboardingState({
activeCommunityPubkey: activeCommunity
? (activeCommunity.pubkey ?? null)
: undefined,
isSharedIdentity: sharedIdentity,
});
const [machineInitialPage, setMachineInitialPage] =
useState<MachineOnboardingPage>();
const [continueOnboarding, setContinueOnboarding] = useState(false);
const reopenMachineConfig = useCallback(() => {
setContinueOnboarding(false);
setMachineInitialPage("config");
machine.reopen();
}, [machine.reopen]);
const completeMachineOnboarding = useCallback(
(pubkey?: string, options?: { continueToProfile?: boolean }) => {
setContinueOnboarding(options?.continueToProfile === true);
setMachineInitialPage(undefined);
machine.complete(pubkey);
},
[machine.complete],
);
const openAddCommunity = useCallback(
(payload: AddCommunityDeepLinkPayload & { requestId: string }) =>
activeCommunity
? requestAddCommunityPrefill(payload)
: communityOnboarding.start({
source: "add-community",
relayUrl: payload.relayUrl,
communityName: payload.name,
}),
[activeCommunity, communityOnboarding.start],
);
// Community links are app-global work. A Huddle companion loads the same
// React tree, but must never race the main window for the native pending-link
// queue or replace its dedicated transcript surface with onboarding.
const acceptsCommunityDeepLinks = huddleWindowChannelId() === null;
useEffect(() => {
if (!acceptsCommunityDeepLinks) return;
const unlisten = listenForDeepLinks({
startCommunityOnboarding: communityOnboarding.start,
openAddCommunity,
onAddCommunityAvailable: onAddCommunityPrefillAvailable,
});
return () => {
void unlisten.then((fn) => fn());
};
}, [acceptsCommunityDeepLinks, communityOnboarding.start, openAddCommunity]);
if (machine.stage === "reset-failed") return <ResetFailedScreen />;
if (machine.stage === "keyring-locked") return <KeyringLockedScreen />;
if (machine.stage === "relaunch-required") return <RelaunchRequiredScreen />;
if (machine.stage === "blocking") return <AppLoadingGate />;
if (machine.stage === "ready") {
return (
<CommunityApp
continueOnboarding={continueOnboarding}
currentPubkey={machine.currentPubkey}
onBackToMachineConfig={reopenMachineConfig}
sharedIdentity={sharedIdentity}
/>
);
}
// A community deep link that arrived before machine onboarding finished is
// persisted immediately and acknowledged here. Invite claiming waits until
// setup completes so it is signed only by the user's final identity.
const transaction = communityOnboarding.transaction;
const isDeepLink =
transaction?.source === "deep-link-join" ||
transaction?.source === "deep-link-connect";
const shouldAcknowledgeDeepLink = isDeepLink && !transaction.acknowledged;
return (
<>
<MachineOnboardingFlow
complete={completeMachineOnboarding}
continueWithIdentity={machine.continueWithIdentity}
continueWithRecoveredIdentity={machine.continueWithRecoveredIdentity}
identityLost={machine.identityLost}
initialPage={machineInitialPage}
queryClient={machine.queryClient}
/>
{shouldAcknowledgeDeepLink ? <PendingInviteGate /> : null}
</>
);
}
export function App() {
useReloadShortcut();
useCloseWindowShortcut();
useInitialRenderReady();
const [sharedIdentity, setSharedIdentity] = useState<boolean | null>(null);
const [queryClient] = useState(createBuzzQueryClient);
useEffect(() => {
isSharedIdentityCmd()
.then(setSharedIdentity)
.catch((err) => {
console.warn("is_shared_identity command failed:", err);
setSharedIdentity(false);
});
}, []);
if (sharedIdentity === null) return <AppLoadingGate />;
return (
<QueryClientProvider client={queryClient}>
<MachineBootstrap sharedIdentity={sharedIdentity} />
</QueryClientProvider>
);
}