Skip to content

Commit 31642f9

Browse files
committed
wip(mobile): native host platform open set and bridge version gate
Claude-Session: https://claude.ai/code/session_01QsR2jSpg4SQPs6XFLsrBhv Co-authored-by: Claude <noreply@anthropic.com>
1 parent eef116e commit 31642f9

5 files changed

Lines changed: 297 additions & 9 deletions

File tree

‎.changeset/29039-mobile-native-shell-mode.md‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -13,4 +13,4 @@ The ObjectStack mobile app hosts the web Console in a WebView and injects a brid
1313
- **`@object-ui/mobile` gains the bridge type and detection.** `ObjectStackNative` types exactly the members of the shell's bridge contract (`version`, `platform`, `appVersion`, `capabilities`, `safeArea`, `has`, the five calls and the two events). `useNativeHost()` returns it, or `null` outside the shell; it reads the global lazily and re-checks at `DOMContentLoaded`, `load` and a few points after `load`, so a late injection still arrives. `getNativeHost()` is the same read outside React.
1414
- **Typed calls that never throw.** `nativeGetPushToken`, `nativeHaptic`, `nativeOpenExternal`, `nativeNavigate` and `nativeResetServer` check `has(capability)` and that the method exists, and resolve a `NativeCallResult`: `{ status: 'unavailable' }`, `{ status: 'ok', value }`, or `{ status: 'failed', code, message }`.
1515
- **Router wiring.** `useNativeHostRouting({ route, navigate })` posts `ready()` once per page load after the first route has rendered, posts `routeChanged(route)` once per route change, and answers the shell's cancelable `objectstack-native:navigate` window event by moving the router to `detail.route` (an in-app path only) and cancelling the event, so a notification tap does not reload the Console. Outside the shell it installs nothing.
16-
- **The Console uses it.** In the shell the Console posts those events from its router, marks the root element with `data-os-native-shell="ios|android"`, and drops the PWA install manifest. It adds no safe-area padding: the shell already pads its WebView. Without the global the Console behaves exactly as before.
16+
- **The Console uses it.** In the shell the Console posts those events from its router, marks the root element with `data-os-native-shell` set to the shell's platform string (an open set: `ios` and `android` from the mobile app, another value from another shell), and drops the PWA install manifest. It adds no safe-area padding: the shell already pads its WebView. Without the global the Console behaves exactly as before.
Lines changed: 240 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,240 @@
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+
});

‎ui/packages/mobile/README.md‎

Lines changed: 13 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -286,22 +286,32 @@ shell; the bridge contract is owned by the mobile app (`docs/HYBRID-SHELL.md`,
286286
- `useNativeHost()` returns the bridge, or `null` outside the shell. It reads the
287287
global lazily and re-checks at `DOMContentLoaded`, `load` and a few points after
288288
`load`, so a bridge injected after the first render still arrives.
289+
- `platform` is the shell's platform string, an open set: `ios` and `android` from
290+
the mobile app, another value from another shell (the desktop one). Do not branch
291+
on it; branch on the viewport or on a capability.
292+
- This package speaks bridge protocol version `1`; the bridge's `version` bumps only
293+
on a breaking change. A bridge whose `version` is higher, or not a number, reads as
294+
no bridge: `null` from `useNativeHost()` and `getNativeHost()`, so the page keeps
295+
its browser behaviour.
289296
- `useNativeHostRouting({ route, navigate })` wires a router to the shell: `ready()`
290297
once per page load after the first commit, `routeChanged(route)` once per route
291298
change, and the shell's cancelable `objectstack-native:navigate` window event moves
292299
the router (in-app paths only) instead of reloading the page. Outside the shell it
293300
installs nothing.
301+
- `ready()` means "the page has painted its own UI", which may be a loading fallback,
302+
such as an auth guard's spinner while the session is read. The shell lifts its
303+
loading cover on it, so the cover hands over to that spinner instead of staying up
304+
through the session round-trip.
294305
- `nativeGetPushToken`, `nativeHaptic`, `nativeOpenExternal`, `nativeNavigate` and
295306
`nativeResetServer` check `has(capability)` and that the method exists before
296307
calling. They never throw: each resolves `{ status: 'unavailable' }` without the
297308
capability, `{ status: 'ok', value }` on success, or
298309
`{ status: 'failed', code, message }` when the shell refuses the call.
299310

300311
```tsx
301-
import { nativeHaptic, useNativeHost } from '@object-ui/mobile';
312+
import { nativeHaptic } from '@object-ui/mobile';
302313

303314
export function SaveButton({ onSave }: { onSave: () => Promise<void> }) {
304-
const host = useNativeHost();
305315
return (
306316
<button
307317
type="button"
@@ -311,7 +321,7 @@ export function SaveButton({ onSave }: { onSave: () => Promise<void> }) {
311321
await nativeHaptic('success');
312322
}}
313323
>
314-
{host ? 'Save' : 'Save changes'}
324+
Save
315325
</button>
316326
);
317327
}

‎ui/packages/mobile/src/nativeHost.ts‎

Lines changed: 35 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -23,6 +23,15 @@
2323
/** The global name the shell injects. */
2424
export const NATIVE_HOST_GLOBAL = 'ObjectStackNative';
2525

26+
/**
27+
* The bridge protocol version this Console speaks. A bridge's `version` bumps
28+
* only on a breaking change, so a host announcing a higher version (or no
29+
* numeric version at all) speaks a protocol this Console cannot read:
30+
* `getNativeHost()` answers `null` for it, and the Console runs as it does in
31+
* a browser.
32+
*/
33+
export const NATIVE_BRIDGE_VERSION = 1;
34+
2635
/**
2736
* The window event the shell dispatches when it opens a Console route without
2837
* reloading the page (a notification tap, an app link, a bridge `navigate`).
@@ -62,7 +71,12 @@ export type NativeHostMethod = 'getPushToken' | 'haptic' | 'openExternal' | 'nav
6271
export interface ObjectStackNative {
6372
/** Bridge protocol version; bumps only on a breaking change. */
6473
readonly version: number;
65-
readonly platform: 'ios' | 'android';
74+
/**
75+
* The shell's platform string. An open set: the mobile shell reports `ios`
76+
* or `android`, and another shell (the desktop one) reports its own value.
77+
* Branch on a capability (`has()`) or the viewport, never on this value.
78+
*/
79+
readonly platform: 'ios' | 'android' | (string & {});
6680
readonly appVersion: string;
6781
/** Feature-detect with `has()`. */
6882
readonly capabilities: readonly string[];
@@ -78,7 +92,10 @@ export interface ObjectStackNative {
7892
/** Forget the configured server and return to the shell's server picker. */
7993
resetServer(): Promise<null>;
8094

81-
/** Event: the page is interactive (the shell lifts its loading cover). */
95+
/**
96+
* Event: the Console has painted its own UI, which may be a loading
97+
* fallback (the shell lifts its loading cover on it). See `postNativeReady`.
98+
*/
8299
ready(): void;
83100
/** Event: the SPA route changed. */
84101
routeChanged(route: string): void;
@@ -105,11 +122,19 @@ type NativeWindow = Window & { [NATIVE_HOST_GLOBAL]?: unknown };
105122
* The bridge when the shell has injected it, otherwise `null`. Reads the
106123
* global on every call, so a bridge injected after the first render is seen
107124
* the next time anyone asks.
125+
*
126+
* A bridge whose `version` is not a number, or is greater than
127+
* `NATIVE_BRIDGE_VERSION`, is also `null`: its protocol has broken this one,
128+
* so the Console takes its browser path (no shell mode, no `ready`, the PWA
129+
* manifest kept) rather than call methods whose meaning may have changed.
108130
*/
109131
export function getNativeHost(): ObjectStackNative | null {
110132
if (typeof window === 'undefined') return null;
111133
const host = (window as NativeWindow)[NATIVE_HOST_GLOBAL];
112-
return host !== null && typeof host === 'object' ? (host as ObjectStackNative) : null;
134+
if (host === null || typeof host !== 'object') return null;
135+
const version = 'version' in host ? host.version : undefined;
136+
if (typeof version !== 'number' || !(version <= NATIVE_BRIDGE_VERSION)) return null;
137+
return host as ObjectStackNative;
113138
}
114139

115140
/** Whether the shell announces `capability` and the bridge carries the method. */
@@ -173,6 +198,13 @@ let lastPostedRoute: string | null = null;
173198
/**
174199
* Post `ready()` to the shell. Posts at most once per page load; later calls
175200
* are no-ops. Returns whether this call posted it.
201+
*
202+
* `ready` means "the Console has painted its own UI", and that UI may be a
203+
* loading fallback: on a cold start to a protected route it is the auth
204+
* guard's spinner while the session is still being read. The shell lifts its
205+
* loading cover on `ready`, so the cover hands over to the Console's own
206+
* spinner. Waiting for the session instead would hold the native cover through
207+
* a network round-trip.
176208
*/
177209
export function postNativeReady(host: ObjectStackNative | null = getNativeHost()): boolean {
178210
if (readyPosted || !host || typeof host.ready !== 'function') return false;

0 commit comments

Comments
 (0)