mirror of
https://github.com/mauriceboe/TREK.git
synced 2026-11-21 19:40:34 +00:00
feat(native): a capability handshake between the app binary and the server's UI
The UI ships with the server and the binary through the stores, so the two drift. TrekShell.getCapabilities now reports the binary's shell API, version and native features by name (iOS and Android), and the UI turns each native feature on only where the binary has it; a binary from before the handshake counts as shell API 1 with none. The other way round, the server names the oldest binary its UI works with (minNativeShellApi), and an app below it is asked to update with a link to its store.
This commit is contained in:
@@ -0,0 +1,77 @@
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
|
||||
import {
|
||||
_resetNativeCapabilities,
|
||||
appUpdateRequired,
|
||||
checkAppUpdate,
|
||||
hasNativeFeature,
|
||||
loadNativeCapabilities,
|
||||
nativeCapabilities,
|
||||
} from './capabilities';
|
||||
import { isNativeApp } from './platform';
|
||||
import { TrekShell } from './trekShell';
|
||||
|
||||
vi.mock('./platform', () => ({ isNativeApp: vi.fn() }));
|
||||
vi.mock('./trekShell', () => ({
|
||||
TrekShell: { getCapabilities: vi.fn() },
|
||||
isUnimplemented: (err: unknown) => (err as { code?: string })?.code === 'UNIMPLEMENTED',
|
||||
}));
|
||||
|
||||
const CAPS = { shellApi: 2, platform: 'ios', appVersion: '5.2.0', build: '12', features: ['capabilities', 'edgeBack'] };
|
||||
|
||||
beforeEach(() => {
|
||||
_resetNativeCapabilities();
|
||||
vi.mocked(isNativeApp).mockReturnValue(true);
|
||||
vi.mocked(TrekShell.getCapabilities)
|
||||
.mockReset()
|
||||
.mockResolvedValue(CAPS as never);
|
||||
});
|
||||
|
||||
afterEach(() => vi.unstubAllGlobals());
|
||||
|
||||
describe('native capabilities', () => {
|
||||
it('asks the binary once and answers features by name', async () => {
|
||||
await loadNativeCapabilities();
|
||||
await loadNativeCapabilities();
|
||||
expect(TrekShell.getCapabilities).toHaveBeenCalledTimes(1);
|
||||
expect(hasNativeFeature('edgeBack')).toBe(true);
|
||||
expect(hasNativeFeature('tileCache')).toBe(false);
|
||||
expect(nativeCapabilities().appVersion).toBe('5.2.0');
|
||||
});
|
||||
|
||||
it('counts a binary from before the handshake as shell API 1 with no features', async () => {
|
||||
vi.mocked(TrekShell.getCapabilities).mockRejectedValue({ code: 'UNIMPLEMENTED' });
|
||||
const caps = await loadNativeCapabilities();
|
||||
expect(caps.shellApi).toBe(1);
|
||||
expect(hasNativeFeature('capabilities')).toBe(false);
|
||||
});
|
||||
|
||||
it('reports a real failure but still settles on the legacy answer', async () => {
|
||||
const report = vi.fn();
|
||||
vi.stubGlobal('reportError', report);
|
||||
vi.mocked(TrekShell.getCapabilities).mockRejectedValue(new Error('bridge down'));
|
||||
expect((await loadNativeCapabilities()).shellApi).toBe(1);
|
||||
expect(report).toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('asks nothing in a browser', async () => {
|
||||
vi.mocked(isNativeApp).mockReturnValue(false);
|
||||
expect((await loadNativeCapabilities()).platform).toBe('web');
|
||||
expect(TrekShell.getCapabilities).not.toHaveBeenCalled();
|
||||
expect(await checkAppUpdate(async () => ({ minNativeShellApi: 9 }))).toBe(false);
|
||||
});
|
||||
|
||||
it('asks for an update only when the server needs a newer binary', async () => {
|
||||
expect(await checkAppUpdate(async () => ({ minNativeShellApi: 2 }))).toBe(false);
|
||||
expect(await checkAppUpdate(async () => ({ minNativeShellApi: 3 }))).toBe(true);
|
||||
expect(appUpdateRequired()).toBe(true);
|
||||
});
|
||||
|
||||
it('requires nothing from a server that names no minimum, or cannot be asked', async () => {
|
||||
expect(await checkAppUpdate(async () => ({}))).toBe(false);
|
||||
expect(
|
||||
await checkAppUpdate(async () => {
|
||||
throw new Error('offline');
|
||||
})
|
||||
).toBe(false);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,102 @@
|
||||
import { useSyncExternalStore } from 'react';
|
||||
import { isNativeApp } from './platform';
|
||||
import { reportNativeFailure } from './reportFailure';
|
||||
import { TrekShell, isUnimplemented } from './trekShell';
|
||||
|
||||
/**
|
||||
* What the installed app binary offers the UI this server delivers.
|
||||
*
|
||||
* The two update on their own clocks: the UI ships with the server, the binary
|
||||
* through the stores. So the UI asks before it calls into anything native the
|
||||
* binary may predate, and turns each feature on by name (hasNativeFeature). A
|
||||
* binary from before this handshake answers UNIMPLEMENTED and counts as shell
|
||||
* API 1 with no named features, which is exactly what it can do.
|
||||
*
|
||||
* The other direction runs through the server's features: minNativeShellApi
|
||||
* names the oldest binary its UI works with, and an app below it is asked to
|
||||
* update (appUpdateRequired) rather than left calling methods it lacks.
|
||||
*/
|
||||
export interface NativeCapabilities {
|
||||
shellApi: number;
|
||||
platform: 'ios' | 'android' | 'web';
|
||||
appVersion: string;
|
||||
build: string;
|
||||
features: string[];
|
||||
}
|
||||
|
||||
const WEB: NativeCapabilities = { shellApi: 0, platform: 'web', appVersion: '', build: '', features: [] };
|
||||
const LEGACY_APP: NativeCapabilities = { shellApi: 1, platform: 'web', appVersion: '', build: '', features: [] };
|
||||
|
||||
let current: NativeCapabilities = WEB;
|
||||
let updateRequired = false;
|
||||
let loading: Promise<NativeCapabilities> | null = null;
|
||||
const listeners = new Set<() => void>();
|
||||
|
||||
function emit(): void {
|
||||
for (const listener of listeners) listener();
|
||||
}
|
||||
|
||||
/** Asks the binary once and keeps the answer for the session. */
|
||||
export function loadNativeCapabilities(): Promise<NativeCapabilities> {
|
||||
if (!isNativeApp()) return Promise.resolve(WEB);
|
||||
loading ??= TrekShell.getCapabilities()
|
||||
.then(
|
||||
(caps) => caps,
|
||||
(err: unknown) => {
|
||||
if (!isUnimplemented(err)) reportNativeFailure(err);
|
||||
return LEGACY_APP;
|
||||
}
|
||||
)
|
||||
.then((caps) => {
|
||||
current = caps;
|
||||
emit();
|
||||
return caps;
|
||||
});
|
||||
return loading;
|
||||
}
|
||||
|
||||
/** Whether the installed binary has a native feature, as far as it is known yet. */
|
||||
export function hasNativeFeature(feature: string): boolean {
|
||||
return current.features.includes(feature);
|
||||
}
|
||||
|
||||
export function nativeCapabilities(): NativeCapabilities {
|
||||
return current;
|
||||
}
|
||||
|
||||
/**
|
||||
* Compares the binary with the oldest one this server's UI works with. A
|
||||
* server that says nothing (older than the handshake) requires nothing.
|
||||
*/
|
||||
export async function checkAppUpdate(fetchFeatures: () => Promise<{ minNativeShellApi?: unknown }>): Promise<boolean> {
|
||||
if (!isNativeApp()) return false;
|
||||
const [caps, features] = await Promise.all([loadNativeCapabilities(), fetchFeatures().catch(() => ({}))]);
|
||||
const min = typeof features.minNativeShellApi === 'number' ? features.minNativeShellApi : 0;
|
||||
updateRequired = caps.shellApi < min;
|
||||
emit();
|
||||
return updateRequired;
|
||||
}
|
||||
|
||||
export function appUpdateRequired(): boolean {
|
||||
return updateRequired;
|
||||
}
|
||||
|
||||
function subscribe(listener: () => void): () => void {
|
||||
listeners.add(listener);
|
||||
return () => listeners.delete(listener);
|
||||
}
|
||||
|
||||
/** Re-renders when the capabilities arrive or the update check answers. */
|
||||
export function useNativeCapabilities(): { caps: NativeCapabilities; updateRequired: boolean } {
|
||||
const caps = useSyncExternalStore(subscribe, nativeCapabilities, nativeCapabilities);
|
||||
const required = useSyncExternalStore(subscribe, appUpdateRequired, appUpdateRequired);
|
||||
return { caps, updateRequired: required };
|
||||
}
|
||||
|
||||
/** Test helper: forget what was asked. */
|
||||
export function _resetNativeCapabilities(): void {
|
||||
current = WEB;
|
||||
updateRequired = false;
|
||||
loading = null;
|
||||
listeners.clear();
|
||||
}
|
||||
@@ -4,6 +4,7 @@ import { SplashScreen } from '@capacitor/splash-screen';
|
||||
import { StatusBar, Style } from '@capacitor/status-bar';
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
|
||||
import { isEffectivelyOffline } from '../sync/networkMode';
|
||||
import { checkAppUpdate } from './capabilities';
|
||||
import { startNativeApp } from './nativeApp';
|
||||
import { keepOfflineShellFresh } from './offlineShell';
|
||||
import { isNativeApp, isNativeIos } from './platform';
|
||||
@@ -15,6 +16,7 @@ vi.mock('@capacitor/status-bar', () => ({ StatusBar: { setStyle: vi.fn() }, Styl
|
||||
vi.mock('./platform', () => ({ isNativeApp: vi.fn(), isNativeIos: vi.fn() }));
|
||||
vi.mock('./offlineShell', () => ({ keepOfflineShellFresh: vi.fn() }));
|
||||
vi.mock('../sync/networkMode', () => ({ isEffectivelyOffline: vi.fn() }));
|
||||
vi.mock('./capabilities', () => ({ checkAppUpdate: vi.fn(async () => false) }));
|
||||
|
||||
function backButtonHandler(): (event: { canGoBack: boolean }) => void {
|
||||
const call = vi.mocked(App.addListener).mock.calls.find(([name]) => name === 'backButton');
|
||||
@@ -44,6 +46,11 @@ describe('startNativeApp', () => {
|
||||
expect(StatusBar.setStyle).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('asks the binary what it can do and the server which binary it needs', () => {
|
||||
startNativeApp();
|
||||
expect(checkAppUpdate).toHaveBeenCalledWith(expect.any(Function));
|
||||
});
|
||||
|
||||
it('hides the splash after the first frame', () => {
|
||||
startNativeApp();
|
||||
vi.runOnlyPendingTimers();
|
||||
|
||||
@@ -3,6 +3,7 @@ import { Keyboard } from '@capacitor/keyboard';
|
||||
import { SplashScreen } from '@capacitor/splash-screen';
|
||||
import { StatusBar, Style } from '@capacitor/status-bar';
|
||||
import { isEffectivelyOffline } from '../sync/networkMode';
|
||||
import { checkAppUpdate } from './capabilities';
|
||||
import { keepOfflineShellFresh } from './offlineShell';
|
||||
import { isNativeApp, isNativeIos } from './platform';
|
||||
import { reportNativeFailure } from './reportFailure';
|
||||
@@ -20,6 +21,9 @@ export function startNativeApp(): void {
|
||||
|
||||
followThemeInStatusBar();
|
||||
|
||||
// What this binary can do, and whether this server's UI needs a newer one.
|
||||
void checkAppUpdate(fetchServerFeatures);
|
||||
|
||||
// Android's back gesture: through the app's own history first, and only
|
||||
// then out of the app, the way a browser tab would behave.
|
||||
void App.addListener('backButton', ({ canGoBack }) => {
|
||||
@@ -58,3 +62,10 @@ function followThemeInStatusBar(): void {
|
||||
apply();
|
||||
new MutationObserver(apply).observe(root, { attributes: true, attributeFilter: ['class'] });
|
||||
}
|
||||
|
||||
/** The server's feature flags, bounded so a slow server cannot hold anything up. */
|
||||
async function fetchServerFeatures(): Promise<{ minNativeShellApi?: unknown }> {
|
||||
const res = await fetch('/api/health/features', { credentials: 'same-origin', signal: AbortSignal.timeout(8000) });
|
||||
if (!res.ok) return {};
|
||||
return (await res.json()) as { minNativeShellApi?: unknown };
|
||||
}
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import { registerPlugin } from '@capacitor/core';
|
||||
import type { NativeCapabilities } from './capabilities';
|
||||
|
||||
/**
|
||||
* The app's own native plugin, implemented in
|
||||
@@ -29,6 +30,8 @@ export interface TrekShellPlugin {
|
||||
refreshOfflineCopy(): Promise<{ saved: boolean }>;
|
||||
/** iOS: loads that copy under the server's origin. False when there is none. */
|
||||
openOfflineCopy(): Promise<{ opened: boolean }>;
|
||||
/** What this binary offers the UI (native/capabilities.ts). Missing before shell API 2. */
|
||||
getCapabilities(): Promise<NativeCapabilities>;
|
||||
}
|
||||
|
||||
export const TrekShell = registerPlugin<TrekShellPlugin>('TrekShell');
|
||||
|
||||
Reference in New Issue
Block a user