|
| 1 | +/** |
| 2 | + * ObjectUI |
| 3 | + * Copyright (c) 2024-present ObjectStack Inc. |
| 4 | + * |
| 5 | + * This source code is licensed under the MIT license found in the |
| 6 | + * LICENSE file in the root directory of this source tree. |
| 7 | + */ |
| 8 | + |
| 9 | +/** |
| 10 | + * Native shell mode beyond the mobile app, as the real `App` wires it. |
| 11 | + * |
| 12 | + * `ObjectStackNative.platform` is an open set: the desktop shell reports a |
| 13 | + * value other than `ios` or `android`, and announces only the capabilities it |
| 14 | + * has. The Console must treat that host exactly like the mobile one: shell |
| 15 | + * mode on, `ready` posted once, the root attribute carrying the platform |
| 16 | + * verbatim, and no call to a method the shell did not announce. |
| 17 | + * |
| 18 | + * Two more pins sit beside it: |
| 19 | + * |
| 20 | + * - `ready` means "the Console has painted its own UI". On a cold start to a |
| 21 | + * protected route that UI is the auth guard's loading fallback, and `ready` |
| 22 | + * is posted while it is still on screen, so the shell's loading cover hands |
| 23 | + * over to the Console's spinner instead of waiting out the session read. |
| 24 | + * - A bridge speaking a newer protocol than this Console (`version` 2) reads |
| 25 | + * as no bridge: no shell mode and no `ready`. |
| 26 | + * |
| 27 | + * `App` is the real module under the real `BrowserRouter`, and so are |
| 28 | + * `ProtectedRoute` and `AuthGuard`; the pages and the shell chrome are stubs, |
| 29 | + * as in `App.nativeShellMode-29039.test.tsx`. |
| 30 | + */ |
| 31 | + |
| 32 | +import { describe, expect, it, vi, afterEach, beforeEach, type Mock } from 'vitest'; |
| 33 | +import { render, screen, cleanup } from '@testing-library/react'; |
| 34 | +import type { ReactNode } from 'react'; |
| 35 | +import { |
| 36 | + NATIVE_HOST_GLOBAL, |
| 37 | + nativeGetPushToken, |
| 38 | + nativeHaptic, |
| 39 | + nativeNavigate, |
| 40 | + nativeOpenExternal, |
| 41 | + nativeResetServer, |
| 42 | + resetNativeHostEventsForTests, |
| 43 | + type ObjectStackNative, |
| 44 | +} from '../../../../packages/mobile/src/nativeHost'; |
| 45 | +import { resetNativeHostWatchForTests } from '../../../../packages/mobile/src/useNativeHost'; |
| 46 | + |
| 47 | +const { passthrough, stub, authState } = vi.hoisted(() => { |
| 48 | + const passthrough = ({ children }: { children?: ReactNode }) => <>{children}</>; |
| 49 | + const stub = (testid: string) => () => <div data-testid={testid} />; |
| 50 | + /** What the session read has answered so far; `isLoading` is a cold start. */ |
| 51 | + const authState = { isLoading: false }; |
| 52 | + return { passthrough, stub, authState }; |
| 53 | +}); |
| 54 | + |
| 55 | +vi.mock('@object-ui/app-shell', async (importOriginal) => ({ |
| 56 | + ...(await importOriginal<Record<string, unknown>>()), |
| 57 | + ConsoleShell: passthrough, |
| 58 | + ConsoleToaster: () => null, |
| 59 | + ConnectedShell: passthrough, |
| 60 | + RequireOrganization: passthrough, |
| 61 | + LoadingFallback: stub('auth-loading-fallback'), |
| 62 | + LoadingScreen: stub('loading-screen'), |
| 63 | + RedirectWithSplash: stub('redirect-with-splash'), |
| 64 | + RequireAiSurface: passthrough, |
| 65 | + SystemRedirect: () => null, |
| 66 | + DefaultHomeLayout: passthrough, |
| 67 | + DefaultHomePage: stub('home-page'), |
| 68 | + DefaultOrganizationsLayout: passthrough, |
| 69 | + DefaultOrganizationsPage: stub('organizations-page'), |
| 70 | + DefaultOrganizationLayout: stub('organization-layout'), |
| 71 | + DefaultMembersPage: stub('members-page'), |
| 72 | + DefaultInvitationsPage: stub('invitations-page'), |
| 73 | + DefaultSettingsPage: stub('settings-page'), |
| 74 | + DefaultAcceptInvitationPage: stub('accept-invitation-page'), |
| 75 | + DefaultAiChatPage: stub('ai-chat-page'), |
| 76 | + StudioDesignSurface: stub('studio-design-surface'), |
| 77 | + BuilderLanding: stub('builder-landing'), |
| 78 | + getProductName: () => 'ObjectOS', |
| 79 | + getFaviconUrl: () => '', |
| 80 | +})); |
| 81 | + |
| 82 | +// The real `AuthGuard` reads the real auth context. The provider is replaced |
| 83 | +// by one that publishes `authState`, so a test can hold the session read open. |
| 84 | +vi.mock('@object-ui/auth', async (importOriginal) => { |
| 85 | + const actual = await importOriginal<typeof import('@object-ui/auth')>(); |
| 86 | + const { AuthCtx } = await import('../../../../packages/auth/src/AuthContext'); |
| 87 | + function AuthStateProvider({ children }: { children?: ReactNode }) { |
| 88 | + // Outside any provider `useAuth` answers its signed-out defaults. |
| 89 | + const signedOut = actual.useAuth(); |
| 90 | + return <AuthCtx.Provider value={{ ...signedOut, isLoading: authState.isLoading }}>{children}</AuthCtx.Provider>; |
| 91 | + } |
| 92 | + return { ...actual, AuthProvider: AuthStateProvider }; |
| 93 | +}); |
| 94 | + |
| 95 | +vi.mock('../AppContent', () => ({ |
| 96 | + AppContent: stub('app-content'), |
| 97 | + ConsolePermissionsScope: ({ children }: { children?: ReactNode }) => <>{children}</>, |
| 98 | + ConsolePermissionsRequest: () => null, |
| 99 | +})); |
| 100 | +vi.mock('../components/RootLandingRedirect', () => ({ RootLandingRedirect: stub('root-landing') })); |
| 101 | +vi.mock('../components/SetupRoute', () => ({ SetupRoute: stub('setup-route') })); |
| 102 | +vi.mock('../components/FormPage', () => ({ FormPage: stub('form-page') })); |
| 103 | +vi.mock('../components/InternalFormRoute', () => ({ InternalFormRoute: stub('internal-form-route') })); |
| 104 | +vi.mock('../components/MetadataHmrReloader', () => ({ MetadataHmrReloader: () => null })); |
| 105 | +vi.mock('../pages/auth/LoginPage', () => ({ LoginPage: stub('login-page') })); |
| 106 | +vi.mock('../pages/auth/RegisterPage', () => ({ RegisterPage: stub('register-page') })); |
| 107 | +vi.mock('../pages/auth/ForgotPasswordPage', () => ({ ForgotPasswordPage: stub('forgot-page') })); |
| 108 | +vi.mock('../pages/auth/ResetPasswordPage', () => ({ ResetPasswordPage: stub('reset-page') })); |
| 109 | +vi.mock('../pages/auth/SetPasswordPage', () => ({ SetPasswordPage: stub('set-password-page') })); |
| 110 | +vi.mock('../pages/auth/VerifyEmailPage', () => ({ VerifyEmailPage: stub('verify-email-page') })); |
| 111 | +vi.mock('../pages/auth/VerifyEmailPromptPage', () => ({ VerifyEmailPromptPage: stub('verify-prompt-page') })); |
| 112 | +vi.mock('../pages/auth/OAuthConsentPage', () => ({ OAuthConsentPage: stub('oauth-consent-page') })); |
| 113 | +vi.mock('../pages/auth/DeviceAuthPage', () => ({ DeviceAuthPage: stub('device-auth-page') })); |
| 114 | +vi.mock('../dev/DevMasterDetail', () => ({ DevMasterDetail: stub('dev-master-detail') })); |
| 115 | +vi.mock('../dev/DevLists', () => ({ DevLists: stub('dev-lists') })); |
| 116 | +vi.mock('../dev/DevModal', () => ({ DevModal: stub('dev-modal') })); |
| 117 | +vi.mock('../dev/DevLookup', () => ({ DevLookup: stub('dev-lookup') })); |
| 118 | +vi.mock('../dev/DevRowActions', () => ({ DevRowActions: stub('dev-row-actions') })); |
| 119 | +vi.mock('sonner', () => ({ toast: { success: vi.fn(), error: vi.fn() } })); |
| 120 | + |
| 121 | +import { App } from '../App'; |
| 122 | + |
| 123 | +type FakeBridge = ObjectStackNative & { |
| 124 | + getPushToken: Mock<ObjectStackNative['getPushToken']>; |
| 125 | + haptic: Mock<ObjectStackNative['haptic']>; |
| 126 | + openExternal: Mock<ObjectStackNative['openExternal']>; |
| 127 | + navigate: Mock<ObjectStackNative['navigate']>; |
| 128 | + resetServer: Mock<ObjectStackNative['resetServer']>; |
| 129 | +}; |
| 130 | + |
| 131 | +/** |
| 132 | + * A fake bridge recording what the Console posts. `ready` notes which of the |
| 133 | + * two first screens is up when it arrives: the shell lifts its cover on it. |
| 134 | + */ |
| 135 | +function installBridge({ |
| 136 | + platform, |
| 137 | + version = 1, |
| 138 | + capabilities, |
| 139 | +}: { |
| 140 | + platform: string; |
| 141 | + version?: number; |
| 142 | + capabilities: readonly string[]; |
| 143 | +}): { bridge: FakeBridge; events: string[] } { |
| 144 | + const events: string[] = []; |
| 145 | + const onScreen = () => |
| 146 | + screen.queryByTestId('auth-loading-fallback') |
| 147 | + ? 'auth-loading-fallback' |
| 148 | + : screen.queryByTestId('login-page') |
| 149 | + ? 'login-page' |
| 150 | + : 'nothing'; |
| 151 | + const bridge: FakeBridge = { |
| 152 | + version, |
| 153 | + platform, |
| 154 | + appVersion: '1.0.0', |
| 155 | + capabilities, |
| 156 | + safeArea: { top: 0, bottom: 0, left: 0, right: 0 }, |
| 157 | + has: (capability: string) => capabilities.includes(capability), |
| 158 | + getPushToken: vi.fn(async () => null), |
| 159 | + haptic: vi.fn(async () => null), |
| 160 | + openExternal: vi.fn(async () => null), |
| 161 | + navigate: vi.fn(async () => null), |
| 162 | + resetServer: vi.fn(async () => null), |
| 163 | + ready: () => events.push(`ready:${onScreen()}`), |
| 164 | + routeChanged: (route: string) => events.push(`route:${route}`), |
| 165 | + }; |
| 166 | + (window as unknown as Record<string, unknown>)[NATIVE_HOST_GLOBAL] = bridge; |
| 167 | + return { bridge, events }; |
| 168 | +} |
| 169 | + |
| 170 | +beforeEach(() => { |
| 171 | + resetNativeHostEventsForTests(); |
| 172 | + resetNativeHostWatchForTests(); |
| 173 | + authState.isLoading = false; |
| 174 | + window.history.pushState({}, '', '/login'); |
| 175 | +}); |
| 176 | + |
| 177 | +afterEach(() => { |
| 178 | + cleanup(); |
| 179 | + delete (window as unknown as Record<string, unknown>)[NATIVE_HOST_GLOBAL]; |
| 180 | + window.history.pushState({}, '', '/'); |
| 181 | +}); |
| 182 | + |
| 183 | +describe('a shell whose platform is neither ios nor android', () => { |
| 184 | + it('desktop with a capability subset: shell mode on, ready once, the platform verbatim, nothing unannounced called', async () => { |
| 185 | + const { bridge, events } = installBridge({ platform: 'desktop', capabilities: ['haptic', 'openExternal'] }); |
| 186 | + const { rerender } = render(<App />); |
| 187 | + expect(await screen.findByTestId('login-page')).toBeInTheDocument(); |
| 188 | + |
| 189 | + expect(document.documentElement.getAttribute('data-os-native-shell')).toBe('desktop'); |
| 190 | + expect(events).toEqual(['ready:login-page', 'route:/login']); |
| 191 | + |
| 192 | + // Every typed call, from inside the running Console: the announced ones |
| 193 | + // reach the shell, the rest resolve `unavailable` without a call. |
| 194 | + await expect(nativeHaptic('success')).resolves.toEqual({ status: 'ok', value: null }); |
| 195 | + await expect(nativeOpenExternal('https://example.com')).resolves.toEqual({ status: 'ok', value: null }); |
| 196 | + await expect(nativeGetPushToken()).resolves.toEqual({ status: 'unavailable' }); |
| 197 | + await expect(nativeNavigate('/home')).resolves.toEqual({ status: 'unavailable' }); |
| 198 | + await expect(nativeResetServer()).resolves.toEqual({ status: 'unavailable' }); |
| 199 | + |
| 200 | + rerender(<App />); |
| 201 | + expect(events.filter((e) => e.startsWith('ready:'))).toHaveLength(1); |
| 202 | + expect(bridge.haptic).toHaveBeenCalledTimes(1); |
| 203 | + expect(bridge.openExternal).toHaveBeenCalledTimes(1); |
| 204 | + expect(bridge.getPushToken).not.toHaveBeenCalled(); |
| 205 | + expect(bridge.navigate).not.toHaveBeenCalled(); |
| 206 | + expect(bridge.resetServer).not.toHaveBeenCalled(); |
| 207 | + }); |
| 208 | +}); |
| 209 | + |
| 210 | +describe('what ready means: the Console has painted its own UI', () => { |
| 211 | + it('a cold start to a protected route posts ready while the auth guard still shows its loading fallback', async () => { |
| 212 | + authState.isLoading = true; |
| 213 | + window.history.pushState({}, '', '/'); |
| 214 | + const { events } = installBridge({ platform: 'ios', capabilities: [] }); |
| 215 | + render(<App />); |
| 216 | + expect(await screen.findByTestId('auth-loading-fallback')).toBeInTheDocument(); |
| 217 | + // The session is still being read: the guard has not let the route through. |
| 218 | + expect(screen.queryByTestId('root-landing')).not.toBeInTheDocument(); |
| 219 | + expect(events).toEqual(['ready:auth-loading-fallback', 'route:/']); |
| 220 | + }); |
| 221 | +}); |
| 222 | + |
| 223 | +describe('a bridge speaking a newer protocol is no bridge', () => { |
| 224 | + it('version 2: no shell mode, no ready, no route posts', async () => { |
| 225 | + const { events } = installBridge({ platform: 'ios', version: 2, capabilities: ['haptic'] }); |
| 226 | + render(<App />); |
| 227 | + expect(await screen.findByTestId('login-page')).toBeInTheDocument(); |
| 228 | + expect(document.documentElement.hasAttribute('data-os-native-shell')).toBe(false); |
| 229 | + expect(events).toEqual([]); |
| 230 | + await expect(nativeHaptic('success')).resolves.toEqual({ status: 'unavailable' }); |
| 231 | + }); |
| 232 | + |
| 233 | + it('control: version 1, the same bridge otherwise, is the shell', async () => { |
| 234 | + const { events } = installBridge({ platform: 'ios', version: 1, capabilities: ['haptic'] }); |
| 235 | + render(<App />); |
| 236 | + expect(await screen.findByTestId('login-page')).toBeInTheDocument(); |
| 237 | + expect(document.documentElement.getAttribute('data-os-native-shell')).toBe('ios'); |
| 238 | + expect(events).toEqual(['ready:login-page', 'route:/login']); |
| 239 | + }); |
| 240 | +}); |
0 commit comments