@shellui/core 0.5.3 → 0.6.0-beta.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (113) hide show
  1. package/README.md +2 -0
  2. package/package.json +6 -4
  3. package/schemas/shellui.config.schema.json +104 -64
  4. package/src/app.tsx +5 -3
  5. package/src/components/ContentView.tsx +14 -23
  6. package/src/components/LoadingOverlay.tsx +1 -1
  7. package/src/components/ui/sonner.spec.tsx +138 -0
  8. package/src/components/ui/sonner.tsx +5 -5
  9. package/src/components/ui/switch.tsx +1 -1
  10. package/src/features/admin/AdminView.tsx +14 -3
  11. package/src/features/ai/AiBridge.tsx +106 -0
  12. package/src/features/ai/AiUnavailableResponder.tsx +39 -0
  13. package/src/features/ai/README.md +52 -0
  14. package/src/features/ai/ShellAiHost.tsx +24 -0
  15. package/src/features/ai/adapters/ollama.ts +170 -0
  16. package/src/features/ai/adapters/promptApi.spec.ts +135 -0
  17. package/src/features/ai/adapters/promptApi.ts +222 -0
  18. package/src/features/ai/adapters/webllm.experimental.spec.ts +69 -0
  19. package/src/features/ai/adapters/webllm.spec.ts +527 -0
  20. package/src/features/ai/adapters/webllm.ts +142 -0
  21. package/src/features/ai/aiDisabledResponses.spec.ts +29 -0
  22. package/src/features/ai/aiDisabledResponses.ts +32 -0
  23. package/src/features/ai/browserInstallStore.spec.ts +58 -0
  24. package/src/features/ai/browserInstallStore.ts +76 -0
  25. package/src/features/ai/catalog.ts +31 -0
  26. package/src/features/ai/createRegistry.ts +83 -0
  27. package/src/features/ai/developHarness.spec.ts +108 -0
  28. package/src/features/ai/developHarness.ts +161 -0
  29. package/src/features/ai/engine/formatAiError.spec.ts +85 -0
  30. package/src/features/ai/engine/formatAiError.ts +132 -0
  31. package/src/features/ai/engine/mapInitProgress.ts +9 -0
  32. package/src/features/ai/engine/normalizeWebLlmModule.spec.ts +47 -0
  33. package/src/features/ai/engine/vite-worker.d.ts +6 -0
  34. package/src/features/ai/engine/webllm.worker.ts +51 -0
  35. package/src/features/ai/engine/webllmEngine.ts +1011 -0
  36. package/src/features/ai/handleRequest.spec.ts +288 -0
  37. package/src/features/ai/handleRequest.ts +325 -0
  38. package/src/features/ai/isAiFeatureEnabled.spec.ts +15 -0
  39. package/src/features/ai/isAiFeatureEnabled.ts +9 -0
  40. package/src/features/ai/promptApiSupport.spec.ts +64 -0
  41. package/src/features/ai/promptApiSupport.ts +117 -0
  42. package/src/features/ai/registry.spec.ts +100 -0
  43. package/src/features/ai/registry.ts +131 -0
  44. package/src/features/ai/status.spec.ts +92 -0
  45. package/src/features/ai/status.ts +85 -0
  46. package/src/features/ai/types.ts +100 -0
  47. package/src/features/ai/webLlmBrowserSupport.spec.ts +86 -0
  48. package/src/features/ai/webLlmBrowserSupport.ts +92 -0
  49. package/src/features/alertDialog/DialogContext.tsx +3 -1
  50. package/src/features/auth/AuthProvider.tsx +254 -39
  51. package/src/features/auth/backends/index.ts +8 -0
  52. package/src/features/auth/backends/shellui.spec.ts +201 -0
  53. package/src/features/auth/backends/shellui.ts +93 -16
  54. package/src/features/auth/backends/supabase.ts +8 -0
  55. package/src/features/auth/backends/types.ts +16 -1
  56. package/src/features/auth/components/LoginButton.tsx +26 -2
  57. package/src/features/auth/components/LoginView.tsx +114 -133
  58. package/src/features/auth/components/SessionLoadingView.tsx +21 -0
  59. package/src/features/auth/hooks/useAuth.tsx +12 -0
  60. package/src/features/auth/shellAccountRequests.ts +76 -0
  61. package/src/features/auth/utils/authRequestError.ts +4 -1
  62. package/src/features/auth/utils/authSessionPersistence.spec.ts +11 -0
  63. package/src/features/auth/utils/authSessionPersistence.ts +12 -0
  64. package/src/features/auth/utils/index.ts +4 -0
  65. package/src/features/auth/utils/resolveLoginSettings.spec.ts +33 -0
  66. package/src/features/auth/utils/resolveLoginSettings.ts +33 -0
  67. package/src/features/auth/utils/shareInFlight.spec.ts +41 -0
  68. package/src/features/auth/utils/shareInFlight.ts +14 -0
  69. package/src/features/config/ConfigProvider.ts +9 -1
  70. package/src/features/config/types.ts +43 -0
  71. package/src/features/layouts/appbar/AppBarLayout.tsx +8 -3
  72. package/src/features/layouts/filterNavigationForAuthState.spec.ts +41 -0
  73. package/src/features/layouts/floating/FloatingLayout.tsx +9 -4
  74. package/src/features/layouts/floating/layoutChromeStore.ts +3 -1
  75. package/src/features/layouts/sidebar/SidebarLayout.tsx +9 -4
  76. package/src/features/layouts/utils.ts +6 -2
  77. package/src/features/layouts/windows/WindowsLayout.tsx +8 -3
  78. package/src/features/messaging/MessagingSecurityBootstrap.tsx +6 -6
  79. package/src/features/security/trustedFrames.spec.ts +65 -0
  80. package/src/features/security/trustedFrames.ts +52 -0
  81. package/src/features/settings/SettingsIcons.tsx +17 -0
  82. package/src/features/settings/SettingsProvider.tsx +29 -4
  83. package/src/features/settings/SettingsRoutes.tsx +8 -0
  84. package/src/features/settings/SettingsView.tsx +21 -4
  85. package/src/features/settings/components/Ai.tsx +830 -0
  86. package/src/features/settings/components/Develop.tsx +4 -0
  87. package/src/features/settings/components/Storage.tsx +197 -32
  88. package/src/features/settings/components/UserSettingsPanel.tsx +160 -12
  89. package/src/features/settings/components/createUserSettingsRoute.tsx +4 -0
  90. package/src/features/settings/components/develop/AiTestTools.tsx +231 -0
  91. package/src/features/settings/utils/buildSettingsForPropagation.spec.ts +54 -1
  92. package/src/features/settings/utils/buildSettingsForPropagation.ts +15 -1
  93. package/src/features/settings/utils/mergePreferencesIntoSettings.spec.ts +6 -0
  94. package/src/features/settings/utils/shouldShowStorageSettings.spec.ts +49 -0
  95. package/src/features/settings/utils/shouldShowStorageSettings.ts +19 -0
  96. package/src/features/storage/uploads/UploadToastCard.tsx +2 -442
  97. package/src/features/storage/uploads/UploadToaster.tsx +2 -44
  98. package/src/features/storage/uploads/uploadQueue.ts +128 -308
  99. package/src/features/storage/uploads/useUploadQueue.ts +7 -3
  100. package/src/features/transfers/TransferToastCard.tsx +467 -0
  101. package/src/features/transfers/TransferToaster.tsx +50 -0
  102. package/src/features/transfers/index.ts +33 -0
  103. package/src/features/transfers/transferQueue.spec.ts +97 -0
  104. package/src/features/transfers/transferQueue.ts +442 -0
  105. package/src/features/transfers/types.ts +38 -0
  106. package/src/features/transfers/useTransferQueue.ts +30 -0
  107. package/src/i18n/translations/en/common.json +46 -2
  108. package/src/i18n/translations/en/settings.json +151 -2
  109. package/src/i18n/translations/fr/common.json +46 -2
  110. package/src/i18n/translations/fr/settings.json +151 -2
  111. package/src/index.css +57 -4
  112. package/src/index.ts +1 -0
  113. package/src/routes/components/NavigationItemRoute.tsx +2 -1
@@ -18,9 +18,9 @@ import {
18
18
  getPreferredBackendProvider,
19
19
  getProviderVisual,
20
20
  isAccessPendingErrorCode,
21
- isLoginMethod,
22
21
  normalizeNextPath,
23
22
  redirectToCliCallback,
23
+ resolveLoginSettings,
24
24
  } from '../utils';
25
25
  import { AppBrandIcon } from '../../layouts/branding/AppBrandIcon';
26
26
  import { DESKTOP_TITLEBAR_HEIGHT_PX } from '../../layouts/chrome/constants';
@@ -35,6 +35,8 @@ const LOGIN_CHROME_PAD_Y = '2rem';
35
35
  const LOGIN_BRAND_BELOW_TITLEBAR_GAP = '0.75rem';
36
36
 
37
37
  const LAST_USED_LOGIN_STORAGE_KEY = 'shellui.auth.last_used_login';
38
+ /** Seconds before the user can go back to the form and request another magic link. */
39
+ const MAGIC_LINK_RESEND_COOLDOWN_SECONDS = 60;
38
40
 
39
41
  const SHELLUI_OAUTH_ERROR_PARAM = 'shellui_oauth_error';
40
42
  const SHELLUI_OAUTH_ERROR_CODE_PARAM = 'shellui_oauth_error_code';
@@ -105,30 +107,16 @@ export const LoginView = () => {
105
107
  sendMagicLink,
106
108
  session,
107
109
  } = useAuth();
108
- const configuredSettings = useMemo<AuthSettings>(() => {
109
- const configuredMethods = Array.isArray(config.backend?.login?.methods)
110
- ? config.backend.login.methods.filter(isLoginMethod)
111
- : [];
112
- const configuredProvidersRaw = Array.isArray(config.backend?.login?.oauthProviders)
113
- ? config.backend.login.oauthProviders
114
- .filter(
115
- (provider): provider is string =>
116
- typeof provider === 'string' && provider.trim() !== '',
117
- )
118
- .map((provider) => provider.toLowerCase())
119
- : [];
120
- const configuredProviders = Array.from(new Set(configuredProvidersRaw));
121
- return {
122
- methods: configuredMethods,
123
- oauthProviders: configuredProviders,
124
- oauthClients: [],
125
- };
126
- }, [config.backend?.login?.methods, config.backend?.login?.oauthProviders]);
110
+ const configuredSettings = useMemo<AuthSettings>(
111
+ () => resolveLoginSettings(config.backend),
112
+ [config.backend],
113
+ );
127
114
  const [oauthLoadingProvider, setOauthLoadingProvider] = useState<string | null>(null);
128
115
  const [web3Loading, setWeb3Loading] = useState(false);
129
116
  const [magicLinkEmail, setMagicLinkEmail] = useState('');
130
117
  const [magicLinkLoading, setMagicLinkLoading] = useState(false);
131
- const [magicLinkMessage, setMagicLinkMessage] = useState<string | null>(null);
118
+ const [magicLinkSentTo, setMagicLinkSentTo] = useState<string | null>(null);
119
+ const [magicLinkCooldown, setMagicLinkCooldown] = useState(0);
132
120
  const [magicLinkError, setMagicLinkError] = useState<string | null>(null);
133
121
  const [methodError, setMethodError] = useState<string | null>(null);
134
122
  const [oauthBounceError, setOauthBounceError] = useState<string | null>(null);
@@ -226,18 +214,12 @@ export const LoginView = () => {
226
214
  if (!featuredOAuthProvider) return allOAuthProviders;
227
215
  return allOAuthProviders.filter((provider) => provider !== featuredOAuthProvider);
228
216
  }, [allOAuthProviders, featuredOAuthProvider, supportsOAuth]);
229
- const hasAlternativeMethods = useMemo(() => {
230
- if (featuredMethod === 'oauth') {
231
- return otherOAuthProviders.length > 0 || supportsMagicLink || supportsWeb3;
232
- }
233
- if (featuredMethod === 'web3') {
234
- return supportsOAuth || supportsMagicLink;
235
- }
236
- if (featuredMethod === 'magic_link') {
237
- return (supportsOAuth && otherOAuthProviders.length > 0) || supportsWeb3;
238
- }
239
- return false;
240
- }, [featuredMethod, otherOAuthProviders.length, supportsMagicLink, supportsOAuth, supportsWeb3]);
217
+ const showWeb3Section = supportsWeb3 && featuredMethod !== 'web3';
218
+ const showOAuthSection = supportsOAuth && otherOAuthProviders.length > 0;
219
+ const showMagicLinkSection = supportsMagicLink && featuredMethod !== 'magic_link';
220
+ const hasAlternativeMethods =
221
+ featuredMethod !== null && (showWeb3Section || showOAuthSection || showMagicLinkSection);
222
+ const showMagicLinkDivider = showMagicLinkSection && (showWeb3Section || showOAuthSection);
241
223
  const showAlternatives = featuredMethod === null || showAlternativeMethods;
242
224
  const alternativesAreCollapsible = featuredMethod !== null && hasAlternativeMethods;
243
225
  useEffect(() => {
@@ -319,11 +301,16 @@ export const LoginView = () => {
319
301
  [getAuthSettings, supportsWeb3, t],
320
302
  );
321
303
 
304
+ useEffect(() => {
305
+ if (magicLinkCooldown <= 0) return;
306
+ const timer = window.setTimeout(() => setMagicLinkCooldown((seconds) => seconds - 1), 1000);
307
+ return () => window.clearTimeout(timer);
308
+ }, [magicLinkCooldown]);
309
+
322
310
  const handleOAuthLogin = async (provider: string) => {
323
311
  setMethodError(null);
324
312
  setOauthBounceError(null);
325
313
  setMagicLinkError(null);
326
- setMagicLinkMessage(null);
327
314
  setOauthLoadingProvider(provider);
328
315
  const support = await verifyMethodSupport('oauth', provider);
329
316
  if (!support.isSupported) {
@@ -354,7 +341,6 @@ export const LoginView = () => {
354
341
  const handleWeb3Login = async () => {
355
342
  setMethodError(null);
356
343
  setMagicLinkError(null);
357
- setMagicLinkMessage(null);
358
344
  setWeb3Loading(true);
359
345
  const support = await verifyMethodSupport('web3');
360
346
  if (!support.isSupported) {
@@ -389,13 +375,11 @@ export const LoginView = () => {
389
375
  const email = magicLinkEmail.trim();
390
376
  if (!email) {
391
377
  setMagicLinkError(t('loginPage.enterEmail'));
392
- setMagicLinkMessage(null);
393
378
  setMethodError(null);
394
379
  return;
395
380
  }
396
381
  setMagicLinkLoading(true);
397
382
  setMagicLinkError(null);
398
- setMagicLinkMessage(null);
399
383
  setMethodError(null);
400
384
 
401
385
  try {
@@ -408,8 +392,9 @@ export const LoginView = () => {
408
392
  if (typeof window !== 'undefined') {
409
393
  localStorage.setItem(LAST_USED_LOGIN_STORAGE_KEY, JSON.stringify(rememberedLogin));
410
394
  }
411
- await sendMagicLink(email, loginPathWithNext);
412
- setMagicLinkMessage(t('loginPage.magicLinkSent'));
395
+ await sendMagicLink(email, oauthCallbackPathWithNext);
396
+ setMagicLinkSentTo(email);
397
+ setMagicLinkCooldown(MAGIC_LINK_RESEND_COOLDOWN_SECONDS);
413
398
  } catch (err) {
414
399
  setMagicLinkError(err instanceof Error ? err.message : t('loginPage.couldNotSendMagicLink'));
415
400
  } finally {
@@ -417,6 +402,80 @@ export const LoginView = () => {
417
402
  }
418
403
  };
419
404
 
405
+ const magicLinkContent = magicLinkSentTo ? (
406
+ <div
407
+ role="status"
408
+ className="space-y-3 rounded-xl border border-border bg-background p-4 text-center"
409
+ >
410
+ <div className="mx-auto flex size-10 items-center justify-center rounded-full bg-muted text-foreground">
411
+ <svg
412
+ xmlns="http://www.w3.org/2000/svg"
413
+ width="20"
414
+ height="20"
415
+ viewBox="0 0 24 24"
416
+ fill="none"
417
+ stroke="currentColor"
418
+ strokeWidth="2"
419
+ strokeLinecap="round"
420
+ strokeLinejoin="round"
421
+ aria-hidden
422
+ >
423
+ <rect
424
+ width="20"
425
+ height="16"
426
+ x="2"
427
+ y="4"
428
+ rx="2"
429
+ />
430
+ <path d="m22 7-8.97 5.7a1.94 1.94 0 0 1-2.06 0L2 7" />
431
+ </svg>
432
+ </div>
433
+ <div className="space-y-1">
434
+ <p className="text-sm font-medium text-foreground">{t('loginPage.magicLinkSentTitle')}</p>
435
+ <p className="text-sm text-muted-foreground">
436
+ {t('loginPage.magicLinkSentDescription')}{' '}
437
+ <span className="break-all font-medium text-foreground">{magicLinkSentTo}</span>
438
+ </p>
439
+ </div>
440
+ <Button
441
+ type="button"
442
+ variant="ghost"
443
+ size="sm"
444
+ disabled={magicLinkCooldown > 0}
445
+ onClick={() => setMagicLinkSentTo(null)}
446
+ >
447
+ {magicLinkCooldown > 0
448
+ ? t('loginPage.magicLinkChangeEmailIn', { seconds: magicLinkCooldown })
449
+ : t('loginPage.magicLinkChangeEmail')}
450
+ </Button>
451
+ </div>
452
+ ) : (
453
+ <form
454
+ className="space-y-2"
455
+ onSubmit={(event) => void handleMagicLinkLogin(event)}
456
+ >
457
+ <input
458
+ id="magic-link-email"
459
+ type="email"
460
+ value={magicLinkEmail}
461
+ onChange={(event) => setMagicLinkEmail(event.target.value)}
462
+ placeholder={t('loginPage.emailPlaceholder')}
463
+ autoComplete="email"
464
+ required
465
+ className="h-10 w-full rounded-md border border-input bg-background px-3 text-sm text-foreground outline-none ring-offset-background focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2"
466
+ />
467
+ <Button
468
+ type="submit"
469
+ variant="secondary"
470
+ className="w-full"
471
+ disabled={isActionPending || magicLinkCooldown > 0}
472
+ >
473
+ {magicLinkLoading ? t('loginPage.sendingMagicLink') : t('loginPage.sendMagicLink')}
474
+ </Button>
475
+ {magicLinkError && <p className="text-sm text-destructive">{magicLinkError}</p>}
476
+ </form>
477
+ );
478
+
420
479
  const panelUrl = useMemo(
421
480
  () => validateLoginPanelUrl(config.backend?.login?.panelUrl, config),
422
481
  [config],
@@ -584,35 +643,7 @@ export const LoginView = () => {
584
643
  <p className="text-xs font-medium uppercase tracking-wide text-muted-foreground">
585
644
  {t('loginPage.lastUsed')}
586
645
  </p>
587
- <form
588
- className="space-y-2"
589
- onSubmit={(event) => void handleMagicLinkLogin(event)}
590
- >
591
- <input
592
- id="magic-link-email"
593
- type="email"
594
- value={magicLinkEmail}
595
- onChange={(event) => setMagicLinkEmail(event.target.value)}
596
- placeholder={t('loginPage.emailPlaceholder')}
597
- autoComplete="email"
598
- required
599
- className="h-10 w-full rounded-md border border-input bg-background px-3 text-sm text-foreground outline-none ring-offset-background focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2"
600
- />
601
- <Button
602
- type="submit"
603
- variant="secondary"
604
- className="w-full"
605
- disabled={isActionPending}
606
- >
607
- {magicLinkLoading
608
- ? t('loginPage.sendingMagicLink')
609
- : t('loginPage.sendMagicLink')}
610
- </Button>
611
- {magicLinkMessage && (
612
- <p className="text-sm text-muted-foreground">{magicLinkMessage}</p>
613
- )}
614
- {magicLinkError && <p className="text-sm text-destructive">{magicLinkError}</p>}
615
- </form>
646
+ {magicLinkContent}
616
647
  </section>
617
648
  )}
618
649
 
@@ -681,7 +712,8 @@ export const LoginView = () => {
681
712
  : 'grid-rows-[1fr] opacity-100',
682
713
  )}
683
714
  >
684
- <div className="min-h-0 overflow-hidden">
715
+ {/* Inset matches focus ring + offset (4px) so overflow-hidden does not clip it. */}
716
+ <div className="-m-1 min-h-0 overflow-hidden p-1">
685
717
  <div
686
718
  className={cn(
687
719
  'space-y-4 transition-transform duration-500 ease-out',
@@ -690,26 +722,7 @@ export const LoginView = () => {
690
722
  : 'translate-y-0',
691
723
  )}
692
724
  >
693
- {featuredMethod === 'oauth' &&
694
- (otherOAuthProviders.length > 0 || supportsMagicLink || supportsWeb3) && (
695
- <div className="relative py-1">
696
- <div className="border-t border-border" />
697
- <span className="absolute left-1/2 top-1/2 -translate-x-1/2 -translate-y-1/2 bg-background px-2 text-xs text-muted-foreground">
698
- {t('loginPage.or')}
699
- </span>
700
- </div>
701
- )}
702
-
703
- {featuredMethod === 'magic_link' && (supportsOAuth || supportsWeb3) && (
704
- <div className="relative py-1">
705
- <div className="border-t border-border" />
706
- <span className="absolute left-1/2 top-1/2 -translate-x-1/2 -translate-y-1/2 bg-background px-2 text-xs text-muted-foreground">
707
- {t('loginPage.or')}
708
- </span>
709
- </div>
710
- )}
711
-
712
- {featuredMethod === 'web3' && (supportsOAuth || supportsMagicLink) && (
725
+ {hasAlternativeMethods && (
713
726
  <div className="relative py-1">
714
727
  <div className="border-t border-border" />
715
728
  <span className="absolute left-1/2 top-1/2 -translate-x-1/2 -translate-y-1/2 bg-background px-2 text-xs text-muted-foreground">
@@ -718,7 +731,7 @@ export const LoginView = () => {
718
731
  </div>
719
732
  )}
720
733
 
721
- {supportsWeb3 && featuredMethod !== 'web3' && (
734
+ {showWeb3Section && (
722
735
  <section className="space-y-2">
723
736
  <p className="text-xs font-medium uppercase tracking-wide text-muted-foreground">
724
737
  {t('loginPage.walletLogin')}
@@ -750,7 +763,7 @@ export const LoginView = () => {
750
763
  </section>
751
764
  )}
752
765
 
753
- {supportsOAuth && otherOAuthProviders.length > 0 && (
766
+ {showOAuthSection && (
754
767
  <section className="space-y-2">
755
768
  <p className="text-xs font-medium uppercase tracking-wide text-muted-foreground">
756
769
  {featuredMethod === 'oauth'
@@ -793,53 +806,21 @@ export const LoginView = () => {
793
806
  </section>
794
807
  )}
795
808
 
796
- {(supportsOAuth || supportsWeb3) &&
797
- supportsMagicLink &&
798
- featuredMethod !== 'magic_link' && (
799
- <div className="relative py-1">
800
- <div className="border-t border-border" />
801
- <span className="absolute left-1/2 top-1/2 -translate-x-1/2 -translate-y-1/2 bg-background px-2 text-xs text-muted-foreground">
802
- {t('loginPage.or')}
803
- </span>
804
- </div>
805
- )}
809
+ {showMagicLinkDivider && (
810
+ <div className="relative py-1">
811
+ <div className="border-t border-border" />
812
+ <span className="absolute left-1/2 top-1/2 -translate-x-1/2 -translate-y-1/2 bg-background px-2 text-xs text-muted-foreground">
813
+ {t('loginPage.or')}
814
+ </span>
815
+ </div>
816
+ )}
806
817
 
807
- {supportsMagicLink && featuredMethod !== 'magic_link' && (
818
+ {showMagicLinkSection && (
808
819
  <section className="space-y-2">
809
820
  <p className="text-xs font-medium uppercase tracking-wide text-muted-foreground">
810
821
  {t('loginPage.emailMagicLink')}
811
822
  </p>
812
- <form
813
- className="space-y-2"
814
- onSubmit={(event) => void handleMagicLinkLogin(event)}
815
- >
816
- <input
817
- id="magic-link-email"
818
- type="email"
819
- value={magicLinkEmail}
820
- onChange={(event) => setMagicLinkEmail(event.target.value)}
821
- placeholder={t('loginPage.emailPlaceholder')}
822
- autoComplete="email"
823
- required
824
- className="h-10 w-full rounded-md border border-input bg-background px-3 text-sm text-foreground outline-none ring-offset-background focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2"
825
- />
826
- <Button
827
- type="submit"
828
- variant="secondary"
829
- className="w-full"
830
- disabled={isActionPending}
831
- >
832
- {magicLinkLoading
833
- ? t('loginPage.sendingMagicLink')
834
- : t('loginPage.sendMagicLink')}
835
- </Button>
836
- {magicLinkMessage && (
837
- <p className="text-sm text-muted-foreground">{magicLinkMessage}</p>
838
- )}
839
- {magicLinkError && (
840
- <p className="text-sm text-destructive">{magicLinkError}</p>
841
- )}
842
- </form>
823
+ {magicLinkContent}
843
824
  </section>
844
825
  )}
845
826
  </div>
@@ -0,0 +1,21 @@
1
+ import { useTranslation } from 'react-i18next';
2
+
3
+ /** Full-area spinner shown while the first session restore resolves (e.g. after a reload). */
4
+ export const SessionLoadingView = () => {
5
+ const { t } = useTranslation('common');
6
+
7
+ return (
8
+ <div
9
+ role="status"
10
+ aria-live="polite"
11
+ data-shellui-session-loading=""
12
+ className="flex h-full w-full flex-col items-center justify-center gap-3 p-6"
13
+ >
14
+ <div
15
+ className="size-6 shrink-0 animate-spin rounded-full border-2 border-muted-foreground/25 border-t-muted-foreground"
16
+ aria-hidden
17
+ />
18
+ <p className="text-sm text-muted-foreground">{t('sessionLoading')}</p>
19
+ </div>
20
+ );
21
+ };
@@ -13,6 +13,10 @@ export interface AuthContextValue {
13
13
  session: AuthSession | null;
14
14
  user: AuthUser | null;
15
15
  isAuthenticated: boolean;
16
+ /**
17
+ * True while the first session restore is in flight (e.g. refresh-token exchange after a page
18
+ * reload). Background token refreshes never set it, so UI can show loading placeholders safely.
19
+ */
16
20
  isLoading: boolean;
17
21
  error: string | null;
18
22
  errorCode: string | null;
@@ -35,6 +39,14 @@ export interface AuthContextValue {
35
39
  syncUserPreferences: (preferences: UserPreferences) => Promise<void>;
36
40
  loadUserPreferences: () => Promise<UserPreferences | null>;
37
41
  logout: () => Promise<void>;
42
+ /** Whether the configured auth backend supports self-service account deletion. */
43
+ supportsAccountDeletion: boolean;
44
+ /** Delete the signed-in account for the current company, then sign out. */
45
+ deleteAccount: () => Promise<void>;
46
+ /** Whether the configured auth backend supports editing the display name. */
47
+ supportsProfileUpdate: boolean;
48
+ /** Update the signed-in user's display name and the local session. */
49
+ updateProfile: (profile: { name: string }) => Promise<{ name: string }>;
38
50
  }
39
51
 
40
52
  export const AuthContext = createContext<AuthContextValue | null>(null);
@@ -0,0 +1,76 @@
1
+ import { postShellMessage, shellui, type ShellUIMessage } from '@shellui/sdk';
2
+
3
+ type ShellUIMessageType = ShellUIMessage['type'];
4
+
5
+ export type DeleteAccountResultStatus = 'deleted' | 'cancelled' | 'error';
6
+
7
+ export type UpdateProfileResult =
8
+ | { status: 'saved'; name: string }
9
+ | { status: 'error'; error?: string };
10
+
11
+ /** The delete confirmation dialog stays open until the user answers, so only give up after a long wait. */
12
+ const DELETE_RESULT_TIMEOUT_MS = 10 * 60_000;
13
+ const UPDATE_PROFILE_TIMEOUT_MS = 30_000;
14
+
15
+ const createRequestId = (): string =>
16
+ typeof crypto !== 'undefined' && typeof crypto.randomUUID === 'function'
17
+ ? crypto.randomUUID()
18
+ : `${Date.now().toString(36)}-${Math.random().toString(36).slice(2)}`;
19
+
20
+ /**
21
+ * Post an account request to the top-level shell (which owns the session) and resolve with
22
+ * the payload of the matching result message, or `null` on timeout.
23
+ */
24
+ function requestFromShell(
25
+ requestType: ShellUIMessageType,
26
+ resultType: ShellUIMessageType,
27
+ payload: Record<string, unknown>,
28
+ timeoutMs: number,
29
+ ): Promise<Record<string, unknown> | null> {
30
+ const id = createRequestId();
31
+ return new Promise((resolve) => {
32
+ let settled = false;
33
+ const finish = (result: Record<string, unknown> | null) => {
34
+ if (settled) return;
35
+ settled = true;
36
+ clearTimeout(timer);
37
+ cleanup();
38
+ resolve(result);
39
+ };
40
+ const cleanup = shellui.addMessageListener(resultType, (message: ShellUIMessage) => {
41
+ const result = message.payload as Record<string, unknown> | undefined;
42
+ if (result?.id === id) finish(result);
43
+ });
44
+ const timer = setTimeout(() => finish(null), timeoutMs);
45
+ postShellMessage({ type: requestType, payload: { ...payload, id } });
46
+ });
47
+ }
48
+
49
+ /** Ask the shell to confirm and delete the signed-in account for the current company. */
50
+ export async function requestAccountDeletion(): Promise<DeleteAccountResultStatus> {
51
+ const result = await requestFromShell(
52
+ 'SHELLUI_DELETE_ACCOUNT_REQUEST',
53
+ 'SHELLUI_DELETE_ACCOUNT_RESULT',
54
+ {},
55
+ DELETE_RESULT_TIMEOUT_MS,
56
+ );
57
+ const status = result?.status;
58
+ return status === 'deleted' || status === 'cancelled' ? status : 'error';
59
+ }
60
+
61
+ /** Ask the shell to update the signed-in user's display name. */
62
+ export async function requestProfileUpdate(name: string): Promise<UpdateProfileResult> {
63
+ const result = await requestFromShell(
64
+ 'SHELLUI_UPDATE_PROFILE_REQUEST',
65
+ 'SHELLUI_UPDATE_PROFILE_RESULT',
66
+ { name },
67
+ UPDATE_PROFILE_TIMEOUT_MS,
68
+ );
69
+ if (result?.status === 'saved' && typeof result.name === 'string') {
70
+ return { status: 'saved', name: result.name };
71
+ }
72
+ return {
73
+ status: 'error',
74
+ error: typeof result?.error === 'string' ? result.error : undefined,
75
+ };
76
+ }
@@ -1,10 +1,13 @@
1
1
  export class AuthRequestError extends Error {
2
2
  readonly code: string | null;
3
+ /** Extra fields from the error response body (e.g. `companies` for `last_company_owner`). */
4
+ readonly details: Record<string, unknown>;
3
5
 
4
- constructor(message: string, code?: string | null) {
6
+ constructor(message: string, code?: string | null, details?: Record<string, unknown>) {
5
7
  super(message);
6
8
  this.name = 'AuthRequestError';
7
9
  this.code = typeof code === 'string' && code.trim() ? code.trim() : null;
10
+ this.details = details ?? {};
8
11
  }
9
12
  }
10
13
 
@@ -7,6 +7,7 @@ import {
7
7
  } from './authStorageKeys';
8
8
  import {
9
9
  clearStoredAuthSession,
10
+ hasStoredAuthSession,
10
11
  persistAuthSession,
11
12
  readStoredAuthSession,
12
13
  } from './authSessionPersistence';
@@ -84,6 +85,16 @@ describe('authSessionPersistence', () => {
84
85
  expect(localStorage.setItem).toHaveBeenCalledWith(AUTH_PROFILE_STORAGE_KEY, expect.any(String));
85
86
  });
86
87
 
88
+ it('reports a stored session only when a profile or legacy snapshot exists', () => {
89
+ expect(hasStoredAuthSession()).toBe(false);
90
+ persistAuthSession(sampleSession());
91
+ expect(hasStoredAuthSession()).toBe(true);
92
+ clearStoredAuthSession();
93
+ expect(hasStoredAuthSession()).toBe(false);
94
+ localStorage.setItem(LEGACY_AUTH_SESSION_STORAGE_KEY, JSON.stringify(sampleSession()));
95
+ expect(hasStoredAuthSession()).toBe(true);
96
+ });
97
+
87
98
  it('clears profile, refresh, and legacy keys', () => {
88
99
  clearStoredAuthSession();
89
100
  expect(localStorage.removeItem).toHaveBeenCalledWith(AUTH_PROFILE_STORAGE_KEY);
@@ -124,6 +124,18 @@ export const readStoredAuthSession = (): AuthSession | null => {
124
124
  return mergeProfileAndTokens(profile, '', refreshToken);
125
125
  };
126
126
 
127
+ /** Whether a session snapshot exists to restore, without migrating or mutating storage. */
128
+ export const hasStoredAuthSession = (): boolean => {
129
+ try {
130
+ return (
131
+ localStorage.getItem(AUTH_PROFILE_STORAGE_KEY) !== null ||
132
+ localStorage.getItem(LEGACY_AUTH_SESSION_STORAGE_KEY) !== null
133
+ );
134
+ } catch {
135
+ return false;
136
+ }
137
+ };
138
+
127
139
  /** Remove all persisted auth keys (profile, refresh, legacy). */
128
140
  export const clearStoredAuthSession = () => {
129
141
  writeProfile(null);
@@ -26,6 +26,7 @@ export {
26
26
  } from './cliCallback';
27
27
  export {
28
28
  clearStoredAuthSession,
29
+ hasStoredAuthSession,
29
30
  persistAuthProfile,
30
31
  persistAuthSession,
31
32
  readStoredAuthSession,
@@ -44,9 +45,12 @@ export { getOAuthProviderCandidates } from './getOAuthProviderCandidates';
44
45
  export { getPreferredBackendProvider } from './getPreferredBackendProvider';
45
46
  export { getProviderVisual } from './getProviderVisual';
46
47
  export { isLoginMethod } from './isLoginMethod';
48
+ export { resolveLoginSettings } from './resolveLoginSettings';
47
49
  export { isSessionExpired } from './isSessionExpired';
48
50
  export { isTokenAutoRefreshDisabled } from './isTokenAutoRefreshDisabled';
49
51
  export { normalizeAuthSettings } from './normalizeAuthSettings';
50
52
  export { normalizeNextPath } from './normalizeNextPath';
51
53
  export { normalizeRedirectPath } from './normalizeRedirectPath';
54
+ export { shareInFlight } from './shareInFlight';
55
+ export type { InFlightSlot } from './shareInFlight';
52
56
  export { toAuthSessionFromSettingsUser } from './toAuthSessionFromSettingsUser';
@@ -0,0 +1,33 @@
1
+ import { describe, expect, it } from 'vitest';
2
+ import { resolveLoginSettings } from './resolveLoginSettings';
3
+
4
+ const url = 'https://auth.example.com';
5
+
6
+ describe('resolveLoginSettings', () => {
7
+ it('keeps configured methods and normalizes providers', () => {
8
+ expect(
9
+ resolveLoginSettings({
10
+ type: 'shellui',
11
+ url,
12
+ login: { methods: ['oauth'], oauthProviders: ['GitHub', 'github', ' '] },
13
+ }),
14
+ ).toEqual({ methods: ['oauth'], oauthProviders: ['github'], oauthClients: [] });
15
+ });
16
+
17
+ it('falls back to magic link when no method is configured', () => {
18
+ expect(resolveLoginSettings({ type: 'shellui', url }).methods).toEqual(['magic_link']);
19
+ expect(resolveLoginSettings({ type: 'supabase', url, login: { methods: [] } }).methods).toEqual(
20
+ ['magic_link'],
21
+ );
22
+ });
23
+
24
+ it('adds oauth to the fallback when providers are listed', () => {
25
+ expect(
26
+ resolveLoginSettings({ type: 'shellui', url, login: { oauthProviders: ['github'] } }),
27
+ ).toEqual({ methods: ['oauth', 'magic_link'], oauthProviders: ['github'], oauthClients: [] });
28
+ });
29
+
30
+ it('shows nothing without a backend', () => {
31
+ expect(resolveLoginSettings(undefined).methods).toEqual([]);
32
+ });
33
+ });
@@ -0,0 +1,33 @@
1
+ import type { BackendConfig } from '../../config/types';
2
+ import type { AuthSettings, LoginMethod } from '../types';
3
+ import { isLoginMethod } from './isLoginMethod';
4
+
5
+ const BACKENDS_WITH_MAGIC_LINK = new Set(['shellui', 'supabase']);
6
+
7
+ /**
8
+ * Login methods and OAuth providers to show, from `backend.login` in the shell config.
9
+ * When no method is listed, falls back to magic link (plus OAuth if providers are listed)
10
+ * so a configured backend never shows an empty login page.
11
+ */
12
+ export function resolveLoginSettings(backend: BackendConfig | undefined): AuthSettings {
13
+ const login = backend?.login;
14
+ const methods = Array.isArray(login?.methods) ? login.methods.filter(isLoginMethod) : [];
15
+ const providers = Array.isArray(login?.oauthProviders)
16
+ ? Array.from(
17
+ new Set(
18
+ login.oauthProviders
19
+ .filter(
20
+ (provider): provider is string =>
21
+ typeof provider === 'string' && provider.trim() !== '',
22
+ )
23
+ .map((provider) => provider.toLowerCase()),
24
+ ),
25
+ )
26
+ : [];
27
+
28
+ if (methods.length > 0 || !backend?.type || !BACKENDS_WITH_MAGIC_LINK.has(backend.type)) {
29
+ return { methods, oauthProviders: providers, oauthClients: [] };
30
+ }
31
+ const fallback: LoginMethod[] = providers.length > 0 ? ['oauth', 'magic_link'] : ['magic_link'];
32
+ return { methods: fallback, oauthProviders: providers, oauthClients: [] };
33
+ }