@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.
- package/README.md +2 -0
- package/package.json +6 -4
- package/schemas/shellui.config.schema.json +104 -64
- package/src/app.tsx +5 -3
- package/src/components/ContentView.tsx +14 -23
- package/src/components/LoadingOverlay.tsx +1 -1
- package/src/components/ui/sonner.spec.tsx +138 -0
- package/src/components/ui/sonner.tsx +5 -5
- package/src/components/ui/switch.tsx +1 -1
- package/src/features/admin/AdminView.tsx +14 -3
- package/src/features/ai/AiBridge.tsx +106 -0
- package/src/features/ai/AiUnavailableResponder.tsx +39 -0
- package/src/features/ai/README.md +52 -0
- package/src/features/ai/ShellAiHost.tsx +24 -0
- package/src/features/ai/adapters/ollama.ts +170 -0
- package/src/features/ai/adapters/promptApi.spec.ts +135 -0
- package/src/features/ai/adapters/promptApi.ts +222 -0
- package/src/features/ai/adapters/webllm.experimental.spec.ts +69 -0
- package/src/features/ai/adapters/webllm.spec.ts +527 -0
- package/src/features/ai/adapters/webllm.ts +142 -0
- package/src/features/ai/aiDisabledResponses.spec.ts +29 -0
- package/src/features/ai/aiDisabledResponses.ts +32 -0
- package/src/features/ai/browserInstallStore.spec.ts +58 -0
- package/src/features/ai/browserInstallStore.ts +76 -0
- package/src/features/ai/catalog.ts +31 -0
- package/src/features/ai/createRegistry.ts +83 -0
- package/src/features/ai/developHarness.spec.ts +108 -0
- package/src/features/ai/developHarness.ts +161 -0
- package/src/features/ai/engine/formatAiError.spec.ts +85 -0
- package/src/features/ai/engine/formatAiError.ts +132 -0
- package/src/features/ai/engine/mapInitProgress.ts +9 -0
- package/src/features/ai/engine/normalizeWebLlmModule.spec.ts +47 -0
- package/src/features/ai/engine/vite-worker.d.ts +6 -0
- package/src/features/ai/engine/webllm.worker.ts +51 -0
- package/src/features/ai/engine/webllmEngine.ts +1011 -0
- package/src/features/ai/handleRequest.spec.ts +288 -0
- package/src/features/ai/handleRequest.ts +325 -0
- package/src/features/ai/isAiFeatureEnabled.spec.ts +15 -0
- package/src/features/ai/isAiFeatureEnabled.ts +9 -0
- package/src/features/ai/promptApiSupport.spec.ts +64 -0
- package/src/features/ai/promptApiSupport.ts +117 -0
- package/src/features/ai/registry.spec.ts +100 -0
- package/src/features/ai/registry.ts +131 -0
- package/src/features/ai/status.spec.ts +92 -0
- package/src/features/ai/status.ts +85 -0
- package/src/features/ai/types.ts +100 -0
- package/src/features/ai/webLlmBrowserSupport.spec.ts +86 -0
- package/src/features/ai/webLlmBrowserSupport.ts +92 -0
- package/src/features/alertDialog/DialogContext.tsx +3 -1
- package/src/features/auth/AuthProvider.tsx +254 -39
- package/src/features/auth/backends/index.ts +8 -0
- package/src/features/auth/backends/shellui.spec.ts +201 -0
- package/src/features/auth/backends/shellui.ts +93 -16
- package/src/features/auth/backends/supabase.ts +8 -0
- package/src/features/auth/backends/types.ts +16 -1
- package/src/features/auth/components/LoginButton.tsx +26 -2
- package/src/features/auth/components/LoginView.tsx +114 -133
- package/src/features/auth/components/SessionLoadingView.tsx +21 -0
- package/src/features/auth/hooks/useAuth.tsx +12 -0
- package/src/features/auth/shellAccountRequests.ts +76 -0
- package/src/features/auth/utils/authRequestError.ts +4 -1
- package/src/features/auth/utils/authSessionPersistence.spec.ts +11 -0
- package/src/features/auth/utils/authSessionPersistence.ts +12 -0
- package/src/features/auth/utils/index.ts +4 -0
- package/src/features/auth/utils/resolveLoginSettings.spec.ts +33 -0
- package/src/features/auth/utils/resolveLoginSettings.ts +33 -0
- package/src/features/auth/utils/shareInFlight.spec.ts +41 -0
- package/src/features/auth/utils/shareInFlight.ts +14 -0
- package/src/features/config/ConfigProvider.ts +9 -1
- package/src/features/config/types.ts +43 -0
- package/src/features/layouts/appbar/AppBarLayout.tsx +8 -3
- package/src/features/layouts/filterNavigationForAuthState.spec.ts +41 -0
- package/src/features/layouts/floating/FloatingLayout.tsx +9 -4
- package/src/features/layouts/floating/layoutChromeStore.ts +3 -1
- package/src/features/layouts/sidebar/SidebarLayout.tsx +9 -4
- package/src/features/layouts/utils.ts +6 -2
- package/src/features/layouts/windows/WindowsLayout.tsx +8 -3
- package/src/features/messaging/MessagingSecurityBootstrap.tsx +6 -6
- package/src/features/security/trustedFrames.spec.ts +65 -0
- package/src/features/security/trustedFrames.ts +52 -0
- package/src/features/settings/SettingsIcons.tsx +17 -0
- package/src/features/settings/SettingsProvider.tsx +29 -4
- package/src/features/settings/SettingsRoutes.tsx +8 -0
- package/src/features/settings/SettingsView.tsx +21 -4
- package/src/features/settings/components/Ai.tsx +830 -0
- package/src/features/settings/components/Develop.tsx +4 -0
- package/src/features/settings/components/Storage.tsx +197 -32
- package/src/features/settings/components/UserSettingsPanel.tsx +160 -12
- package/src/features/settings/components/createUserSettingsRoute.tsx +4 -0
- package/src/features/settings/components/develop/AiTestTools.tsx +231 -0
- package/src/features/settings/utils/buildSettingsForPropagation.spec.ts +54 -1
- package/src/features/settings/utils/buildSettingsForPropagation.ts +15 -1
- package/src/features/settings/utils/mergePreferencesIntoSettings.spec.ts +6 -0
- package/src/features/settings/utils/shouldShowStorageSettings.spec.ts +49 -0
- package/src/features/settings/utils/shouldShowStorageSettings.ts +19 -0
- package/src/features/storage/uploads/UploadToastCard.tsx +2 -442
- package/src/features/storage/uploads/UploadToaster.tsx +2 -44
- package/src/features/storage/uploads/uploadQueue.ts +128 -308
- package/src/features/storage/uploads/useUploadQueue.ts +7 -3
- package/src/features/transfers/TransferToastCard.tsx +467 -0
- package/src/features/transfers/TransferToaster.tsx +50 -0
- package/src/features/transfers/index.ts +33 -0
- package/src/features/transfers/transferQueue.spec.ts +97 -0
- package/src/features/transfers/transferQueue.ts +442 -0
- package/src/features/transfers/types.ts +38 -0
- package/src/features/transfers/useTransferQueue.ts +30 -0
- package/src/i18n/translations/en/common.json +46 -2
- package/src/i18n/translations/en/settings.json +151 -2
- package/src/i18n/translations/fr/common.json +46 -2
- package/src/i18n/translations/fr/settings.json +151 -2
- package/src/index.css +57 -4
- package/src/index.ts +1 -0
- package/src/routes/components/NavigationItemRoute.tsx +2 -1
|
@@ -0,0 +1,86 @@
|
|
|
1
|
+
import { describe, expect, it } from 'vitest';
|
|
2
|
+
import {
|
|
3
|
+
mapWebLlmRuntimeError,
|
|
4
|
+
probeWebLlmBrowserSupport,
|
|
5
|
+
WEBLLM_EXPERIMENTAL_BROWSER_MESSAGE,
|
|
6
|
+
WEBLLM_WEBGPU_WORKER_FAILED_MESSAGE,
|
|
7
|
+
} from './webLlmBrowserSupport.js';
|
|
8
|
+
|
|
9
|
+
describe('probeWebLlmBrowserSupport', () => {
|
|
10
|
+
it('recommends Chromium / Edge user agents (Install allowed)', () => {
|
|
11
|
+
const chrome = probeWebLlmBrowserSupport(
|
|
12
|
+
'Mozilla/5.0 (Macintosh; Intel Mac OS X) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36',
|
|
13
|
+
);
|
|
14
|
+
expect(chrome.recommended).toBe(true);
|
|
15
|
+
expect(chrome.canInstall).toBe(true);
|
|
16
|
+
const edge = probeWebLlmBrowserSupport(
|
|
17
|
+
'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36 Edg/131.0.0.0',
|
|
18
|
+
);
|
|
19
|
+
expect(edge.recommended).toBe(true);
|
|
20
|
+
expect(edge.canInstall).toBe(true);
|
|
21
|
+
});
|
|
22
|
+
|
|
23
|
+
it('marks Firefox experimental but still installable', () => {
|
|
24
|
+
const result = probeWebLlmBrowserSupport(
|
|
25
|
+
'Mozilla/5.0 (Macintosh; Intel Mac OS X 10.15; rv:133.0) Gecko/20100101 Firefox/133.0',
|
|
26
|
+
);
|
|
27
|
+
expect(result.recommended).toBe(false);
|
|
28
|
+
expect(result.canInstall).toBe(true);
|
|
29
|
+
expect(result.reason).toBe('firefox');
|
|
30
|
+
expect(result.detail).toBe(WEBLLM_EXPERIMENTAL_BROWSER_MESSAGE);
|
|
31
|
+
});
|
|
32
|
+
|
|
33
|
+
it('recommends Safari like Chromium (Install allowed, no experimental warning)', () => {
|
|
34
|
+
const result = probeWebLlmBrowserSupport(
|
|
35
|
+
'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/18.0 Safari/605.1.15',
|
|
36
|
+
);
|
|
37
|
+
expect(result.recommended).toBe(true);
|
|
38
|
+
expect(result.canInstall).toBe(true);
|
|
39
|
+
expect(result.reason).toBeUndefined();
|
|
40
|
+
expect(result.detail).toBe('');
|
|
41
|
+
});
|
|
42
|
+
});
|
|
43
|
+
|
|
44
|
+
describe('mapWebLlmRuntimeError', () => {
|
|
45
|
+
it('maps WebGPU-ish errors on Firefox to the experimental-browser guidance', () => {
|
|
46
|
+
expect(
|
|
47
|
+
mapWebLlmRuntimeError(
|
|
48
|
+
new Error('Failed to get GPU adapter'),
|
|
49
|
+
'Mozilla/5.0 (Macintosh; Intel Mac OS X 10.15; rv:133.0) Gecko/20100101 Firefox/133.0',
|
|
50
|
+
),
|
|
51
|
+
).toBe(WEBLLM_EXPERIMENTAL_BROWSER_MESSAGE);
|
|
52
|
+
});
|
|
53
|
+
|
|
54
|
+
it('maps WebGPU-ish errors on Chromium to the worker WebGPU message', () => {
|
|
55
|
+
expect(
|
|
56
|
+
mapWebLlmRuntimeError(
|
|
57
|
+
new Error('Unable to find a compatible GPU'),
|
|
58
|
+
'Mozilla/5.0 Chrome/131.0.0.0 Safari/537.36',
|
|
59
|
+
),
|
|
60
|
+
).toBe(WEBLLM_WEBGPU_WORKER_FAILED_MESSAGE);
|
|
61
|
+
});
|
|
62
|
+
|
|
63
|
+
it('maps WebGPU-ish errors on Safari to the worker WebGPU message (not experimental)', () => {
|
|
64
|
+
expect(
|
|
65
|
+
mapWebLlmRuntimeError(
|
|
66
|
+
new Error('Failed to get GPU adapter'),
|
|
67
|
+
'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/18.0 Safari/605.1.15',
|
|
68
|
+
),
|
|
69
|
+
).toBe(WEBLLM_WEBGPU_WORKER_FAILED_MESSAGE);
|
|
70
|
+
});
|
|
71
|
+
|
|
72
|
+
it('maps WebLLM string rejections (worker err.toString())', () => {
|
|
73
|
+
expect(
|
|
74
|
+
mapWebLlmRuntimeError(
|
|
75
|
+
'WebGPUNotAvailableError: WebGPU is not supported in your current environment',
|
|
76
|
+
'Mozilla/5.0 Chrome/131.0.0.0 Safari/537.36',
|
|
77
|
+
),
|
|
78
|
+
).toBe(WEBLLM_WEBGPU_WORKER_FAILED_MESSAGE);
|
|
79
|
+
});
|
|
80
|
+
|
|
81
|
+
it('returns null for non-WebGPU errors', () => {
|
|
82
|
+
expect(
|
|
83
|
+
mapWebLlmRuntimeError(new Error('some unrelated failure'), 'Mozilla/5.0 Chrome/131'),
|
|
84
|
+
).toBeNull();
|
|
85
|
+
});
|
|
86
|
+
});
|
|
@@ -0,0 +1,92 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* WebLLM / MLC in-browser runtime support for Shellui.
|
|
3
|
+
*
|
|
4
|
+
* Chrome, Edge, and Safari (mature WebGPU) are the **recommended** runtimes.
|
|
5
|
+
* Firefox also ships WebGPU, but its implementation is less mature for
|
|
6
|
+
* `@mlc-ai/web-llm` — Install may fail. We no longer hard-block it: Install is
|
|
7
|
+
* allowed everywhere (experimental on Firefox) and real failures surface via
|
|
8
|
+
* the clear `[shellui.ai]` error mapping.
|
|
9
|
+
*/
|
|
10
|
+
|
|
11
|
+
/** Shown as a non-blocking warning on Firefox (Install still allowed). */
|
|
12
|
+
export const WEBLLM_EXPERIMENTAL_BROWSER_MESSAGE =
|
|
13
|
+
'Browser models work best in Chrome, Edge, or Safari (WebGPU). Support in this browser is experimental — if Install fails, use Ollama.';
|
|
14
|
+
|
|
15
|
+
/** Any browser when WebGPU fails inside the WebLLM worker. */
|
|
16
|
+
export const WEBLLM_WEBGPU_WORKER_FAILED_MESSAGE =
|
|
17
|
+
'WebGPU failed in the WebLLM worker. Check chrome://gpu (or about:support), try Chrome/Edge/Safari, or use Ollama.';
|
|
18
|
+
|
|
19
|
+
export type WebLlmBrowserSupport = {
|
|
20
|
+
/** Chrome / Edge / Safari — the recommended runtime. */
|
|
21
|
+
recommended: boolean;
|
|
22
|
+
/** Install is always allowed now; Firefox is experimental. */
|
|
23
|
+
canInstall: true;
|
|
24
|
+
/** Why the browser is not recommended (when `recommended` is false). */
|
|
25
|
+
reason?: 'firefox' | 'other';
|
|
26
|
+
/** Warning text when `recommended` is false (empty string when recommended). */
|
|
27
|
+
detail: string;
|
|
28
|
+
};
|
|
29
|
+
|
|
30
|
+
const WEBGPU_ERROR_RE =
|
|
31
|
+
/webgpu|gpuadapter|gpudevice|device lost|adapter|wgpu|vulkan|metal|dawn|compatible gpu|gpu vendor/i;
|
|
32
|
+
|
|
33
|
+
/**
|
|
34
|
+
* Cheap UA check for whether WebLLM Install is *recommended* (distinct from the
|
|
35
|
+
* soft WebGPU probe). Install is allowed regardless; this only drives warnings.
|
|
36
|
+
* Injectable `userAgent` for tests.
|
|
37
|
+
*/
|
|
38
|
+
export function probeWebLlmBrowserSupport(
|
|
39
|
+
userAgent: string = typeof navigator !== 'undefined' ? navigator.userAgent : '',
|
|
40
|
+
): WebLlmBrowserSupport {
|
|
41
|
+
const ua = userAgent || '';
|
|
42
|
+
|
|
43
|
+
// Firefox desktop + Firefox on iOS (FxiOS).
|
|
44
|
+
if (/firefox\//i.test(ua) || /fxios\//i.test(ua)) {
|
|
45
|
+
return {
|
|
46
|
+
recommended: false,
|
|
47
|
+
canInstall: true,
|
|
48
|
+
reason: 'firefox',
|
|
49
|
+
detail: WEBLLM_EXPERIMENTAL_BROWSER_MESSAGE,
|
|
50
|
+
};
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
// Chrome, Edge, Safari, and other UAs: recommended (no amber warning).
|
|
54
|
+
return { recommended: true, canInstall: true, detail: '' };
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
/**
|
|
58
|
+
* Map engine / worker throws to a clear user-facing message.
|
|
59
|
+
* - Firefox + WebGPU-ish → experimental-browser guidance (try Chrome/Edge/Safari or Ollama)
|
|
60
|
+
* - Recommended browser + WebGPU-ish → “WebGPU failed in the WebLLM worker”
|
|
61
|
+
* WebLLM often rejects with a **string** (`err.toString()` from the worker).
|
|
62
|
+
*/
|
|
63
|
+
export function mapWebLlmRuntimeError(error: unknown, userAgent?: string): string | null {
|
|
64
|
+
const text =
|
|
65
|
+
error instanceof Error
|
|
66
|
+
? `${error.name} ${error.message}`
|
|
67
|
+
: typeof error === 'string'
|
|
68
|
+
? error
|
|
69
|
+
: typeof ErrorEvent !== 'undefined' && error instanceof ErrorEvent
|
|
70
|
+
? error.message || formatLoose(error.error)
|
|
71
|
+
: '';
|
|
72
|
+
if (!text) return null;
|
|
73
|
+
const lower = text.toLowerCase();
|
|
74
|
+
const looksLikeWebGpu =
|
|
75
|
+
WEBGPU_ERROR_RE.test(lower) ||
|
|
76
|
+
/not support|unsupported|not implemented|not available|necessary to run the webllm/i.test(
|
|
77
|
+
lower,
|
|
78
|
+
);
|
|
79
|
+
if (!looksLikeWebGpu) return null;
|
|
80
|
+
|
|
81
|
+
const support = probeWebLlmBrowserSupport(userAgent);
|
|
82
|
+
if (!support.recommended) {
|
|
83
|
+
return support.detail;
|
|
84
|
+
}
|
|
85
|
+
return WEBLLM_WEBGPU_WORKER_FAILED_MESSAGE;
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
function formatLoose(value: unknown): string {
|
|
89
|
+
if (value instanceof Error) return value.message;
|
|
90
|
+
if (typeof value === 'string') return value;
|
|
91
|
+
return '';
|
|
92
|
+
}
|
|
@@ -460,7 +460,9 @@ export const DialogProvider = ({ children }: DialogProviderProps) => {
|
|
|
460
460
|
)}
|
|
461
461
|
<AlertDialogTitle>{dialogState.title}</AlertDialogTitle>
|
|
462
462
|
{dialogState.description && (
|
|
463
|
-
<AlertDialogDescription>
|
|
463
|
+
<AlertDialogDescription className="whitespace-pre-line">
|
|
464
|
+
{dialogState.description}
|
|
465
|
+
</AlertDialogDescription>
|
|
464
466
|
)}
|
|
465
467
|
</AlertDialogHeader>
|
|
466
468
|
<AlertDialogFooter>{renderButtons()}</AlertDialogFooter>
|
|
@@ -1,7 +1,9 @@
|
|
|
1
1
|
import { type ReactNode, useCallback, useEffect, useMemo, useRef, useState } from 'react';
|
|
2
|
+
import { useTranslation } from 'react-i18next';
|
|
2
3
|
import { getLogger, postShellMessage, shellui, type Settings } from '@shellui/sdk';
|
|
3
4
|
import urls from '../../constants/urls';
|
|
4
5
|
import { useConfig } from '../config/useConfig';
|
|
6
|
+
import { isShellSettingsFrameMessage } from '../security/trustedFrames';
|
|
5
7
|
import { createAuthBackend } from './backends';
|
|
6
8
|
import { AuthContext, type AuthContextValue, type OAuthCallbackResult } from './hooks/useAuth';
|
|
7
9
|
import type { AuthEvent, AuthSession, AuthUser, UserPreferences } from './types';
|
|
@@ -12,6 +14,8 @@ import {
|
|
|
12
14
|
getAccessTokenFromSdkSettings,
|
|
13
15
|
getAuthRequestErrorCode,
|
|
14
16
|
getUserFromSdkSettings,
|
|
17
|
+
hashHasOAuthTokens,
|
|
18
|
+
hasStoredAuthSession,
|
|
15
19
|
inferAccessPendingErrorCode,
|
|
16
20
|
isBffAuthEnabledFromConfig,
|
|
17
21
|
isSessionExpired,
|
|
@@ -20,8 +24,12 @@ import {
|
|
|
20
24
|
persistAuthSession,
|
|
21
25
|
readStoredAuthSession,
|
|
22
26
|
refreshBffAuthSession,
|
|
27
|
+
shareInFlight,
|
|
23
28
|
toAuthSessionFromSettingsUser,
|
|
29
|
+
type InFlightSlot,
|
|
24
30
|
} from './utils';
|
|
31
|
+
import { buildAuthUrlWithNext } from './utils/buildAuthUrlWithNext';
|
|
32
|
+
import type { DeleteAccountResultStatus, UpdateProfileResult } from './shellAccountRequests';
|
|
25
33
|
|
|
26
34
|
const logger = getLogger('shellcore');
|
|
27
35
|
|
|
@@ -30,6 +38,23 @@ const PROACTIVE_REFRESH_LEEWAY_SECONDS = 90;
|
|
|
30
38
|
/** Periodic check while the shell tab is open (also mitigates background-tab timer throttling). */
|
|
31
39
|
const TOKEN_REFRESH_TICK_MS = 45_000;
|
|
32
40
|
|
|
41
|
+
/**
|
|
42
|
+
* Shared across StrictMode remounts (component refs reset). Prevents two restore refreshes
|
|
43
|
+
* with the same refresh token — identity rotation revokes the family on reuse (401 → logout).
|
|
44
|
+
*/
|
|
45
|
+
const restoreRefreshSlot: InFlightSlot<AuthSession | null> = { current: null };
|
|
46
|
+
|
|
47
|
+
/**
|
|
48
|
+
* Initial `isLoading`: true only when the first mount has a session to resolve, so signed-out
|
|
49
|
+
* visitors render the login entry right away instead of a skeleton flash. Later background
|
|
50
|
+
* refreshes never touch `isLoading`.
|
|
51
|
+
*/
|
|
52
|
+
const hasInitialSessionToResolve = (): boolean => {
|
|
53
|
+
if (typeof window === 'undefined') return false;
|
|
54
|
+
if (window.parent !== window) return getUserFromSdkSettings() !== null;
|
|
55
|
+
return hashHasOAuthTokens(window.location.hash) || hasStoredAuthSession();
|
|
56
|
+
};
|
|
57
|
+
|
|
33
58
|
type LoginMessagePayload = {
|
|
34
59
|
method?: 'oauth' | 'web3';
|
|
35
60
|
provider?: string;
|
|
@@ -40,6 +65,7 @@ type LoginMessagePayload = {
|
|
|
40
65
|
|
|
41
66
|
export const AuthProvider = ({ children }: { children: ReactNode }) => {
|
|
42
67
|
const { config } = useConfig();
|
|
68
|
+
const { i18n } = useTranslation();
|
|
43
69
|
const bffAuthEnabled = isBffAuthEnabledFromConfig(config.security);
|
|
44
70
|
const backend = useMemo(
|
|
45
71
|
() => createAuthBackend(config.backend),
|
|
@@ -72,7 +98,7 @@ export const AuthProvider = ({ children }: { children: ReactNode }) => {
|
|
|
72
98
|
);
|
|
73
99
|
|
|
74
100
|
const [session, setSession] = useState<AuthSession | null>(null);
|
|
75
|
-
const [isLoading, setIsLoading] = useState(
|
|
101
|
+
const [isLoading, setIsLoading] = useState(hasInitialSessionToResolve);
|
|
76
102
|
const [error, setError] = useState<string | null>(null);
|
|
77
103
|
const [errorCode, setErrorCode] = useState<string | null>(null);
|
|
78
104
|
const [authEvent, setAuthEvent] = useState<AuthEvent>(null);
|
|
@@ -139,38 +165,46 @@ export const AuthProvider = ({ children }: { children: ReactNode }) => {
|
|
|
139
165
|
return;
|
|
140
166
|
}
|
|
141
167
|
|
|
142
|
-
|
|
143
|
-
if (isTokenAutoRefreshDisabled()) {
|
|
144
|
-
if (!cancelled) {
|
|
145
|
-
setSession(stored);
|
|
146
|
-
setIsLoading(false);
|
|
147
|
-
}
|
|
148
|
-
return;
|
|
149
|
-
}
|
|
168
|
+
const applyRestoredSession = async (source: AuthSession) => {
|
|
150
169
|
try {
|
|
151
|
-
const restored = await
|
|
170
|
+
const restored = await shareInFlight(restoreRefreshSlot, () =>
|
|
171
|
+
refreshAuthSession(source, now),
|
|
172
|
+
);
|
|
152
173
|
if (!restored) {
|
|
153
|
-
|
|
174
|
+
// Only the active mount may clear — a cancelled StrictMode pass must not wipe
|
|
175
|
+
// storage after a sibling mount already rotated the refresh token.
|
|
154
176
|
if (!cancelled) {
|
|
177
|
+
clearStoredAuthSession();
|
|
155
178
|
setSession(null);
|
|
156
179
|
setIsLoading(false);
|
|
157
180
|
}
|
|
158
181
|
return;
|
|
159
182
|
}
|
|
183
|
+
// Persist even when cancelled so a rotated refresh token is not lost mid-remount.
|
|
160
184
|
persistAuthSession(restored, { storeRefreshToken: !bffAuthEnabled });
|
|
161
185
|
if (!cancelled) {
|
|
162
186
|
setSession(restored);
|
|
163
187
|
setIsLoading(false);
|
|
164
188
|
}
|
|
165
|
-
return;
|
|
166
189
|
} catch {
|
|
167
|
-
clearStoredAuthSession();
|
|
168
190
|
if (!cancelled) {
|
|
191
|
+
clearStoredAuthSession();
|
|
169
192
|
setSession(null);
|
|
170
193
|
setIsLoading(false);
|
|
171
194
|
}
|
|
195
|
+
}
|
|
196
|
+
};
|
|
197
|
+
|
|
198
|
+
if (!stored.accessToken && (stored.refreshToken || bffAuthEnabled)) {
|
|
199
|
+
if (isTokenAutoRefreshDisabled()) {
|
|
200
|
+
if (!cancelled) {
|
|
201
|
+
setSession(stored);
|
|
202
|
+
setIsLoading(false);
|
|
203
|
+
}
|
|
172
204
|
return;
|
|
173
205
|
}
|
|
206
|
+
await applyRestoredSession(stored);
|
|
207
|
+
return;
|
|
174
208
|
}
|
|
175
209
|
|
|
176
210
|
if (!isSessionExpired(stored)) {
|
|
@@ -193,29 +227,7 @@ export const AuthProvider = ({ children }: { children: ReactNode }) => {
|
|
|
193
227
|
return;
|
|
194
228
|
}
|
|
195
229
|
|
|
196
|
-
|
|
197
|
-
const restored = await refreshAuthSession(stored, now);
|
|
198
|
-
if (!restored) {
|
|
199
|
-
clearStoredAuthSession();
|
|
200
|
-
if (!cancelled) {
|
|
201
|
-
setSession(null);
|
|
202
|
-
setIsLoading(false);
|
|
203
|
-
}
|
|
204
|
-
return;
|
|
205
|
-
}
|
|
206
|
-
|
|
207
|
-
if (!cancelled) {
|
|
208
|
-
persistAuthSession(restored, { storeRefreshToken: !bffAuthEnabled });
|
|
209
|
-
setSession(restored);
|
|
210
|
-
setIsLoading(false);
|
|
211
|
-
}
|
|
212
|
-
} catch {
|
|
213
|
-
clearStoredAuthSession();
|
|
214
|
-
if (!cancelled) {
|
|
215
|
-
setSession(null);
|
|
216
|
-
setIsLoading(false);
|
|
217
|
-
}
|
|
218
|
-
}
|
|
230
|
+
await applyRestoredSession(stored);
|
|
219
231
|
};
|
|
220
232
|
|
|
221
233
|
void initializeSession();
|
|
@@ -465,15 +477,18 @@ export const AuthProvider = ({ children }: { children: ReactNode }) => {
|
|
|
465
477
|
const getAuthSettings = useCallback(() => backend.getAuthSettings(), [backend]);
|
|
466
478
|
|
|
467
479
|
const sendMagicLink = useCallback(
|
|
468
|
-
async (email: string, redirectPath = urls.
|
|
480
|
+
async (email: string, redirectPath = urls.loginCallback) => {
|
|
469
481
|
try {
|
|
470
|
-
await backend.sendMagicLink(email, redirectPath
|
|
482
|
+
await backend.sendMagicLink(email, redirectPath, {
|
|
483
|
+
language: i18n.resolvedLanguage ?? i18n.language,
|
|
484
|
+
});
|
|
471
485
|
} catch (err) {
|
|
486
|
+
if (err instanceof AuthRequestError) throw err;
|
|
472
487
|
const message = err instanceof Error ? err.message : 'Could not send magic link.';
|
|
473
488
|
throw new Error(message);
|
|
474
489
|
}
|
|
475
490
|
},
|
|
476
|
-
[backend],
|
|
491
|
+
[backend, i18n],
|
|
477
492
|
);
|
|
478
493
|
|
|
479
494
|
const syncUserPreferences = useCallback(
|
|
@@ -557,6 +572,198 @@ export const AuthProvider = ({ children }: { children: ReactNode }) => {
|
|
|
557
572
|
return () => cleanup();
|
|
558
573
|
}, [logout]);
|
|
559
574
|
|
|
575
|
+
const deleteAccount = useCallback(async () => {
|
|
576
|
+
await backend.deleteAccount(session);
|
|
577
|
+
await logout();
|
|
578
|
+
}, [backend, logout, session]);
|
|
579
|
+
|
|
580
|
+
const updateProfile = useCallback(
|
|
581
|
+
async ({ name }: { name: string }) => {
|
|
582
|
+
const saved = await backend.updateProfile(session, { name });
|
|
583
|
+
const current = sessionRef.current;
|
|
584
|
+
if (current) {
|
|
585
|
+
const next = { ...current, userName: saved.name };
|
|
586
|
+
persistAuthSession(next, bffAuthEnabled ? { storeRefreshToken: false } : undefined);
|
|
587
|
+
setSession(next);
|
|
588
|
+
}
|
|
589
|
+
return saved;
|
|
590
|
+
},
|
|
591
|
+
[backend, bffAuthEnabled, session],
|
|
592
|
+
);
|
|
593
|
+
|
|
594
|
+
useEffect(() => {
|
|
595
|
+
if (typeof window === 'undefined' || window.parent !== window) {
|
|
596
|
+
return;
|
|
597
|
+
}
|
|
598
|
+
|
|
599
|
+
const cleanup = shellui.addMessageListener('SHELLUI_UPDATE_PROFILE_REQUEST', (message) => {
|
|
600
|
+
const payload = message.payload as { id?: unknown; name?: unknown } | undefined;
|
|
601
|
+
const id = payload?.id;
|
|
602
|
+
if (typeof id !== 'string' || !id) {
|
|
603
|
+
return;
|
|
604
|
+
}
|
|
605
|
+
const from = message.from?.filter(Boolean) as string[] | undefined;
|
|
606
|
+
const reply = (result: UpdateProfileResult) => {
|
|
607
|
+
const response = {
|
|
608
|
+
type: 'SHELLUI_UPDATE_PROFILE_RESULT' as const,
|
|
609
|
+
payload: { id, ...result },
|
|
610
|
+
};
|
|
611
|
+
if (from?.length) {
|
|
612
|
+
shellui.sendMessage({ ...response, to: from });
|
|
613
|
+
return;
|
|
614
|
+
}
|
|
615
|
+
postShellMessage(response);
|
|
616
|
+
};
|
|
617
|
+
|
|
618
|
+
if (
|
|
619
|
+
!backend.supportsProfileUpdate ||
|
|
620
|
+
!session ||
|
|
621
|
+
typeof payload?.name !== 'string' ||
|
|
622
|
+
!isShellSettingsFrameMessage(
|
|
623
|
+
from,
|
|
624
|
+
shellui.frameRegistry,
|
|
625
|
+
urls.settings,
|
|
626
|
+
window.location.origin,
|
|
627
|
+
)
|
|
628
|
+
) {
|
|
629
|
+
logger.warn('Rejected profile update request', { from });
|
|
630
|
+
reply({ status: 'error' });
|
|
631
|
+
return;
|
|
632
|
+
}
|
|
633
|
+
|
|
634
|
+
void updateProfile({ name: payload.name }).then(
|
|
635
|
+
(saved) => reply({ status: 'saved', name: saved.name }),
|
|
636
|
+
(err: unknown) => {
|
|
637
|
+
logger.error('Profile update failed', { err });
|
|
638
|
+
reply({ status: 'error', error: err instanceof Error ? err.message : undefined });
|
|
639
|
+
},
|
|
640
|
+
);
|
|
641
|
+
});
|
|
642
|
+
|
|
643
|
+
return () => cleanup();
|
|
644
|
+
}, [backend, session, updateProfile]);
|
|
645
|
+
|
|
646
|
+
useEffect(() => {
|
|
647
|
+
if (typeof window === 'undefined' || window.parent !== window) {
|
|
648
|
+
return;
|
|
649
|
+
}
|
|
650
|
+
|
|
651
|
+
const cleanup = shellui.addMessageListener('SHELLUI_DELETE_ACCOUNT_REQUEST', (message) => {
|
|
652
|
+
const id = (message.payload as { id?: unknown } | undefined)?.id;
|
|
653
|
+
if (typeof id !== 'string' || !id) {
|
|
654
|
+
return;
|
|
655
|
+
}
|
|
656
|
+
const from = message.from?.filter(Boolean) as string[] | undefined;
|
|
657
|
+
const reply = (status: DeleteAccountResultStatus) => {
|
|
658
|
+
const result = {
|
|
659
|
+
type: 'SHELLUI_DELETE_ACCOUNT_RESULT' as const,
|
|
660
|
+
payload: { id, status },
|
|
661
|
+
};
|
|
662
|
+
if (from?.length) {
|
|
663
|
+
shellui.sendMessage({ ...result, to: from });
|
|
664
|
+
return;
|
|
665
|
+
}
|
|
666
|
+
postShellMessage(result);
|
|
667
|
+
};
|
|
668
|
+
|
|
669
|
+
if (
|
|
670
|
+
!backend.supportsAccountDeletion ||
|
|
671
|
+
!session ||
|
|
672
|
+
!isShellSettingsFrameMessage(
|
|
673
|
+
from,
|
|
674
|
+
shellui.frameRegistry,
|
|
675
|
+
urls.settings,
|
|
676
|
+
window.location.origin,
|
|
677
|
+
)
|
|
678
|
+
) {
|
|
679
|
+
logger.warn('Rejected account deletion request', { from });
|
|
680
|
+
reply('error');
|
|
681
|
+
return;
|
|
682
|
+
}
|
|
683
|
+
|
|
684
|
+
const t = i18n.getFixedT(null, 'settings');
|
|
685
|
+
const appName = config.title?.trim() || window.location.host;
|
|
686
|
+
const isAdmin = session.userIsCompanyOwner === true || session.userIsStaff === true;
|
|
687
|
+
const description = [
|
|
688
|
+
t('userAccount.deleteAccount.description', { appName }),
|
|
689
|
+
isAdmin ? t('userAccount.deleteAccount.adminWarning', { appName }) : null,
|
|
690
|
+
]
|
|
691
|
+
.filter(Boolean)
|
|
692
|
+
.join('\n\n');
|
|
693
|
+
shellui.dialog({
|
|
694
|
+
title: t('userAccount.deleteAccount.title'),
|
|
695
|
+
description,
|
|
696
|
+
mode: 'delete',
|
|
697
|
+
size: 'sm',
|
|
698
|
+
okLabel: t('userAccount.deleteAccount.confirm'),
|
|
699
|
+
cancelLabel: t('userAccount.deleteAccount.cancel'),
|
|
700
|
+
onOk: () => {
|
|
701
|
+
void (async () => {
|
|
702
|
+
try {
|
|
703
|
+
await deleteAccount();
|
|
704
|
+
reply('deleted');
|
|
705
|
+
postShellMessage({ type: 'SHELLUI_CLOSE_MODAL', payload: {} });
|
|
706
|
+
postShellMessage({ type: 'SHELLUI_CLOSE_DRAWER', payload: {} });
|
|
707
|
+
shellui.toast({
|
|
708
|
+
type: 'success',
|
|
709
|
+
title: t('userAccount.deleteAccount.successTitle'),
|
|
710
|
+
description: t('userAccount.deleteAccount.successDescription', { appName }),
|
|
711
|
+
});
|
|
712
|
+
} catch (err) {
|
|
713
|
+
reply('error');
|
|
714
|
+
const errorCode = getAuthRequestErrorCode(err);
|
|
715
|
+
if (errorCode === 'last_company_owner') {
|
|
716
|
+
const companies =
|
|
717
|
+
err instanceof AuthRequestError && Array.isArray(err.details.companies)
|
|
718
|
+
? (err.details.companies as Array<{ name?: unknown }>)
|
|
719
|
+
.map((c) => (typeof c?.name === 'string' ? c.name : ''))
|
|
720
|
+
.filter(Boolean)
|
|
721
|
+
.join(', ')
|
|
722
|
+
: '';
|
|
723
|
+
shellui.dialog({
|
|
724
|
+
title: t('userAccount.deleteAccount.lastOwnerTitle'),
|
|
725
|
+
description: t('userAccount.deleteAccount.lastOwnerDescription', {
|
|
726
|
+
companies: companies || appName,
|
|
727
|
+
}),
|
|
728
|
+
mode: 'ok',
|
|
729
|
+
size: 'sm',
|
|
730
|
+
});
|
|
731
|
+
return;
|
|
732
|
+
}
|
|
733
|
+
if (errorCode === 'recent_login_required') {
|
|
734
|
+
shellui.dialog({
|
|
735
|
+
title: t('userAccount.deleteAccount.reauthTitle'),
|
|
736
|
+
description: t('userAccount.deleteAccount.reauthDescription'),
|
|
737
|
+
mode: 'okCancel',
|
|
738
|
+
size: 'sm',
|
|
739
|
+
okLabel: t('userAccount.deleteAccount.reauthAction'),
|
|
740
|
+
cancelLabel: t('userAccount.deleteAccount.cancel'),
|
|
741
|
+
onOk: () => {
|
|
742
|
+
void logout().then(() => {
|
|
743
|
+
window.location.assign(
|
|
744
|
+
buildAuthUrlWithNext(urls.login, `${urls.settings}/user`),
|
|
745
|
+
);
|
|
746
|
+
});
|
|
747
|
+
},
|
|
748
|
+
});
|
|
749
|
+
return;
|
|
750
|
+
}
|
|
751
|
+
logger.error('Account deletion failed', { err });
|
|
752
|
+
shellui.toast({
|
|
753
|
+
type: 'error',
|
|
754
|
+
title: t('userAccount.deleteAccount.errorTitle'),
|
|
755
|
+
description: err instanceof Error ? err.message : undefined,
|
|
756
|
+
});
|
|
757
|
+
}
|
|
758
|
+
})();
|
|
759
|
+
},
|
|
760
|
+
onCancel: () => reply('cancelled'),
|
|
761
|
+
});
|
|
762
|
+
});
|
|
763
|
+
|
|
764
|
+
return () => cleanup();
|
|
765
|
+
}, [backend, config.title, deleteAccount, i18n, logout, session]);
|
|
766
|
+
|
|
560
767
|
useEffect(() => {
|
|
561
768
|
if (typeof window === 'undefined' || window.parent !== window) {
|
|
562
769
|
return;
|
|
@@ -628,8 +835,16 @@ export const AuthProvider = ({ children }: { children: ReactNode }) => {
|
|
|
628
835
|
syncUserPreferences,
|
|
629
836
|
loadUserPreferences,
|
|
630
837
|
logout,
|
|
838
|
+
supportsAccountDeletion: backend.supportsAccountDeletion,
|
|
839
|
+
deleteAccount,
|
|
840
|
+
supportsProfileUpdate: backend.supportsProfileUpdate,
|
|
841
|
+
updateProfile,
|
|
631
842
|
}),
|
|
632
843
|
[
|
|
844
|
+
backend.supportsAccountDeletion,
|
|
845
|
+
deleteAccount,
|
|
846
|
+
backend.supportsProfileUpdate,
|
|
847
|
+
updateProfile,
|
|
633
848
|
session,
|
|
634
849
|
user,
|
|
635
850
|
isLoading,
|
|
@@ -17,6 +17,14 @@ const createNoopBackend = (): AuthBackend => ({
|
|
|
17
17
|
throw new Error('No auth backend configured.');
|
|
18
18
|
},
|
|
19
19
|
logout: async () => {},
|
|
20
|
+
supportsAccountDeletion: false,
|
|
21
|
+
deleteAccount: async () => {
|
|
22
|
+
throw new Error('No auth backend configured.');
|
|
23
|
+
},
|
|
24
|
+
supportsProfileUpdate: false,
|
|
25
|
+
updateProfile: async () => {
|
|
26
|
+
throw new Error('No auth backend configured.');
|
|
27
|
+
},
|
|
20
28
|
getAuthSettings: async () => ({ methods: [], oauthProviders: [], oauthClients: [] }),
|
|
21
29
|
sendMagicLink: async () => {
|
|
22
30
|
throw new Error('No auth backend configured.');
|