From f5f45784e281e2d4cee54938c32d82a8633cfd47 Mon Sep 17 00:00:00 2001 From: OrcaWin Date: Fri, 6 Nov 2026 23:07:50 -0800 Subject: [PATCH] test: remove 212 low-value mobile shell and routing tests (#39334) Co-authored-by: OrcaWin <293788423+OrcaWin@users.noreply.github.com> --- .../vitest-real-agent-cli-guard.test.ts | 6 - .../pr-editor-host-model-e2e-route.test.mjs | 20 - ...-editor-preview-e2e-source-routes.test.mjs | 17 - .../pr-rich-markdown-find-route.test.mjs | 21 - .../pr-wsl-move-fence-route.test.mjs | 24 - .../mobile-browser-frameless-stream.test.tsx | 226 --------- .../src/components/HostProtocolGate.test.ts | 137 ------ .../pr-sidebar/MobilePrTabSheets.test.tsx | 139 ------ mobile/src/device-store/device-store.test.ts | 67 --- .../android-release-signing-plugin.test.ts | 17 - .../MobileWebShellScreen.test.tsx | 460 +----------------- .../bridge-host-verdict-hold.test.ts | 11 - .../bridge/bridge-reply-chunking.test.ts | 276 +---------- .../bridge/page-device-store.test.ts | 53 -- .../host-area-two-hosts.test.tsx | 121 ----- .../mobile-web-shell-back-claim-state.test.ts | 24 - .../mobile-web-shell-page-route-wall.test.ts | 96 ---- ...-web-shell-refused-update-decision.test.ts | 154 ------ ...mobile-web-shell-safe-area-screen.test.tsx | 91 ---- .../mobile-web-shell-session-grants.test.ts | 107 ---- .../mobile-web-shell-session.test.ts | 369 +------------- ...le-web-shell-update-failure-record.test.ts | 228 --------- .../shell-failure-recovery.test.ts | 18 - .../shell-lifecycle-log.test.ts | 378 +------------- .../mobile-web-shell/shell-page-frame.test.ts | 44 -- .../use-mobile-web-shell-bridge.test.ts | 219 +-------- .../push-registration-cancellation.test.ts | 19 - .../platform/keyboard-occlusion.web.test.tsx | 346 ------------- .../text-input-selection-reveal.web.test.tsx | 78 --- mobile/src/query/host-query-errors.test.ts | 39 -- 30 files changed, 6 insertions(+), 3799 deletions(-) delete mode 100644 config/scripts/workflow/source-routing/pr-editor-host-model-e2e-route.test.mjs delete mode 100644 config/scripts/workflow/source-routing/pr-editor-preview-e2e-source-routes.test.mjs delete mode 100644 config/scripts/workflow/source-routing/pr-rich-markdown-find-route.test.mjs delete mode 100644 config/scripts/workflow/source-routing/pr-wsl-move-fence-route.test.mjs delete mode 100644 mobile/src/browser/mobile-browser-frameless-stream.test.tsx delete mode 100644 mobile/src/components/pr-sidebar/MobilePrTabSheets.test.tsx delete mode 100644 mobile/src/mobile-web-shell/bridge/page-device-store.test.ts delete mode 100644 mobile/src/mobile-web-shell/host-area-two-hosts.test.tsx delete mode 100644 mobile/src/mobile-web-shell/mobile-web-shell-page-route-wall.test.ts delete mode 100644 mobile/src/mobile-web-shell/mobile-web-shell-safe-area-screen.test.tsx delete mode 100644 mobile/src/mobile-web-shell/mobile-web-shell-session-grants.test.ts delete mode 100644 mobile/src/mobile-web-shell/mobile-web-shell-update-failure-record.test.ts delete mode 100644 mobile/src/mobile-web-shell/shell-page-frame.test.ts delete mode 100644 mobile/src/platform/keyboard-occlusion.web.test.tsx delete mode 100644 mobile/src/platform/text-input-selection-reveal.web.test.tsx delete mode 100644 mobile/src/query/host-query-errors.test.ts diff --git a/config/scripts/test-runtime/environment/vitest-real-agent-cli-guard.test.ts b/config/scripts/test-runtime/environment/vitest-real-agent-cli-guard.test.ts index 8a06f5e35f2..54399412c53 100644 --- a/config/scripts/test-runtime/environment/vitest-real-agent-cli-guard.test.ts +++ b/config/scripts/test-runtime/environment/vitest-real-agent-cli-guard.test.ts @@ -7,12 +7,6 @@ afterEach(() => { }) describe.skipIf(!globalThis.orcaRealAgentCliGuard)('vitest real-agent-cli guard', () => { - it('blocks version discovery without treating an absent agent as a test failure', () => { - const result = spawnSync('claude', ['--version'], { encoding: 'utf8', env: process.env }) - expect(result.status).toBe(127) - expect(takeRealAgentCliCalls()).toEqual([]) - }) - it('blocks and records an agent CLI resolved from the inherited PATH', () => { const result = spawnSync('claude', ['-p', 'hello'], { encoding: 'utf8', env: process.env }) expect(result.status).toBe(127) diff --git a/config/scripts/workflow/source-routing/pr-editor-host-model-e2e-route.test.mjs b/config/scripts/workflow/source-routing/pr-editor-host-model-e2e-route.test.mjs deleted file mode 100644 index ce279521c96..00000000000 --- a/config/scripts/workflow/source-routing/pr-editor-host-model-e2e-route.test.mjs +++ /dev/null @@ -1,20 +0,0 @@ -import { describe, expect, it } from 'vitest' -import { selectPrE2eSpecs } from './pr-e2e-source-routing.mjs' - -describe('editor host model identity E2E routing', () => { - const spec = 'tests/e2e/editor-model-host-isolation.spec.ts' - it.each([ - 'src/renderer/src/components/editor/model-lifetime/identity/editor-model-uri.ts', - 'src/renderer/src/components/editor/useEditorPanelFileContentLoader.ts', - 'src/renderer/src/lib/editor-file-operation-provenance.ts' - ])('routes %s', (path) => { - expect(selectPrE2eSpecs([path])).toContain(spec) - }) - it('does not route unit tests of those sources', () => { - expect( - selectPrE2eSpecs([ - 'src/renderer/src/components/editor/model-lifetime/identity/editor-model-uri.test.ts' - ]) - ).not.toContain(spec) - }) -}) diff --git a/config/scripts/workflow/source-routing/pr-editor-preview-e2e-source-routes.test.mjs b/config/scripts/workflow/source-routing/pr-editor-preview-e2e-source-routes.test.mjs deleted file mode 100644 index 5ef2accff58..00000000000 --- a/config/scripts/workflow/source-routing/pr-editor-preview-e2e-source-routes.test.mjs +++ /dev/null @@ -1,17 +0,0 @@ -import { describe, expect, it } from 'vitest' -import { selectPrE2eSpecs } from './pr-e2e-source-routing.mjs' - -describe('CSV preview E2E routing', () => { - it('routes CSV viewer sources, not their unit tests, to the CSV specs', () => { - expect(selectPrE2eSpecs(['src/renderer/src/components/editor/csv/CsvCellValue.tsx'])).toEqual( - expect.arrayContaining([ - 'tests/e2e/csv-paged-preview.spec.ts', - 'tests/e2e/csv-table-editing.spec.ts', - 'tests/e2e/csv-url-links.spec.ts' - ]) - ) - expect( - selectPrE2eSpecs(['src/renderer/src/components/editor/csv/csv-parse.test.ts']) - ).not.toContain('tests/e2e/csv-url-links.spec.ts') - }) -}) diff --git a/config/scripts/workflow/source-routing/pr-rich-markdown-find-route.test.mjs b/config/scripts/workflow/source-routing/pr-rich-markdown-find-route.test.mjs deleted file mode 100644 index 380df26c932..00000000000 --- a/config/scripts/workflow/source-routing/pr-rich-markdown-find-route.test.mjs +++ /dev/null @@ -1,21 +0,0 @@ -import { describe, expect, it } from 'vitest' -import { selectPrE2eSpecs } from './pr-e2e-source-routing.mjs' - -describe('rich Markdown Find routing', () => { - const spec = 'tests/e2e/markdown-find-adversarial.spec.ts' - - it.each([ - 'src/renderer/src/components/editor/rich-markdown/search/rich-markdown-search-focus.ts', - 'src/renderer/src/components/editor/rich-markdown/search/RichMarkdownSearchBar.tsx', - 'src/renderer/src/components/editor/rich-markdown/instance/RichMarkdownEditorSurface.tsx' - ])('routes %s', (file) => { - expect(selectPrE2eSpecs([file])).toContain(spec) - }) - - it.each([ - 'src/renderer/src/components/editor/rich-markdown/search/rich-markdown-search-focus.test.ts', - 'src/renderer/src/components/editor/rich-markdown/instance/RichMarkdownEditor.tsx' - ])('does not route %s', (file) => { - expect(selectPrE2eSpecs([file])).not.toContain(spec) - }) -}) diff --git a/config/scripts/workflow/source-routing/pr-wsl-move-fence-route.test.mjs b/config/scripts/workflow/source-routing/pr-wsl-move-fence-route.test.mjs deleted file mode 100644 index 865f6778cdf..00000000000 --- a/config/scripts/workflow/source-routing/pr-wsl-move-fence-route.test.mjs +++ /dev/null @@ -1,24 +0,0 @@ -import { describe, expect, it } from 'vitest' -import { selectPrE2eSpecs } from './pr-e2e-source-routing.mjs' - -describe('WSL move fence routing', () => { - const spec = 'tests/e2e/wsl-move-fence.spec.ts' - - it.each([ - 'src/main/persistence/moving-wsl-projects/wsl-move-reset.ts', - 'src/main/persistence/moving-wsl-projects/wsl-move-scope-guard.ts', - 'src/main/ipc/pty/host-env/spawn-cwd.ts', - 'src/main/wsl/host-lifecycle/wsl-host-gate.ts', - 'src/shared/wsl-move/wsl-move-cutover.ts' - ])('routes %s', (file) => { - expect(selectPrE2eSpecs([file])).toContain(spec) - }) - - it.each([ - 'src/main/persistence/moving-wsl-projects/wsl-move-reset.test.ts', - 'src/main/persistence/moving-wsl-projects/wsl-move-driver.ts', - 'src/shared/wsl-move/wsl-move-cutover-extra.ts' - ])('does not route %s', (file) => { - expect(selectPrE2eSpecs([file])).not.toContain(spec) - }) -}) diff --git a/mobile/src/browser/mobile-browser-frameless-stream.test.tsx b/mobile/src/browser/mobile-browser-frameless-stream.test.tsx deleted file mode 100644 index 44ed835ea0e..00000000000 --- a/mobile/src/browser/mobile-browser-frameless-stream.test.tsx +++ /dev/null @@ -1,226 +0,0 @@ -import { Buffer } from 'buffer' -import { createElement } from 'react' -import { act, create, type ReactTestRenderer } from 'react-test-renderer' -import { describe, expect, it, vi } from 'vitest' -import { - BrowserScreencastOpcode, - type BrowserScreencastFrame -} from '../transport/browser-screencast-protocol' -import type { RpcClient } from '../transport/rpc-client' -import { MobileBrowserPane, type MobileBrowserTab } from './MobileBrowserPane' -import { useBrowserBinaryScreencastGrant } from './use-browser-binary-screencast-grant' -import { findAllByHostType } from '../test-support/react-test-renderer-host-nodes' - -// Mock binary-lane negotiation: native always supports it, but older shells may have no encoder behind requested lane (ruling 5). -vi.mock('./use-browser-binary-screencast-grant', () => ({ - useBrowserBinaryScreencastGrant: vi.fn(() => true) -})) - -vi.mock('./MobileBrowserLoadProgress', () => ({ MobileBrowserLoadProgress: () => null })) - -vi.mock('react-native', () => ({ - ActivityIndicator: 'ActivityIndicator', - AppState: { currentState: 'active', addEventListener: () => ({ remove: () => {} }) }, - Image: 'Image', - PanResponder: { create: () => ({ panHandlers: {} }) }, - PixelRatio: { get: () => 2 }, - Platform: { OS: 'android' }, - Pressable: 'Pressable', - StyleSheet: { - absoluteFillObject: { position: 'absolute', top: 0, left: 0, right: 0, bottom: 0 }, - create: (styles: unknown) => styles - }, - Text: 'Text', - TextInput: 'TextInput', - View: 'View' -})) - -// Mock transitive icons too: Vitest throws on first unmocked export, including view-mode switch. -vi.mock('lucide-react-native', () => ({ - ArrowUp: 'ArrowUp', - ChevronLeft: 'ChevronLeft', - ChevronRight: 'ChevronRight', - Monitor: 'Monitor', - RefreshCw: 'RefreshCw', - Smartphone: 'Smartphone' -})) - -type Subscription = { - listener: (payload: unknown) => void - onBinaryFrame?: (frame: BrowserScreencastFrame) => void -} - -let pageCounter = 0 - -function makeFrame(): BrowserScreencastFrame { - return { - opcode: BrowserScreencastOpcode.Frame, - seq: 1, - format: 'jpeg', - metadata: { deviceWidth: 360, deviceHeight: 640, pageScaleFactor: 1 }, - image: new TextEncoder().encode('frame') - } -} - -function spinnerCount(renderer: ReactTestRenderer): number { - return findAllByHostType(renderer.root, 'ActivityIndicator').length -} - -async function renderPane(): Promise<{ - renderer: ReactTestRenderer - stream: Subscription | undefined - subscriptions: Subscription[] - sendRequest: ReturnType -}> { - pageCounter += 1 - const subscriptions: Subscription[] = [] - const sendRequest = vi.fn().mockResolvedValue({}) - const client: RpcClient = { - sendRequest, - subscribe: (_method, _params, listener, options) => { - subscriptions.push({ listener, onBinaryFrame: options?.onBinaryFrame }) - return () => {} - }, - updateTerminalSubscriptionViewport: vi.fn(), - getState: () => 'connected', - getReconnectAttempt: () => 0, - getLastConnectedAt: () => null, - onStateChange: () => () => {}, - notifyForeground: vi.fn(), - close: vi.fn() - } - - const tab: MobileBrowserTab = { - type: 'browser', - id: `tab-${pageCounter}`, - title: 'Dashboard', - browserWorkspaceId: 'bw-1', - browserPageId: `page-${pageCounter}`, - url: 'https://dashboard.example', - loading: false, - canGoBack: false, - canGoForward: false, - isActive: true - } - - const rendered: { renderer?: ReactTestRenderer } = {} - await act(async () => { - rendered.renderer = create( - createElement(MobileBrowserPane, { - client, - // Why: unique worktree id keeps each test on a cold module-level frame cache. - worktreeId: `wt-${pageCounter}`, - tab, - screencastSupported: true, - keyboardLift: 0, - bottomInset: 0, - onToast: () => {} - }), - { createNodeMock: () => ({ setNativeProps: () => {} }) } - ) - await Promise.resolve() - }) - const mounted = rendered.renderer - if (!mounted) { - throw new Error('MobileBrowserPane did not mount') - } - const viewport = findAllByHostType(mounted.root, 'View').find( - (node) => typeof node.props.onLayout === 'function' - ) - if (!viewport) { - throw new Error('Viewport with onLayout not found') - } - act(() => { - viewport.props.onLayout({ nativeEvent: { layout: { width: 360, height: 640 } } }) - }) - return { renderer: mounted, stream: subscriptions[0], subscriptions, sendRequest } -} - -async function renderStreamingPane(): Promise<{ - renderer: ReactTestRenderer - stream: Subscription - sendRequest: ReturnType -}> { - const { renderer, stream, sendRequest } = await renderPane() - if (!stream) { - throw new Error('browser.screencast subscription not created') - } - return { renderer, stream, sendRequest } -} - -function errorMessages(renderer: ReactTestRenderer): string[] { - return findAllByHostType(renderer.root, 'Text').flatMap((node) => - typeof node.props.children === 'string' ? [node.props.children] : [] - ) -} - -describe('MobileBrowserPane with a stream that reports ready but sends no frames', () => { - // Ready without frames must retain indicator instead of unexplained blank pane. - it('keeps showing the loading indicator instead of an empty black pane', async () => { - const { renderer, stream } = await renderStreamingPane() - - act(() => { - stream.listener({ type: 'ready', tab: { url: 'https://dashboard.example' } }) - }) - - expect(spinnerCount(renderer)).toBeGreaterThan(0) - }) - - it('clears the indicator once real pixels arrive', async () => { - const { renderer, stream } = await renderStreamingPane() - - act(() => { - stream.listener({ type: 'ready', tab: { url: 'https://dashboard.example' } }) - }) - act(() => { - stream.onBinaryFrame?.(makeFrame()) - }) - - expect(spinnerCount(renderer)).toBe(0) - expect(errorMessages(renderer)).not.toContain( - 'Update the Orca app to stream browser tabs here.' - ) - const source = findAllByHostType(renderer.root, 'Image') - .map((image) => (image.props.source as { uri?: string } | null)?.uri) - .find((uri) => typeof uri === 'string') - expect(source).toContain(Buffer.from(makeFrame().image).toString('base64')) - }) -}) - -describe('MobileBrowserPane against a shell with no binary screencast lane', () => { - // Grant is negotiation: subscribing without encoder yields no frames until startup timeout (ruling 5). - it('never subscribes, and says so with the stream-error state it already has', async () => { - vi.mocked(useBrowserBinaryScreencastGrant).mockReturnValue(false) - try { - const { renderer, subscriptions } = await renderPane() - - expect(subscriptions).toEqual([]) - expect(errorMessages(renderer)).toContain('Update the Orca app to stream browser tabs here.') - } finally { - vi.mocked(useBrowserBinaryScreencastGrant).mockReturnValue(true) - } - }) -}) - -describe('MobileBrowserPane frame acks', () => { - // Old hosts strip the opt-in and would refuse the unknown ack method. - it('acks received frames only after ready echoes frameAck', async () => { - const legacy = await renderStreamingPane() - act(() => { - legacy.stream.listener({ type: 'ready', subscriptionId: 'sub-legacy', tab: {} }) - legacy.stream.onBinaryFrame?.(makeFrame()) - }) - expect(legacy.sendRequest).not.toHaveBeenCalled() - - const credited = await renderStreamingPane() - act(() => { - credited.stream.listener({ type: 'ready', subscriptionId: 'sub-1', frameAck: true, tab: {} }) - credited.stream.onBinaryFrame?.(makeFrame()) - }) - expect(credited.sendRequest).toHaveBeenCalledWith('browser.screencast.ack', { - worktree: `id:wt-${pageCounter}`, - subscriptionId: 'sub-1', - seq: 1 - }) - }) -}) diff --git a/mobile/src/components/HostProtocolGate.test.ts b/mobile/src/components/HostProtocolGate.test.ts index c94e367ecee..afa5294dfff 100644 --- a/mobile/src/components/HostProtocolGate.test.ts +++ b/mobile/src/components/HostProtocolGate.test.ts @@ -53,10 +53,6 @@ vi.mock('../transport/host-descriptor-recorder', () => ({ recordHostDescriptorFromStatus: vi.fn() })) -function clientWithStatus(result: Record): RpcClient { - return { sendRequest: vi.fn().mockResolvedValue({ ok: true, result }) } as unknown as RpcClient -} - function GateConsumer() { const { hostCapabilities } = useHostProtocolGates() return createElement('GateStatus', null, hostCapabilities.join(',')) @@ -114,78 +110,6 @@ describe('HostProtocolGate', () => { vi.restoreAllMocks() }) - it('replaces the host UI with the block screen when mobile is too old', async () => { - // Why: blocked warns to console; keep test output clean without hiding other errors. - vi.spyOn(console, 'warn').mockImplementation(() => {}) - hostClient.current = { - client: clientWithStatus({ protocolVersion: 5, minCompatibleMobileVersion: 999 }), - state: 'connected' - } - renderer = await renderGate() - const output = renderedText(renderer) - expect(output).toContain('Update Orca Mobile') - expect(output).toContain('Open App Store') - expect(output).not.toContain('HostContent') - }) - - it('routes Android mobile updates to GitHub Releases', async () => { - vi.spyOn(console, 'warn').mockImplementation(() => {}) - nativeTestState.platform.OS = 'android' - hostClient.current = { - client: clientWithStatus({ protocolVersion: 5, minCompatibleMobileVersion: 999 }), - state: 'connected' - } - renderer = await renderGate() - const output = renderedText(renderer) - expect(output).toContain('Update Orca Mobile') - expect(output).toContain('Update Orca Mobile from GitHub Releases') - expect(output).toContain('Open GitHub Releases') - expect(output).not.toContain('mobile app store') - expect(output).not.toContain('HostContent') - const [openReleases] = findAllByHostType(renderer.root, 'Pressable') - act(() => openReleases?.props.onPress()) - expect(nativeTestState.openUrl).toHaveBeenCalledWith( - 'https://github.com/stablyai/orca/releases' - ) - }) - - it('replaces the host UI with the block screen when desktop is too old', async () => { - vi.spyOn(console, 'warn').mockImplementation(() => {}) - hostClient.current = { - client: clientWithStatus({ protocolVersion: 0, minCompatibleMobileVersion: 0 }), - state: 'connected' - } - renderer = await renderGate() - const output = renderedText(renderer) - expect(output).toContain('Update Orca on your computer') - expect(output).toContain('Open GitHub Releases') - expect(output).not.toContain('HostContent') - }) - - it('renders the host UI when the verdict is ok', async () => { - const client = clientWithStatus({ - protocolVersion: 5, - minCompatibleMobileVersion: 0, - capabilities: ['browser.screencast.v1'] - }) - hostClient.current = { - client, - state: 'connected' - } - renderer = await renderGate() - const output = renderedText(renderer) - expect(output).toContain('HostContent') - expect(output).toContain('browser.screencast.v1') - expect(output).not.toContain('Update Orca') - expect(client.sendRequest).toHaveBeenCalledOnce() - }) - - it('renders the host UI while the host connection is still pending', async () => { - hostClient.current = { client: null, state: 'connecting' } - renderer = await renderGate() - expect(renderedText(renderer)).toContain('HostContent') - }) - it('does not mount host routes before a connected host passes the compatibility probe', async () => { const client = { sendRequest: vi.fn().mockReturnValue(new Promise(() => {})) @@ -249,65 +173,4 @@ describe('HostProtocolGate', () => { ) expect(overlay?.props.pointerEvents).toBe('auto') }) - - it('still replaces mounted routes when the verdict comes back blocked', async () => { - vi.spyOn(console, 'warn').mockImplementation(() => {}) - hostClient.current = { client: null, state: 'connecting' } - renderer = await renderGate() - expect(renderedText(renderer)).toContain('HostContent') - - await act(async () => { - hostClient.current = { - client: clientWithStatus({ protocolVersion: 5, minCompatibleMobileVersion: 999 }), - state: 'connected' - } - renderer?.update(gateElement()) - await Promise.resolve() - }) - - const output = renderedText(renderer) - expect(output).toContain('Update Orca Mobile') - expect(output).not.toContain('HostContent') - }) - - it('keeps an already-validated host route mounted while reconnect status is pending', async () => { - const client = { - sendRequest: vi - .fn() - .mockResolvedValueOnce({ - ok: true, - result: { protocolVersion: 5, minCompatibleMobileVersion: 0 } - }) - .mockReturnValueOnce(new Promise(() => {})) - } as unknown as RpcClient - hostClient.current = { client, state: 'connected' } - renderer = await renderGate() - - await act(async () => { - hostClient.current = { client, state: 'disconnected' } - renderer?.update(gateElement()) - }) - await act(async () => { - hostClient.current = { client, state: 'connected' } - renderer?.update(gateElement()) - await Promise.resolve() - }) - - const output = renderedText(renderer) - expect(output).toContain('HostContent') - // Why: the host already answered once, so a reconnect probe must not dim the UI it validated. - expect(output).not.toContain('Checking host compatibility') - expect(client.sendRequest).toHaveBeenCalledTimes(2) - }) - - it('fails open when a connected host cannot answer the status probe', async () => { - hostClient.current = { - client: { - sendRequest: vi.fn().mockResolvedValue({ ok: false, error: { message: 'unavailable' } }) - } as unknown as RpcClient, - state: 'connected' - } - renderer = await renderGate() - expect(renderedText(renderer)).toContain('HostContent') - }) }) diff --git a/mobile/src/components/pr-sidebar/MobilePrTabSheets.test.tsx b/mobile/src/components/pr-sidebar/MobilePrTabSheets.test.tsx deleted file mode 100644 index 92578953038..00000000000 --- a/mobile/src/components/pr-sidebar/MobilePrTabSheets.test.tsx +++ /dev/null @@ -1,139 +0,0 @@ -// @vitest-environment happy-dom -import React, { act } from 'react' -import { createRoot, type Root } from 'react-dom/client' -import { afterEach, expect, it, vi } from 'vitest' -import { MobilePrTabSheets } from './MobilePrTabSheets' -import type { MobilePrTab, PrTabSheetRequest } from './use-mobile-pr-tab' - -type Field = { value: string; onChangeText: (value: string) => void } -const io = vi.hoisted(() => ({ - load: vi.fn(), - fields: new Map() -})) -vi.mock('react-native', () => ({ - StyleSheet: { create: (styles: T) => styles, hairlineWidth: 1 }, - View: ({ children }: React.PropsWithChildren) =>
{children}
, - Text: ({ children }: React.PropsWithChildren) => {children}, - ActivityIndicator: () => , - Pressable: ({ children }: React.PropsWithChildren) =>
{children}
-})) -vi.mock('lucide-react-native', () => ({ - ChevronsUpDown: () => null, - GitMerge: () => null, - Sparkles: () => null -})) -// The drawer finishes its hide at once, so a closed sheet unmounts as it does on the phone. -vi.mock('../bottom-drawer/mounted-bottom-drawer', async () => { - const { useLayoutEffect } = await import('react') - return { - MountedBottomDrawer: ({ - visible, - children, - onHidden - }: React.PropsWithChildren<{ visible: boolean; onHidden: () => void }>) => { - useLayoutEffect(() => { - if (!visible) { - onHidden() - } - }, [visible, onHidden]) - return
{children}
- } - } -}) -vi.mock('../composer-input/FieldTextInput', () => ({ - FieldTextInput: (props: Field & { accessibilityLabel?: string }) => { - io.fields.set(props.accessibilityLabel ?? '', props) - return null - } -})) -vi.mock('../nav-bar/SheetHeader', () => ({ SheetHeader: () => null })) -vi.mock('../SheetPrimaryButton', () => ({ SheetPrimaryButton: () => null })) -vi.mock('../list/ListGroup', () => ({ ListGroup: () => null, ListRow: () => null })) -vi.mock('../MobileSwitch', () => ({ MobileSwitch: () => null })) -vi.mock('../ConfirmModal', () => ({ ConfirmModal: () => null })) -vi.mock('./PrReviewersSheet', () => ({ PrReviewersSheet: () => null })) -vi.mock('./PrBasePicker', () => ({ PrBasePicker: () => null })) -vi.mock('../../source-control/MobileCommitFailurePanel', () => ({ - MobileCommitFailurePanel: () => null -})) -vi.mock('../../source-control/use-mobile-commit-failure-recovery', () => ({ - useMobileCommitFailureRecovery: () => ({}) -})) -vi.mock('../../source-control/mobile-pr-create-draft', () => ({ - loadMobilePrCreateDraft: io.load, - generateMobilePrFields: vi.fn(), - cancelMobilePrFields: vi.fn() -})) -vi.mock('expo-router', () => ({ useFocusEffect: () => {} })) -vi.mock('../../theme/use-mobile-color-scheme', () => ({ useMobileColorScheme: () => 'dark' })) -vi.mock('../../i18n/use-mobile-translation', () => ({ - useMobileTranslation: () => (_key: string, fallback: string) => fallback -})) - -let root: Root | null = null -afterEach(() => { - act(() => root?.unmount()) - root = null - io.fields.clear() - io.load.mockReset() -}) - -function seed(title: string) { - return { prefill: { provider: 'github' }, title, body: '', base: 'main' } -} - -function render(gitBranch: string, sheetRequest: PrTabSheetRequest | null) { - // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: carries every MobilePrTab member the sheets and Create read. - const tab = { - client: {}, - worktreeId: 'wt-1', - gitBranch, - gitStatus: null, - commitsAhead: 2, - creatingPr: false, - setCreatingPr: () => {}, - state: { kind: 'none' }, - confirm: null, - sheetRequest, - sheetInScope: () => true, - closeSheet: () => {}, - onSheetAfterClose: () => {} - } as unknown as MobilePrTab - act(() => root!.render()) -} - -function createRequest(id: number): PrTabSheetRequest { - return { - kind: 'createPr', - scope: { client: null, worktreeId: 'wt-1', branch: 'feature/a', resource: null }, - id - } -} - -async function settle() { - await act(async () => {}) -} - -it('reopens Create PR on the same branch with the typed title, and seeds another branch from its commits', async () => { - root = createRoot(document.createElement('div')) - io.load.mockImplementation(async (_client: unknown, _wt: string, input: { branch: string }) => - seed(input.branch === 'feature/a' ? 'Seeded from a' : 'Seeded from b') - ) - render('feature/a', createRequest(1)) - await settle() - act(() => io.fields.get('Title')!.onChangeText('My typed title')) - - render('feature/a', null) - io.fields.clear() - render('feature/a', createRequest(2)) - await settle() - - expect(io.fields.get('Title')!.value).toBe('My typed title') - - render('feature/a', null) - io.fields.clear() - render('feature/b', createRequest(3)) - await settle() - - expect(io.fields.get('Title')!.value).toBe('Seeded from b') -}) diff --git a/mobile/src/device-store/device-store.test.ts b/mobile/src/device-store/device-store.test.ts index 86ea388debc..4c7cb059883 100644 --- a/mobile/src/device-store/device-store.test.ts +++ b/mobile/src/device-store/device-store.test.ts @@ -1,4 +1,3 @@ -import { randomBytes } from 'node:crypto' import { describe, expect, it, vi } from 'vitest' vi.mock('expo-file-system', () => ({ Directory: class {}, File: class {}, Paths: {} })) @@ -14,7 +13,6 @@ import { FAKE_GENERATION_ROOT, type FakeGenerationFileSystem } from '../mobile-web-shell/generation-file-system-fake' -import { deriveHostCacheKey } from '../mobile-web-shell/host-cache-key' import { createDeviceStore, type DeviceStoreOptions } from './device-store' import { deviceStoreRows } from './device-store-files' import type { DeviceStoreKeychain } from './device-store-key' @@ -54,71 +52,6 @@ const rowUri = (hostId: string, table: 'cache' | 'draft', key: string): string = deviceStoreRows(ROOTS, hostId, table, [key])[0]!.uri describe('device store', () => { - it('evicts least-recently-used cache rows past the cap across a relaunch and never touches drafts', async () => { - vi.useFakeTimers({ toFake: ['Date'] }) - const fileSystem = createFakeGenerationFileSystem() - const keychain = memoryKeychain() - const firstLaunch = storeOn(fileSystem, { keychain }) - await firstLaunch.runLaunchMaintenance() - for (let draft = 0; draft < 3; draft += 1) { - await firstLaunch.write('host-a', 'draft', [ - { key: `draft-${draft}`, value: base64('typed') } - ]) - } - // 512 KiB encoded seals to 393,244 bytes, so the 342nd row crosses 128 MiB and eviction keeps 307. - const value = randomBytes(393_216).toString('base64') - const writeRow = async (target: typeof firstLaunch, row: number) => { - vi.setSystemTime(1_000_000 + row) - expect(await target.write('host-a', 'cache', [{ key: `row-${row}`, value }])).toEqual({ - written: true - }) - } - for (let row = 0; row < 300; row += 1) { - await writeRow(firstLaunch, row) - } - // The next launch learns the first 300 rows only from its seed. - const store = storeOn(fileSystem, { keychain }) - await store.runLaunchMaintenance() - for (let row = 300; row < 350; row += 1) { - await writeRow(store, row) - } - vi.useRealTimers() - const cache = await store.read('host-a', 'cache', ['row-0', 'row-34', 'row-35', 'row-349']) - expect(cache.status === 'ok' && cache.values.map((v) => v !== null)).toEqual([ - false, - false, - true, - true - ]) - expect(await store.read('host-a', 'draft', ['draft-0', 'draft-1', 'draft-2'])).toEqual({ - status: 'ok', - values: [base64('typed'), base64('typed'), base64('typed')] - }) - }) - - it('leaves no file of a removed host, whether wiped directly or swept at the next launch', async () => { - const fileSystem = createFakeGenerationFileSystem() - const keychain = memoryKeychain() - const store = storeOn(fileSystem, { keychain }) - for (const hostId of ['host-a', 'host-b', 'host-c']) { - await store.write(hostId, 'cache', [{ key: 'hosts', value: base64(hostId) }]) - await store.write(hostId, 'draft', [{ key: 'draft', value: base64(hostId) }]) - } - await store.wipeHost('host-a') - const hostPaths = (hostId: string) => - fileSystem.paths().filter((path) => path.includes(deriveHostCacheKey(hostId))) - expect(hostPaths('host-a')).toEqual([]) - - // Relaunch with host-c missing from the stored host list. - const relaunched = storeOn(fileSystem, { keychain }) - await relaunched.runLaunchMaintenance() - expect(hostPaths('host-c')).toEqual([]) - expect(await relaunched.read('host-b', 'draft', ['draft'])).toEqual({ - status: 'ok', - values: [base64('host-b')] - }) - }) - it('wipes and remints when the key is gone but files remain', async () => { const fileSystem = createFakeGenerationFileSystem() await storeOn(fileSystem).write('host-a', 'draft', [{ key: 'draft', value: base64('x') }]) diff --git a/mobile/src/mobile-release/android-release-signing-plugin.test.ts b/mobile/src/mobile-release/android-release-signing-plugin.test.ts index 6cf419cf9db..96265299b9b 100644 --- a/mobile/src/mobile-release/android-release-signing-plugin.test.ts +++ b/mobile/src/mobile-release/android-release-signing-plugin.test.ts @@ -32,23 +32,6 @@ const TEMPLATE = `android { ` describe('android-release-signing plugin', () => { - it('signs release builds through the env-driven release config', () => { - const patched = patchAppBuildGradle(TEMPLATE) - - expect(patched).toContain('storeFile file(orcaKeystorePath)') - expect(patched).toContain('enableV3Signing = true') - expect(patched).toContain('signingConfig orcaReleaseSigningConfig(signingConfigs)') - expect(patched).toContain("System.getenv('ORCA_ANDROID_REQUIRE_RELEASE_SIGNING') == 'true'") - // Debug builds keep the debug key; only the release build type changes. - expect(patched.match(/signingConfig signingConfigs\.debug/g)).toHaveLength(1) - expect(patched).not.toMatch(/storePassword '(?!android')/) - }) - - it('is idempotent across repeated prebuilds', () => { - const once = patchAppBuildGradle(TEMPLATE) - expect(patchAppBuildGradle(once)).toBe(once) - }) - it('fails prebuild when the template no longer matches', () => { const changed = TEMPLATE.replace( /(release \{[\s\S]*?)signingConfig signingConfigs\.debug/, diff --git a/mobile/src/mobile-web-shell/MobileWebShellScreen.test.tsx b/mobile/src/mobile-web-shell/MobileWebShellScreen.test.tsx index 06cf54846f2..875aa9c9261 100644 --- a/mobile/src/mobile-web-shell/MobileWebShellScreen.test.tsx +++ b/mobile/src/mobile-web-shell/MobileWebShellScreen.test.tsx @@ -24,444 +24,26 @@ vi.mock('../app-update/use-wall-app-update', mocks['../app-update/use-wall-app-u vi.mock('../transport/host-client-hooks', mocks['../transport/host-client-hooks']) vi.mock('./use-page-host-snapshot', mocks['./use-page-host-snapshot']) vi.mock('./use-mobile-web-shell-session', mocks['./use-mobile-web-shell-session']) - -import { createElement } from 'react' -import { act, create } from 'react-test-renderer' -import { bridgeId, clientFrame, createFakeRpcClient } from './bridge-host-test-fakes' +import { act } from 'react-test-renderer' import { byName, - trackRenderedScreen, - SCREEN_BUILD_ID as BUILD_ID, - SCREEN_DIRECTORY as DIRECTORY, readyState, renderScreen as mountScreen, - textOf, - updateScreen as reRenderScreen + textOf } from './mobile-web-shell-screen-test-harness' -import { BRIDGE_BACK_CLAIM_NOTIFY } from './bridge/bridge-page-back' -import { BRIDGE_PAGE_PAINTED } from './bridge/bridge-page-painted' -import { - BRIDGE_FAULT_GRANT, - BRIDGE_NAVIGATE_BACK_NOTIFY, - readBridgeHostMessage -} from './bridge/bridge-envelope' import { MobileWebShellScreen } from './MobileWebShellScreen' import type { MobileWebShellSessionState } from './mobile-web-shell-session-contract' import type { ReactTestInstance, ReactTestRenderer } from 'react-test-renderer' -const fetching = (receivedBytes: number, totalBytes: number): MobileWebShellSessionState => ({ - kind: 'fetching', - completedAssets: 0, - totalAssets: 128, - receivedBytes, - totalBytes -}) - -function fillScaleOf(tree: ReactTestRenderer): unknown { - return fillOf(tree).value -} - -function fillOf(tree: ReactTestRenderer): { readonly value: unknown } { - const bar = tree.root.find( - (node) => node.props.testID === 'mobile-web-shell-progress-bar' && String(node.type) === 'View' - ) - const [fill] = bar.findAll((node) => String(node.type) === 'Animated.View') - return fill.props.style[1].transform[0].scaleX -} - const renderScreen = (state: MobileWebShellSessionState): Promise => mountScreen(MobileWebShellScreen, dependencies, state) -const updateScreen = (tree: ReactTestRenderer, state: MobileWebShellSessionState): Promise => - reRenderScreen(MobileWebShellScreen, dependencies, tree, state) - afterEach(harness.unmountRenderedScreens) beforeEach(() => { harness.resetScreenDependencies(dependencies) }) -describe('the hybrid shell screen', () => { - it('moves the fill with the download feed, without a render to carry it', async () => { - const tree = await renderScreen(fetching(2_020_592, 8_082_368)) - expect(fillScaleOf(tree)).toBe(0.25) - dependencies.downloadProgress.publish(0.5) - expect(fillScaleOf(tree)).toBe(0.5) - expect(textOf(tree)).toContain('2.0 of 8.1 MB') - }) - - it('starts one ease per window toward the latest value, and lands full at once', async () => { - const tree = await renderScreen(fetching(0, 8_082_368)) - vi.useFakeTimers({ toFake: ['setTimeout', 'clearTimeout', 'Date'] }) - try { - dependencies.downloadProgress.publish(0.1) - dependencies.downloadProgress.publish(0.2) - dependencies.downloadProgress.publish(0.3) - expect(fillScaleOf(tree)).toBe(0.1) - vi.advanceTimersByTime(50) - expect(fillScaleOf(tree)).toBe(0.3) - dependencies.downloadProgress.publish(0.4) - dependencies.downloadProgress.publish(1) - expect(fillScaleOf(tree)).toBe(1) - } finally { - vi.useRealTimers() - } - }) - - it('starts nothing after unmount for a value still waiting on its window', async () => { - const tree = await renderScreen(fetching(0, 8_082_368)) - vi.useFakeTimers({ toFake: ['setTimeout', 'clearTimeout', 'Date'] }) - try { - dependencies.downloadProgress.publish(0.1) - dependencies.downloadProgress.publish(0.5) - const fill = fillOf(tree) - act(() => tree.unmount()) - vi.advanceTimersByTime(50) - expect(fill.value).toBe(0.1) - } finally { - vi.useRealTimers() - } - }) - - it('delivers an init through the ready view bridge', async () => { - dependencies.client = createFakeRpcClient() - const tree = await renderScreen(readyState('session-one')) - const view = byName(tree, 'ShellViewProbe')[0] - expect(view.props.bridgeEnabled).toBe(true) - await act(async () => - view.props.onBridgeMessage({ nativeEvent: { json: clientFrame({ type: 'ready' }) } }) - ) - expect(dependencies.posted.map((raw) => readBridgeHostMessage(raw))).toContainEqual({ - ok: true, - message: expect.objectContaining({ - type: 'init', - sessionId: 'session-one', - host: expect.objectContaining({ id: 'host-1' }) - }) - }) - }) - - it('rebuilds the view rather than updating it when the session id changes', async () => { - const tree = await renderScreen(readyState('session-one')) - await updateScreen(tree, readyState('session-two')) - expect(dependencies.lifecycle).toEqual([ - 'mount:session-one', - 'unmount:session-one', - 'mount:session-two' - ]) - }) - - it('forwards a failure the native view reports and drops a payload it cannot read', async () => { - const tree = await renderScreen(readyState('session-one')) - const view = byName(tree, 'ShellViewProbe')[0] - await act(async () => { - view.props.onLoadState({ nativeEvent: { state: 'ready' } }) - view.props.onLoadState({ nativeEvent: { state: 'failed', reason: 'invented' } }) - view.props.onLoadState({ nativeEvent: { state: 'failed', reason: 'render-process-gone' } }) - }) - expect(dependencies.reportShellFailure.mock.calls).toEqual([['render-process-gone']]) - }) - - it('requests an app-store refresh on every ready ask', async () => { - dependencies.client = createFakeRpcClient() - const tree = await renderScreen(readyState('session-one')) - const view = byName(tree, 'ShellViewProbe')[0] - const refreshesBeforeReady = dependencies.storageRefreshes - await act(async () => { - view.props.onBridgeMessage({ nativeEvent: { json: clientFrame({ type: 'ready' }) } }) - view.props.onBridgeMessage({ nativeEvent: { json: clientFrame({ type: 'ready' }) } }) - }) - // A document that reloads inside one mount asks again; a refresh per ask is what lets a key - // the app changed meanwhile reach the `init` after it. - expect(dependencies.storageRefreshes - refreshesBeforeReady).toBe(2) - }) - - // Observe wire frames only; ruling 34 leaves delivery untracked and one-shot consumption to the page. - async function renderForRoute(params: Record): Promise<{ - tree: ReactTestRenderer - initRoutes: () => (Record | undefined)[] - move: (next: Record) => Promise - ready: () => Promise - }> { - const element = (next: Record) => - createElement(MobileWebShellScreen, { - hostId: 'host-1', - route: { pathname: '/h/host-1', params: next } - }) - dependencies.state = readyState('session-one') - const rendered: { tree: ReactTestRenderer | null } = { tree: null } - await act(async () => { - rendered.tree = create(element(params)) - }) - const tree = rendered.tree - if (tree === null) { - throw new Error('screen did not render') - } - trackRenderedScreen(tree) - return { - tree, - // Parse with the page’s reader so rejected frames cannot inflate init counts. - initRoutes: () => - dependencies.posted - .map((json) => readBridgeHostMessage(json)) - .flatMap((read) => (read.ok && read.message.type === 'init' ? [read.message] : [])) - .map((frame) => frame.route?.params), - move: async (next) => { - await act(async () => { - tree.update(element(next)) - }) - }, - ready: async () => { - await act(async () => { - byName(tree, 'ShellViewProbe')[0].props.onBridgeMessage({ - nativeEvent: { json: clientFrame({ type: 'ready' }) } - }) - }) - } - } - } - - // Send once per route change; the next ready repairs missed delivery using the current route, without tracking acknowledgements (rulings 33.1/34). - it('posts one init for a route that moved, and none for a render that moved nothing', async () => { - dependencies.client = createFakeRpcClient() - const page = await renderForRoute({ paneKey: '' }) - await page.ready() - expect(page.initRoutes()).toEqual([{ paneKey: '' }]) - await page.move({ paneKey: 'pane-1' }) - expect(page.initRoutes()).toEqual([{ paneKey: '' }, { paneKey: 'pane-1' }]) - await page.move({ paneKey: 'pane-1' }) - expect(page.initRoutes()).toHaveLength(2) - }) - - it('answers every ask with the route it holds then, which is how a lost frame is repaired', async () => { - dependencies.client = createFakeRpcClient() - dependencies.postFails = true - const warned = vi.spyOn(console, 'warn').mockImplementation(() => undefined) - const page = await renderForRoute({ paneKey: '' }) - await page.ready() - await page.move({ paneKey: 'pane-1' }) - expect(dependencies.posted).toHaveLength(2) - dependencies.postFails = false - await page.ready() - expect(page.initRoutes().at(-1)).toEqual({ paneKey: 'pane-1' }) - warned.mockRestore() - }) - - // Client replacement rebuilds the host without changing the page session; seed it from reducer state because the page does not handshake again. - it('serves a page whose session handshook before this host was built', async () => { - const client = createFakeRpcClient() - dependencies.client = client - dependencies.pageReady = true - const tree = await renderScreen(readyState('session-one')) - // No new ready arrives from a page that was never told its host changed. - await act(async () => { - byName(tree, 'ShellViewProbe')[0].props.onBridgeMessage({ - nativeEvent: { - json: clientFrame({ type: 'request', id: bridgeId(1), method: 'status.get' }) - } - }) - }) - expect(client.requests.map((request) => request.method)).toEqual(['status.get']) - }) - - it('reports a ready page fault as a document-load failure', async () => { - dependencies.client = createFakeRpcClient() - const warned = vi.spyOn(console, 'warn').mockImplementation(() => undefined) - const tree = await renderScreen(readyState('session-one')) - await act(async () => { - // Only an established session receives the fault grant. - byName(tree, 'ShellViewProbe')[0].props.onBridgeMessage({ - nativeEvent: { json: clientFrame({ type: 'ready' }) } - }) - byName(tree, 'ShellViewProbe')[0].props.onBridgeMessage({ - nativeEvent: { - json: clientFrame({ - type: 'notify', - name: BRIDGE_FAULT_GRANT, - error: { category: 'Error', message: 'the route threw', isRpcDeliveryUnknown: false } - }) - } - }) - }) - expect(dependencies.reportShellFailure.mock.calls).toEqual([['document-load-failed']]) - warned.mockRestore() - }) - - it('reports a URL nothing on this phone could open, which is the dead tap that survives', async () => { - dependencies.client = createFakeRpcClient() - const failure = new Error('no activity found') - // Create rejection per call; constructing it before the frame arrives would leave it temporarily unhandled. - dependencies.openUrl.mockImplementation(() => Promise.reject(failure)) - const warned = vi.spyOn(console, 'warn').mockImplementation(() => undefined) - const tree = await renderScreen(readyState('session-one')) - await act(async () => { - byName(tree, 'ShellViewProbe')[0].props.onBridgeMessage({ - nativeEvent: { json: clientFrame({ type: 'ready' }) } - }) - byName(tree, 'ShellViewProbe')[0].props.onBridgeMessage({ - nativeEvent: { - json: clientFrame({ - type: 'notify', - name: 'externalLink', - url: 'mailto:someone@example.com' - }) - } - }) - }) - // Notify has no reply, so only diagnostics reveal that the device failed to open the link. - expect(warned.mock.calls).toContainEqual([ - '[web-shell] could not open a URL for the page', - { url: 'mailto:someone@example.com', error: failure } - ]) - warned.mockRestore() - }) - - it('pops its own stack when the page hands its back button over', async () => { - dependencies.client = createFakeRpcClient() - const tree = await renderScreen(readyState('session-one')) - await act(async () => { - byName(tree, 'ShellViewProbe')[0].props.onBridgeMessage({ - nativeEvent: { json: clientFrame({ type: 'ready' }) } - }) - byName(tree, 'ShellViewProbe')[0].props.onBridgeMessage({ - nativeEvent: { json: clientFrame({ type: 'notify', name: BRIDGE_NAVIGATE_BACK_NOTIFY }) } - }) - }) - expect(dependencies.back).toHaveBeenCalledTimes(1) - expect(dependencies.push).not.toHaveBeenCalled() - }) - - // This file pins iOS swipe interception; use-shell-page-back.test.tsx covers platform key selection. - it('carries the page taking the device Back key up to the session', async () => { - dependencies.client = createFakeRpcClient() - const tree = await renderScreen(readyState('session-one')) - await act(async () => { - byName(tree, 'ShellViewProbe')[0].props.onBridgeMessage({ - nativeEvent: { json: clientFrame({ type: 'ready' }) } - }) - byName(tree, 'ShellViewProbe')[0].props.onBridgeMessage({ - nativeEvent: { - json: clientFrame({ type: 'notify', name: BRIDGE_BACK_CLAIM_NOTIFY, claimed: true }) - } - }) - }) - expect(dependencies.reportPageBackClaim).toHaveBeenCalledWith(true) - }) - - it('pops nothing when this page is the first screen on the stack, rather than dismissing it', async () => { - dependencies.client = createFakeRpcClient() - dependencies.canGoBack = false - const warned = vi.spyOn(console, 'warn').mockImplementation(() => undefined) - const tree = await renderScreen(readyState('session-one')) - await act(async () => { - byName(tree, 'ShellViewProbe')[0].props.onBridgeMessage({ - nativeEvent: { json: clientFrame({ type: 'ready' }) } - }) - byName(tree, 'ShellViewProbe')[0].props.onBridgeMessage({ - nativeEvent: { json: clientFrame({ type: 'notify', name: BRIDGE_NAVIGATE_BACK_NOTIFY }) } - }) - }) - expect(dependencies.back).not.toHaveBeenCalled() - // Back notify has no reply; its log is the only evidence of failure. - expect(warned.mock.calls).toContainEqual([ - '[web-shell-bridge] did not pop the stack for a page going back', - { why: 'nothing-to-pop' } - ]) - warned.mockRestore() - }) - - it('shows a build id prefix and never the whole one, the cache path, or the host id', async () => { - const tree = await renderScreen(readyState('session-one')) - const text = textOf(tree) - expect(text).toContain(BUILD_ID.slice(0, 12)) - expect(text).toContain('4096 B') - expect(text).toContain('811 ms') - expect(text).not.toContain(BUILD_ID) - expect(text).not.toContain(DIRECTORY) - expect(text).not.toContain('host-1') - }) -}) - -describe('the dropped-frame count on the dev facts line', () => { - // 500,000 raw bytes exceed the frame cap once encoded. - const oversized = { - opcode: 1 as const, - seq: 1, - format: 'jpeg' as const, - metadata: {}, - image: new Uint8Array(500_000) - } - - async function openBinaryStream(tree: ReactTestRenderer): Promise { - await act(async () => { - byName(tree, 'ShellViewProbe')[0]?.props.onBridgeMessage({ - nativeEvent: { json: clientFrame({ type: 'ready' }) } - }) - }) - await act(async () => { - byName(tree, 'ShellViewProbe')[0]?.props.onBridgeMessage({ - nativeEvent: { - json: clientFrame({ - type: 'subscribe', - id: 'a'.repeat(22), - method: 'browser.screencast', - params: {}, - wantsBinary: true - }) - } - }) - }) - } - - async function drop(times: number): Promise { - const emit = dependencies.client?.streams[0]?.emitBinary - if (emit === undefined || emit === null) { - throw new Error('binary subscription was never opened') - } - for (let index = 0; index < times; index += 1) { - await act(async () => { - emit({ ...oversized, seq: index + 1 }) - }) - } - } - - function devFactsText(tree: ReactTestRenderer): string | null { - const line = byName(tree, 'Text').find( - (node) => node.props.testID === 'mobile-web-shell-dev-facts' - ) - return line === undefined ? null : String(line.props.children) - } - - it('shows the running total and resets it when the host is rebuilt', async () => { - dependencies.client = createFakeRpcClient() - dependencies.routeGrants = ['navigate', 'screencastBinary'] - const tree = await renderScreen(readyState('session-one')) - await openBinaryStream(tree) - await drop(2) - expect(devFactsText(tree)).toContain('2 frames dropped') - await updateScreen(tree, readyState('session-two')) - expect(devFactsText(tree)).not.toContain('dropped') - }) - - // Dev facts render null in release; their updates must not rerender the screen at screencast frequency. - it('renders the screen not once more per dropped frame in a production build', async () => { - Object.assign(globalThis, { __DEV__: false }) - try { - dependencies.client = createFakeRpcClient() - dependencies.routeGrants = ['navigate', 'screencastBinary'] - const tree = await renderScreen(readyState('session-one')) - await openBinaryStream(tree) - expect(devFactsText(tree)).toBeNull() - const before = dependencies.viewRenders - await drop(5) - expect({ extraRenders: dependencies.viewRenders - before }).toEqual({ extraRenders: 0 }) - expect(devFactsText(tree)).toBeNull() - } finally { - Object.assign(globalThis, { __DEV__: true }) - } - }) -}) - // Keep update refusal separate from the working fallback document; dismissing its notice must not reload that document. describe('a refused update is said beside the page, not in front of it', () => { function dismissControl(tree: ReactTestRenderer): ReactTestInstance | undefined { @@ -487,42 +69,4 @@ describe('a refused update is said beside the page, not in front of it', () => { expect(byName(tree, 'ShellViewProbe')).toHaveLength(1) expect(dependencies.lifecycle).toEqual([]) }) - - it('shows a later refusal rather than staying dismissed for the rest of the host', async () => { - dependencies.updateNotice = 'update-failed' - const tree = await renderScreen(readyState('session-one')) - await act(async () => { - tree.root - .find( - (node) => - String(node.type) === 'Pressable' && node.props.accessibilityLabel === 'Dismiss notice' - ) - .props.onPress() - }) - // A new document’s refusal must not inherit the previous document’s dismissal. - await updateScreen(tree, readyState('session-two')) - expect(dismissControl(tree)).toBeDefined() - }) -}) - -// Keep a cover until first paint; uncovering at ready exposed bare surface during measured 1.42-second cached-page startup. -describe('the frame under a page that has not painted', () => { - it('hands the page report to the session', async () => { - dependencies.pageFrame = 'unpainted' - dependencies.client = createFakeRpcClient() - const tree = await renderScreen(readyState('session-a')) - const probe = byName(tree, 'ShellViewProbe')[0] - await act(async () => { - probe.props.onBridgeMessage({ - nativeEvent: { json: clientFrame({ type: 'ready' }) } - }) - }) - expect(dependencies.reportPageReady).toHaveBeenCalledTimes(1) - await act(async () => { - probe.props.onBridgeMessage({ - nativeEvent: { json: clientFrame({ type: 'notify', name: BRIDGE_PAGE_PAINTED }) } - }) - }) - expect(dependencies.reportPagePainted).toHaveBeenCalledTimes(1) - }) }) diff --git a/mobile/src/mobile-web-shell/bridge-host-verdict-hold.test.ts b/mobile/src/mobile-web-shell/bridge-host-verdict-hold.test.ts index 6f8c2bd4fe5..60e3940beea 100644 --- a/mobile/src/mobile-web-shell/bridge-host-verdict-hold.test.ts +++ b/mobile/src/mobile-web-shell/bridge-host-verdict-hold.test.ts @@ -74,15 +74,4 @@ describe('the connection verdict hold', () => { 'stats.summary' ]) }) - - it('fails what waited when the host goes away before the verdict', async () => { - const { bridge } = heldBridge() - bridge.host.receive( - clientFrame({ type: 'request', id: bridgeId(1), method: 'worktree.ps', params: {} }) - ) - bridge.host.dispose() - await flushBridge() - expect(bridge.client.requests).toEqual([]) - expect(bridge.last()).toMatchObject({ type: 'error', id: bridgeId(1) }) - }) }) diff --git a/mobile/src/mobile-web-shell/bridge/bridge-reply-chunking.test.ts b/mobile/src/mobile-web-shell/bridge/bridge-reply-chunking.test.ts index b2165c21482..40f8bc6fc96 100644 --- a/mobile/src/mobile-web-shell/bridge/bridge-reply-chunking.test.ts +++ b/mobile/src/mobile-web-shell/bridge/bridge-reply-chunking.test.ts @@ -1,11 +1,5 @@ import { describe, expect, it } from 'vitest' -import { - BRIDGE_MAX_MESSAGE_BYTES, - BRIDGE_MAX_PENDING_REQUESTS, - BRIDGE_MAX_REPLY_BYTES, - BRIDGE_MAX_REPLY_PARTS, - utf8ByteLength -} from './bridge-caps' +import { BRIDGE_MAX_MESSAGE_BYTES, BRIDGE_MAX_REPLY_BYTES } from './bridge-caps' import { BRIDGE_PROTOCOL_VERSION, readBridgeHostMessage, @@ -20,7 +14,6 @@ import { const ID = 'AAAAAAAAAAAAAAAAAAAAAA' const OTHER_ID = 'BBBBBBBBBBBBBBBBBBBBBB' -const WORST_ESCAPING_CHARACTER = String.fromCharCode(1) function payloadOf(result: unknown): BridgeReplyPayload { return { id: 'r1', ok: true, result, _meta: { runtimeId: 'runtime-a' } } @@ -97,7 +90,6 @@ function splitInsidePair(extra = ''): BridgeReplyMessage[] { } const ASTRAL = String.fromCodePoint(0x1f600) -const LONE_HIGH_SURROGATE = String.fromCharCode(0xd800) function ceilingPayload(): BridgeReplyPayload { const overhead = JSON.stringify(payloadOf('')).length @@ -116,50 +108,6 @@ function assemble(frames: BridgeReplyMessage[]): ReturnType { - it('leaves a reply that fits in one frame unchunked, its escaped payload spliced byte for byte', () => { - const payload = payloadOf( - `quote " slash \\ line\n\u0001 caf\u00e9 ${ASTRAL}${LONE_HIGH_SURROGATE}` - ) - expect(rawFramesOf(splitBridgeReply(ID, payload))).toEqual([ - '{"v":1,"type":"reply","id":"AAAAAAAAAAAAAAAAAAAAAA","payload":{"id":"r1","ok":true,"result":"quote \\" slash \\\\ line\\n\\u0001 café \u{1f600}\\ud800","_meta":{"runtimeId":"runtime-a"}}}' - ]) - }) - - it('chunks a reply over the frame cap', () => { - const frames = framesOf(splitBridgeReply(ID, payloadOf('x'.repeat(1_500_000)))) - expect(frames.length).toBeGreaterThan(2) - expect(frames.map((frame) => ('part' in frame ? frame.part.i : -1))).toEqual( - frames.map((_, index) => index) - ) - }) - - it('ships only frames the receiving side will accept', () => { - for (const raw of rawFramesOf(splitBridgeReply(ID, payloadOf('x'.repeat(1_500_000))))) { - expect(utf8ByteLength(raw)).toBeLessThanOrEqual(BRIDGE_MAX_MESSAGE_BYTES) - expect(readBridgeHostMessage(raw).ok).toBe(true) - } - }) - - it('splits the worst reply the ceiling admits into fewer parts than the schema allows', () => { - // Use maximum-size fully re-escaped content to prove every accepted reply stays below the part-count ceiling. - const empty = payloadOf('') - const backslashes = Math.floor((BRIDGE_MAX_REPLY_BYTES - JSON.stringify(empty).length) / 2) - const payload = payloadOf('\\'.repeat(backslashes)) - expect(new TextEncoder().encode(JSON.stringify(payload)).byteLength).toBeLessThanOrEqual( - BRIDGE_MAX_REPLY_BYTES - ) - expect(new TextEncoder().encode(JSON.stringify(payload)).byteLength).toBeGreaterThan( - BRIDGE_MAX_REPLY_BYTES - 4 - ) - const split = splitBridgeReply(ID, payload) - const frames = framesOf(split) - expect(BRIDGE_MAX_REPLY_PARTS).toBeGreaterThan(frames.length) - for (const raw of rawFramesOf(split)) { - expect(utf8ByteLength(raw)).toBeLessThanOrEqual(BRIDGE_MAX_MESSAGE_BYTES) - } - expect(assemble(frames)).toEqual({ status: 'complete', payload }) - }) - it('never cuts a frame inside a surrogate pair, at any cut parity', () => { for (let padding = 0; padding < 4; padding += 1) { const payload = payloadOf(`${'x'.repeat(padding)}${ASTRAL.repeat(1_000_000)}`) @@ -178,80 +126,9 @@ describe('splitBridgeReply', () => { } } }) - - it('round-trips a reply of exactly the ceiling, cuts and all', () => { - const payload = ceilingPayload() - expect(new TextEncoder().encode(JSON.stringify(payload)).byteLength).toBe( - BRIDGE_MAX_REPLY_BYTES - ) - expect(assemble(framesOf(splitBridgeReply(ID, payload)))).toEqual({ - status: 'complete', - payload - }) - }) - - it('refuses a lone-surrogate reply over the ceiling rather than splitting it', () => { - const payload = payloadOf(LONE_HIGH_SURROGATE.repeat(BRIDGE_MAX_REPLY_BYTES / 6)) - expect(splitBridgeReply(ID, payload)).toEqual({ ok: false, refusal: 'reply-too-large' }) - }) - - it('round-trips lone surrogates that fit', () => { - const payload = payloadOf(LONE_HIGH_SURROGATE.repeat(200_000)) - expect(assemble(framesOf(splitBridgeReply(ID, payload)))).toEqual({ - status: 'complete', - payload - }) - }) - - it('refuses a reply over the ceiling instead of chunking it forever', () => { - const oversized = payloadOf('x'.repeat(BRIDGE_MAX_REPLY_BYTES + 1)) - expect(splitBridgeReply(ID, oversized)).toEqual({ ok: false, refusal: 'reply-too-large' }) - }) }) describe('round trip', () => { - const payloads: [string, BridgeReplyPayload][] = [ - ['a small reply', payloadOf({ ok: 1 })], - ['a reply spanning several frames', payloadOf('x'.repeat(1_500_000))], - ['a reply of astral characters', payloadOf('\u{1f600}'.repeat(400_000))], - ['a reply of control characters', payloadOf(WORST_ESCAPING_CHARACTER.repeat(1_300_000))], - ['a reply of mixed widths', payloadOf(`${'é'.repeat(300_000)}${'中'.repeat(300_000)}`)] - ] - - for (const [name, payload] of payloads) { - it(`reassembles ${name} byte for byte`, () => { - const split = splitBridgeReply(ID, payload) - const frames = framesOf(split) - expect(frames.length).toBeLessThanOrEqual(BRIDGE_MAX_REPLY_PARTS) - for (const raw of rawFramesOf(split)) { - expect(new TextEncoder().encode(raw).byteLength).toBeLessThanOrEqual( - BRIDGE_MAX_MESSAGE_BYTES - ) - } - expect(assemble(frames)).toEqual({ - status: 'complete', - payload - }) - }) - } - - it('restores a surrogate pair that was cut in half between two frames', () => { - // JSON escapes lone surrogate halves; joining the decoded parts must restore the original pair. - const head = '{"id":"r1","ok":true,"result":"\ud83d' - const tail = '\ude00","_meta":{"runtimeId":"runtime-a"}}' - expect(JSON.parse(JSON.stringify(head))).toBe(head) - expect(assemble([part(0, 2, head), part(1, 2, tail)])).toEqual({ - status: 'complete', - payload: payloadOf('\u{1f600}') - }) - }) - - it('reassembles frames that arrive out of order', () => { - const payload = payloadOf('x'.repeat(1_500_000)) - const frames = framesOf(splitBridgeReply(ID, payload)) - expect(assemble(frames.toReversed())).toEqual({ status: 'complete', payload }) - }) - it('keeps two replies apart while both are in flight', () => { const first = payloadOf('x'.repeat(1_500_000)) const second = payloadOf('y'.repeat(1_500_000)) @@ -273,21 +150,6 @@ describe('round trip', () => { }) describe('BridgeReplyAssembler refusals', () => { - it('stays pending while a part is missing', () => { - const assembler = new BridgeReplyAssembler() - expect(assembler.accept(part(0, 3, '{"id"'))).toEqual({ status: 'pending' }) - expect(assembler.accept(part(2, 3, '}'))).toEqual({ status: 'pending' }) - }) - - it('refuses a part index that arrived already, and drops what it held', () => { - const assembler = new BridgeReplyAssembler() - expect(assembler.accept(part(0, 2, 'a'))).toEqual({ status: 'pending' }) - expect(assembler.accept(part(0, 2, 'a'))).toEqual({ - status: 'failed', - refusal: 'duplicate-part' - }) - }) - it('keeps a refused id refused, so a sender cannot start over on the next part', () => { const assembler = new BridgeReplyAssembler() assembler.accept(part(0, 3, '{"id"')) @@ -317,56 +179,6 @@ describe('BridgeReplyAssembler refusals', () => { expect(assembler.accept(part(0, 3, '{"id"'))).toEqual({ status: 'pending' }) }) - it('refuses every later part of a reply that went past the ceiling', () => { - const assembler = new BridgeReplyAssembler() - const frames = asciiParts(BRIDGE_MAX_REPLY_BYTES + 1) - for (const frame of frames.slice(0, -1)) { - expect(assembler.accept(frame)).toEqual({ status: 'pending' }) - } - expect(assembler.accept(requiredLast(frames))).toEqual({ - status: 'failed', - refusal: 'reply-too-large' - }) - for (const frame of checkedParts(['new', 'reply'])) { - expect(assembler.accept(frame)).toEqual({ status: 'failed', refusal: 'reply-too-large' }) - } - }) - - it('refuses a part whose count disagrees with the parts already held', () => { - const assembler = new BridgeReplyAssembler() - expect(assembler.accept(part(0, 2, 'a'))).toEqual({ status: 'pending' }) - expect(assembler.accept(part(1, 3, 'b'))).toEqual({ - status: 'failed', - refusal: 'inconsistent-part' - }) - }) - - it('refuses a part index that is not inside its own count', () => { - expect(new BridgeReplyAssembler().accept(part(2, 2, 'a'))).toEqual({ - status: 'failed', - refusal: 'inconsistent-part' - }) - }) - - it('holds no more half-assembled replies than there can be requests in flight', () => { - const assembler = new BridgeReplyAssembler() - const idOf = (index: number): string => `id${String(index).padStart(20, '0')}` - for (let index = 0; index < BRIDGE_MAX_PENDING_REQUESTS; index += 1) { - expect(assembler.accept(part(0, 2, 'a', idOf(index)))).toEqual({ status: 'pending' }) - } - const overflowing = idOf(BRIDGE_MAX_PENDING_REQUESTS) - expect(assembler.accept(part(0, 2, 'a', overflowing))).toEqual({ - status: 'failed', - refusal: 'too-many-pending' - }) - expect(assembler.accept(part(1, 2, 'b', idOf(0)))).toEqual({ - status: 'failed', - refusal: 'malformed-json' - }) - assembler.discard(overflowing) - expect(assembler.accept(part(0, 2, 'a', overflowing))).toEqual({ status: 'pending' }) - }) - it('refuses the part that would push every reply in flight past the aggregate', () => { const assembler = new BridgeReplyAssembler() const idOf = (index: number) => `id${String(index).padStart(20, '0')}` @@ -388,29 +200,6 @@ describe('BridgeReplyAssembler refusals', () => { }) }) - it('forgets every refusal when it is cleared for teardown', () => { - const assembler = new BridgeReplyAssembler() - assembler.accept(part(0, 2, 'a')) - expect(assembler.accept(part(0, 2, 'a'))).toEqual({ - status: 'failed', - refusal: 'duplicate-part' - }) - assembler.clear() - expect(assembler.accept(part(0, 2, 'a'))).toEqual({ status: 'pending' }) - }) - - it('frees a slot when the page discards an id it abandoned', () => { - const assembler = new BridgeReplyAssembler() - const idOf = (index: number): string => `id${String(index).padStart(20, '0')}` - for (let index = 0; index < BRIDGE_MAX_PENDING_REQUESTS; index += 1) { - assembler.accept(part(0, 2, 'a', idOf(index))) - } - assembler.discard(idOf(3)) - expect(assembler.accept(part(0, 2, 'a', idOf(BRIDGE_MAX_PENDING_REQUESTS)))).toEqual({ - status: 'pending' - }) - }) - it('measures joined UTF8 bytes when a surrogate pair crosses parts', () => { const payload = ceilingPayload() expect(new TextEncoder().encode(JSON.stringify(payload)).byteLength).toBe( @@ -426,67 +215,4 @@ describe('BridgeReplyAssembler refusals', () => { expect(new TextEncoder().encode(joined).byteLength).toBeGreaterThan(BRIDGE_MAX_REPLY_BYTES) expect(assemble(frames)).toEqual({ status: 'failed', refusal: 'reply-too-large' }) }) - - it('retains incomplete ASCII parts totaling exactly the reply ceiling', () => { - const assembler = new BridgeReplyAssembler() - for (const frame of asciiParts(BRIDGE_MAX_REPLY_BYTES)) { - expect(assembler.accept(frame)).toEqual({ status: 'pending' }) - } - }) - - it('aborts incomplete ASCII parts one byte past the reply ceiling', () => { - const assembler = new BridgeReplyAssembler() - const frames = asciiParts(BRIDGE_MAX_REPLY_BYTES + 1) - for (const frame of frames.slice(0, -1)) { - expect(assembler.accept(frame)).toEqual({ status: 'pending' }) - } - expect(assembler.accept(requiredLast(frames))).toEqual({ - status: 'failed', - refusal: 'reply-too-large' - }) - }) - - it('refuses parts that do not reassemble into JSON', () => { - const assembler = new BridgeReplyAssembler() - assembler.accept(part(0, 2, '{"id":')) - expect(assembler.accept(part(1, 2, 'not json'))).toEqual({ - status: 'failed', - refusal: 'malformed-json' - }) - }) - - it('refuses parts that reassemble into something that is not a reply', () => { - const assembler = new BridgeReplyAssembler() - assembler.accept(part(0, 2, '{"id":"r1",')) - expect(assembler.accept(part(1, 2, '"ok":true}'))).toEqual({ - status: 'failed', - refusal: 'unrecognised-message' - }) - }) - - it('drops a half-assembled reply when the whole one arrives instead', () => { - const assembler = new BridgeReplyAssembler() - const payload = payloadOf({ ok: 1 }) - assembler.accept(part(0, 2, '{"id":')) - expect( - assembler.accept({ v: BRIDGE_PROTOCOL_VERSION, type: 'reply', id: ID, payload }) - ).toEqual({ status: 'complete', payload }) - expect(assembler.accept(part(0, 2, '{"id":'))).toEqual({ status: 'pending' }) - }) - - it('forgets a reply the page abandoned', () => { - const assembler = new BridgeReplyAssembler() - assembler.accept(part(0, 2, 'a')) - assembler.discard(ID) - expect(assembler.accept(part(0, 2, 'a'))).toEqual({ status: 'pending' }) - }) - - it('forgets every reply on teardown', () => { - const assembler = new BridgeReplyAssembler() - assembler.accept(part(0, 2, 'a')) - assembler.accept(part(0, 2, 'a', OTHER_ID)) - assembler.clear() - expect(assembler.accept(part(0, 2, 'a'))).toEqual({ status: 'pending' }) - expect(assembler.accept(part(0, 2, 'a', OTHER_ID))).toEqual({ status: 'pending' }) - }) }) diff --git a/mobile/src/mobile-web-shell/bridge/page-device-store.test.ts b/mobile/src/mobile-web-shell/bridge/page-device-store.test.ts deleted file mode 100644 index 19a2c549b5c..00000000000 --- a/mobile/src/mobile-web-shell/bridge/page-device-store.test.ts +++ /dev/null @@ -1,53 +0,0 @@ -import { afterEach, describe, expect, it } from 'vitest' -import { MOBILE_WEB_SHELL_GRANTS } from '../page-route-policy' -import { createFakeBridgePortPair, disposeBridgePortPair } from './bridge-port-pair-test-harness' -import { createPageDeviceStore } from './page-device-store' -import { storeParamsSchema } from './bridge-store-verb' - -let pair: ReturnType | null = null - -afterEach(async () => { - if (pair) { - await disposeBridgePortPair(pair) - } - pair = null -}) - -describe('the page device store', () => { - it('answers unavailable without asking a shell that did not grant the verb', async () => { - pair = createFakeBridgePortPair({ - routeGrants: MOBILE_WEB_SHELL_GRANTS.filter((grant) => grant !== 'native.store.rows') - }) - await pair.flush() - const store = createPageDeviceStore(pair.client) - - expect(await store.read('cache', ['q-1'])).toEqual({ status: 'unavailable' }) - expect(await store.write('draft', [{ key: 'draft:chat::t', value: 'dHlwZWQ=' }])).toEqual({ - written: false, - refusal: 'unavailable' - }) - expect(pair.toShell.filter((json) => json.includes('"native.store.rows"'))).toEqual([]) - }) - - it('reads deferred keys again until every value is in hand', async () => { - const stored: Record = { a: 'QQ==', b: 'Qg==', c: 'Qw==' } - pair = createFakeBridgePortPair({ - // Fills only the first key of each read, like a reply that hit its budget. - serveNativeVerb: async (_verb, params) => { - const call = storeParamsSchema.parse(params) - const keys = call.action === 'read' ? call.keys : [] - return { - values: keys.map((key, at) => (at === 0 ? stored[key] : null)), - deferred: keys.slice(1).map((_key, at) => at + 1) - } - } - }) - await pair.flush() - const store = createPageDeviceStore(pair.client) - - expect(await store.read('cache', ['a', 'b', 'c'])).toEqual({ - status: 'ok', - values: ['QQ==', 'Qg==', 'Qw=='] - }) - }) -}) diff --git a/mobile/src/mobile-web-shell/host-area-two-hosts.test.tsx b/mobile/src/mobile-web-shell/host-area-two-hosts.test.tsx deleted file mode 100644 index 7ace2754e71..00000000000 --- a/mobile/src/mobile-web-shell/host-area-two-hosts.test.tsx +++ /dev/null @@ -1,121 +0,0 @@ -// Push host B over A, then pop: A must regain area ownership without a duplicate native sidebar. -import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' - -const harness = await vi.hoisted(async () => await import('./mobile-web-shell-screen-test-harness')) -const dependencies = vi.hoisted(() => harness.createScreenDependencies()) -const { screenModuleMocks } = await vi.hoisted( - async () => await import('./mobile-web-shell-screen-test-mocks') -) -const mocks = vi.hoisted(() => screenModuleMocks(dependencies)) -const stack = await vi.hoisted(async () => { - const React = await import('react') - const hosts: string[] = ['host-a'] - return { - hosts, - Focused: React.createContext(true), - HostSidebar: function HostSidebar(): null { - return null - } - } -}) - -vi.mock('react-native', () => ({ - ...mocks['react-native'](), - PanResponder: { create: () => ({ panHandlers: {} }) }, - useWindowDimensions: () => ({ width: 1180, height: 820 }) -})) -vi.mock('expo-router', async () => { - const React = await import('react') - return { - ...mocks['expo-router'](), - useGlobalSearchParams: () => ({ hostId: stack.hosts.at(-1) }), - // Model native stack focus: rerun only for the top screen when it returns. - useFocusEffect: (effect: () => undefined | (() => void)) => { - const focused = React.useContext(stack.Focused) - React.useEffect(() => (focused ? effect() : undefined), [focused, effect]) - } - } -}) -vi.mock('expo-clipboard', mocks['expo-clipboard']) -vi.mock('expo-haptics', mocks['expo-haptics']) -vi.mock('expo-document-picker', mocks['expo-document-picker']) -vi.mock('@orca/expo-two-way-audio', mocks['@orca/expo-two-way-audio']) -vi.mock('expo-keep-awake', mocks['expo-keep-awake']) -vi.mock('expo-image-picker', mocks['expo-image-picker']) -vi.mock('expo-file-system', mocks['expo-file-system']) -vi.mock('../device-store/device-store', mocks['../device-store/device-store']) -vi.mock('lucide-react-native', mocks['lucide-react-native']) -vi.mock('react-native-safe-area-context', mocks['react-native-safe-area-context']) -vi.mock('../../modules/orca-mobile-web-shell/src', mocks['../../modules/orca-mobile-web-shell/src']) -vi.mock('../app-update/use-wall-app-update', mocks['../app-update/use-wall-app-update']) -vi.mock('../transport/host-client-hooks', mocks['../transport/host-client-hooks']) -vi.mock('./use-page-host-snapshot', mocks['./use-page-host-snapshot']) -vi.mock('./use-mobile-web-shell-session', () => ({ - useMobileWebShellSession: (args: { routePathname: string }) => ({ - ...mocks['./use-mobile-web-shell-session']().useMobileWebShellSession(), - ownsHostArea: /^\/h\/[^/]+$/.test(args.routePathname) - }) -})) -vi.mock('../theme/mobile-theme', async (original) => ({ - ...(await original>()), - colors: {} -})) -vi.mock('../storage/preferences', () => ({ - HOST_SIDEBAR_DEFAULT_WIDTH: 320, - HOST_SIDEBAR_MAX_WIDTH: 480, - HOST_SIDEBAR_MIN_WIDTH: 240, - loadHostSidebarWidth: async () => 320, - saveHostSidebarWidth: async () => {} -})) -vi.mock('../components/HostProtocolGate', () => ({ - HostProtocolGate: ({ children }: { children: unknown }) => children -})) -vi.mock('../host-screen/HostScreen', () => ({ HostScreen: stack.HostSidebar })) -vi.mock('../navigation/host-stack', async () => { - const { MobileWebShellScreen } = await import('./MobileWebShellScreen') - return { - HostStack: () => - stack.hosts.map((hostId, index) => ( - - - - )) - } -}) - -import { act, create, type ReactTestRenderer } from 'react-test-renderer' -import HostGroupLayout from '../../app/h/_layout' - -const mounted: { tree: ReactTestRenderer | null } = { tree: null } - -async function show(hosts: string[]): Promise { - stack.hosts = hosts - dependencies.pathname = `/h/${hosts.at(-1) ?? ''}` - await act(async () => { - if (mounted.tree === null) { - mounted.tree = create() - } else { - mounted.tree.update() - } - }) - await act(async () => {}) - return mounted.tree?.root.findAllByType(stack.HostSidebar).length ?? 0 -} - -beforeEach(() => { - harness.resetScreenDependencies(dependencies) - dependencies.state = harness.readyState('session-1') - mounted.tree = null -}) - -afterEach(() => { - act(() => mounted.tree?.unmount()) -}) - -describe('two hosts whose pages own the host area', () => { - it('draws no native sidebar beside either, through a push and the pop back', async () => { - expect(await show(['host-a'])).toBe(0) - expect(await show(['host-a', 'host-b'])).toBe(0) - expect(await show(['host-a'])).toBe(0) - }) -}) diff --git a/mobile/src/mobile-web-shell/mobile-web-shell-back-claim-state.test.ts b/mobile/src/mobile-web-shell/mobile-web-shell-back-claim-state.test.ts index 213e7b5be6a..54d7754e387 100644 --- a/mobile/src/mobile-web-shell/mobile-web-shell-back-claim-state.test.ts +++ b/mobile/src/mobile-web-shell/mobile-web-shell-back-claim-state.test.ts @@ -13,36 +13,12 @@ describe('the page claiming the device Back key', () => { ) } - it('records the claim and gives it back when the page lets go', () => { - const held = claimed() - expect(shellPageBackClaimed(held.session)).toBe(true) - expect( - shellPageBackClaimed(run(held.session, { type: 'page-back-claim', claimed: false }).session) - ).toBe(false) - }) - it('drops it when a replacement document starts inside this mount', () => { expect(shellPageBackClaimed(run(claimed().session, { type: 'document-started' }).session)).toBe( false ) }) - it('drops it when the view is remounted under a new session id', () => { - const remounted = run(claimed().session, { type: 'remounted', sessionId: 'session-two' }) - expect(shellPageBackClaimed(remounted.session)).toBe(false) - }) - - it('drops it when the document asks for a session again, so the page has to claim again', () => { - const reasked = run(claimed().session, { type: 'page-ready' }) - expect(shellPageBackClaimed(reasked.session)).toBe(false) - }) - - it('drops it when a refetch takes the generation off screen', () => { - const failed = run(claimed().session, { type: 'shell-failed', reason: 'generation-unreadable' }) - expect(failed.session.state.kind).not.toBe('ready') - expect(shellPageBackClaimed(failed.session)).toBe(false) - }) - it('records nothing from a page whose generation is no longer on screen', () => { const failed = run(claimed().session, { type: 'shell-failed', reason: 'isolation-unavailable' }) const late = run(failed.session, { type: 'page-back-claim', claimed: true }) diff --git a/mobile/src/mobile-web-shell/mobile-web-shell-page-route-wall.test.ts b/mobile/src/mobile-web-shell/mobile-web-shell-page-route-wall.test.ts deleted file mode 100644 index 36150a7d379..00000000000 --- a/mobile/src/mobile-web-shell/mobile-web-shell-page-route-wall.test.ts +++ /dev/null @@ -1,96 +0,0 @@ -import { describe, expect, it } from 'vitest' -import { - MANIFEST, - awaitingManifest, - createMobileWebShellSession, - gates, - run -} from './mobile-web-shell-session-test-fixtures' - -const UNLISTED_WALL = { kind: 'wall', verdict: { kind: 'blocked', reason: 'page-route-unlisted' } } - -describe('a manifest whose page does not serve this route walls instead of going native', () => { - it('walls the desktop as too old for a route the bundle does not list', () => { - const step = run(awaitingManifest(null).session, { - type: 'manifest-read', - manifest: { ...MANIFEST, routes: [{ pathname: '/h/[hostId]/tasks', grants: [] }] } - }) - expect(step.session.state).toEqual(UNLISTED_WALL) - expect(step.effects).toEqual([]) - }) - - it('walls this app as too old for a route listed with a grant it does not implement', () => { - const step = run(awaitingManifest(null).session, { - type: 'manifest-read', - manifest: { - ...MANIFEST, - routes: [{ pathname: '/h/[hostId]', grants: ['navigate', 'teleport'] }] - } - }) - expect(step.session.state).toEqual({ - kind: 'wall', - verdict: { kind: 'blocked', reason: 'page-route-grant-missing' } - }) - expect(step.effects).toEqual([]) - }) - - it('walls the desktop as too old when it predates the routes field itself', () => { - const step = run(awaitingManifest(null).session, { - type: 'manifest-read', - manifest: { ...MANIFEST, routes: undefined } - }) - expect(step.session.state).toEqual(UNLISTED_WALL) - }) - - it('answers the compat wall before the route, since an unreadable schema hides the route list', () => { - const step = run(awaitingManifest(null).session, { - type: 'manifest-read', - manifest: { ...MANIFEST, schemaVersion: 99, routes: [] } - }) - expect(step.session.state).toEqual({ - kind: 'wall', - verdict: { kind: 'blocked', reason: 'bundle-shell-too-old', schemaVersion: 99 } - }) - }) - - it('walls a page below the floor as it is, whatever routes it lists', () => { - const step = run(awaitingManifest(null).session, { - type: 'manifest-read', - manifest: { ...MANIFEST, pageVersion: 0, routes: [] } - }) - expect(step.session.state).toMatchObject({ - kind: 'wall', - verdict: { reason: 'bundle-incompatible', side: 'desktop', pageVersion: 0 } - }) - }) - - it('says the screen is unavailable, not the desktop too old, for a pathname this app has no screen for', () => { - const opened = run( - createMobileWebShellSession('/h/host-1/insights', false, false), - { type: 'gates-changed', gates: gates() }, - { type: 'cache-read', generation: null } - ) - const step = run(opened.session, { type: 'manifest-read', manifest: MANIFEST }) - expect(step.session.state).toEqual({ kind: 'route-unavailable' }) - }) - - it('says the screen is unavailable when the manifest carries a pattern this shell cannot read', () => { - const step = run(awaitingManifest(null).session, { - type: 'manifest-read', - manifest: { ...MANIFEST, routes: [{ pathname: '/h/[...a]/[...b]', grants: [] }] } - }) - expect(step.session.state).toEqual({ kind: 'route-unavailable' }) - }) - - it('keeps that answer across a layout flip, which rebuilds the session', () => { - const opened = run( - createMobileWebShellSession('/h/host-1/insights', false, false), - { type: 'gates-changed', gates: gates() }, - { type: 'cache-read', generation: null }, - { type: 'manifest-read', manifest: MANIFEST } - ) - expect(run(opened.session, { type: 'layout-changed', wide: true }).session.appNamesRoute).toBe( - false - ) - }) -}) diff --git a/mobile/src/mobile-web-shell/mobile-web-shell-refused-update-decision.test.ts b/mobile/src/mobile-web-shell/mobile-web-shell-refused-update-decision.test.ts index 16874e75f5c..db718a15cbd 100644 --- a/mobile/src/mobile-web-shell/mobile-web-shell-refused-update-decision.test.ts +++ b/mobile/src/mobile-web-shell/mobile-web-shell-refused-update-decision.test.ts @@ -11,8 +11,6 @@ import { withoutRecord } from './mobile-web-shell-session-test-fixtures' -const DOWNLOAD_FAILED = { kind: 'failed', reason: 'download-failed', retriedOnce: false } - // Refused updates should fall back to intact cached bytes under their own routes/grants, as offline entry does, while respecting any reachable host’s compatibility window. describe('an update this shell refused falls back to the generation that already works', () => { // Change assets and grants so the new manifest cannot safely authorize the old bytes. @@ -30,66 +28,10 @@ describe('an update this shell refused falls back to the generation that already ) } - it('asks for the newer generation before any of this, so the refusal is a real one', () => { - const fetching = run(awaitingManifest(CACHED).session, { - type: 'manifest-read', - manifest: NEWER - }) - expect(fetching.session.state).toMatchObject({ kind: 'fetching' }) - expect(fetching.effects).toEqual([{ kind: 'download' }]) - }) - - it('opens the cached generation rather than walling a host it can still reach', () => { - const step = refused() - expect(step.session.updateNotice).toBe('update-failed') - expect(step.session.state).toEqual({ kind: 'activating', source: 'cache' }) - expect(withoutRecord(step.effects)).toEqual([ - { - kind: 'open-generation', - directory: CACHED.directory, - buildId: CACHED.buildId, - totalBytes: CACHED.totalBytes - } - ]) - }) - it('runs it under its own grants, not the ones the refused manifest declared', () => { expect(refused().session.routeGrants).toEqual(['navigate']) }) - it('names the refusal as a notice beside the workspace, not as a state in front of it', () => { - const ready = run(refused().session, { - type: 'activated', - generationDirectory: CACHED.directory, - sessionId: 'session-one', - buildId: CACHED.buildId, - totalBytes: CACHED.totalBytes, - elapsedMs: 8 - }) - expect(ready.session.state).toMatchObject({ kind: 'ready', buildId: CACHED.buildId }) - expect(ready.session.updateNotice).toBe('update-failed') - }) - - it('leaves the refused generation out of the cache and keeps the cached one', () => { - const step = refused() - expect(step.session.cached).toEqual(CACHED) - expect(step.effects.map((effect) => effect.kind)).not.toContain('delete-cache') - }) - - it('still walls when there is no cached generation to fall back to', () => { - const step = run(awaitingManifest(null).session, { - type: 'manifest-read', - manifest: NEWER - }) - const failed = run(step.session, { type: 'download-failed', cause: BUNDLE_REFUSED }) - expect(failed.session.state).toEqual({ - kind: 'failed', - reason: 'download-failed', - retriedOnce: false - }) - expect(withoutRecord(failed.effects)).toEqual([]) - }) - it('walls the cached generation the host has moved past rather than serving it', () => { // Unlike offline fallback, this reachable host can have moved outside the cached bundle’s compatibility window. const step = run( @@ -111,28 +53,6 @@ describe('an update this shell refused falls back to the generation that already }) expect(withoutRecord(step.effects)).toEqual([]) }) - - it('shows the download failure when the cached bundle never carried the route, before any wall', () => { - // An unclaimed cached route is download failure, not a compat wall, even when those unused bytes are below the host floor. - const fetching = run(awaitingManifest({ ...CACHED_BELOW_HOST_FLOOR, routes: [] }).session, { - type: 'manifest-read', - manifest: NEWER - }) - const step = run(fetching.session, { type: 'download-failed', cause: BUNDLE_REFUSED }) - expect(step.session.state).toEqual(DOWNLOAD_FAILED) - expect(step.session.updateNotice).toBeNull() - expect(withoutRecord(step.effects)).toEqual([]) - }) - - it('shows the download failure for a generation from before routes were listed at all', () => { - // Older cached manifests lack routes and cannot claim this one; do not wall bytes that will not run. - const fetching = run( - awaitingManifest({ ...CACHED_BELOW_HOST_FLOOR, routes: undefined }).session, - { type: 'manifest-read', manifest: NEWER } - ) - const step = run(fetching.session, { type: 'download-failed', cause: BUNDLE_REFUSED }) - expect(step.session.state).toEqual(DOWNLOAD_FAILED) - }) }) // Gates can change during fetching; fallback must use their current verdict, including recoverable unreadable status, instead of inventing another decision. @@ -148,16 +68,6 @@ describe('the fallback answers each gate verdict the way the rest of the shell d return run(moved.session, { type: 'download-failed', cause: BUNDLE_REFUSED }) } - it('walls the host when it has stopped serving a bundle at all', () => { - const step = refusedUnder({ hostCapabilities: [] }) - expect(step.session.state).toEqual({ - kind: 'wall', - verdict: { kind: 'blocked', reason: 'bundle-unavailable' } - }) - expect(step.session.updateNotice).toBeNull() - expect(withoutRecord(step.effects)).toEqual([]) - }) - it('says the status could not be read rather than serving a generation it cannot judge', () => { const step = refusedUnder({ statusReadable: false, hostCapabilities: [] }) expect(step.session.state).toEqual({ @@ -169,68 +79,4 @@ describe('the fallback answers each gate verdict the way the rest of the shell d { kind: 'open-cache' } ]) }) - - it('serves a generation the host can no longer be asked about, compat check and all skipped', () => { - // Offline fallback skips compatibility checks because no reachable host has stated a newer window. - const step = refusedUnder({ reachability: 'unreachable' }, CACHED_BELOW_HOST_FLOOR) - expect(step.session.state).toEqual({ kind: 'activating', source: 'cache' }) - expect(step.session.updateNotice).toBe('update-failed') - }) - - it.each([{ reachability: 'connecting' as const }, { statusPending: true, hostCapabilities: [] }])( - 'opens the cached generation before the verdict (%o), which then judges it', - (patch) => { - const step = refusedUnder(patch, CACHED_BELOW_HOST_FLOOR) - expect(step.session.state).toEqual({ kind: 'activating', source: 'cache' }) - } - ) - - it('judges the generation only on the verdict that leaves a host to judge against', () => { - const step = refusedUnder({}, CACHED_BELOW_HOST_FLOOR) - expect(step.session.state).toMatchObject({ kind: 'wall' }) - }) -}) - -describe('an update this shell refused, once it is on screen', () => { - const NEWER = manifestFacts({ ...MANIFEST_WIRE, buildId: 'c'.repeat(64) }) - - function refused() { - return run( - awaitingManifest(CACHED).session, - { type: 'manifest-read', manifest: NEWER }, - { type: 'download-failed', cause: BUNDLE_REFUSED } - ) - } - - it('tries the update again on the next run of the flow, and drops the notice with it', () => { - const retried = run(refused().session, { type: 'retry-pressed' }) - expect(retried.session.updateNotice).toBeNull() - expect(retried.effects).toEqual([{ kind: 'open-cache' }]) - const again = run( - retried.session, - { type: 'cache-read', generation: CACHED }, - { - type: 'activated', - generationDirectory: CACHED.directory, - sessionId: 'session-two', - buildId: CACHED.buildId, - totalBytes: CACHED.totalBytes, - elapsedMs: 8 - } - ) - expect(again.effects).toContainEqual({ kind: 'read-manifest' }) - }) - - it('drops the notice the moment the flow runs again, before anything is known again', () => { - const served = run(refused().session, { - type: 'activated', - generationDirectory: CACHED.directory, - sessionId: 'session-one', - buildId: CACHED.buildId, - totalBytes: CACHED.totalBytes, - elapsedMs: 8 - }) - const dropped = run(served.session, { type: 'shell-failed', reason: 'generation-unreadable' }) - expect(dropped.session.updateNotice).toBeNull() - }) }) diff --git a/mobile/src/mobile-web-shell/mobile-web-shell-safe-area-screen.test.tsx b/mobile/src/mobile-web-shell/mobile-web-shell-safe-area-screen.test.tsx deleted file mode 100644 index cda126a2b96..00000000000 --- a/mobile/src/mobile-web-shell/mobile-web-shell-safe-area-screen.test.tsx +++ /dev/null @@ -1,91 +0,0 @@ -import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' - -const harness = await vi.hoisted(async () => await import('./mobile-web-shell-screen-test-harness')) -const dependencies = vi.hoisted(() => harness.createScreenDependencies()) - -const { screenModuleMocks } = await vi.hoisted( - async () => await import('./mobile-web-shell-screen-test-mocks') -) -const mocks = vi.hoisted(() => screenModuleMocks(dependencies)) -vi.mock('react-native', mocks['react-native']) -vi.mock('expo-clipboard', mocks['expo-clipboard']) -vi.mock('expo-haptics', mocks['expo-haptics']) -vi.mock('expo-document-picker', mocks['expo-document-picker']) -vi.mock('@orca/expo-two-way-audio', mocks['@orca/expo-two-way-audio']) -vi.mock('expo-keep-awake', mocks['expo-keep-awake']) -vi.mock('expo-image-picker', mocks['expo-image-picker']) -vi.mock('expo-file-system', mocks['expo-file-system']) -vi.mock('../device-store/device-store', mocks['../device-store/device-store']) -vi.mock('lucide-react-native', mocks['lucide-react-native']) -vi.mock('react-native-safe-area-context', mocks['react-native-safe-area-context']) -vi.mock('expo-router', mocks['expo-router']) -vi.mock('../../modules/orca-mobile-web-shell/src', mocks['../../modules/orca-mobile-web-shell/src']) -vi.mock('../app-update/use-wall-app-update', mocks['../app-update/use-wall-app-update']) -vi.mock('../transport/host-client-hooks', mocks['../transport/host-client-hooks']) -vi.mock('./use-page-host-snapshot', mocks['./use-page-host-snapshot']) -vi.mock('./use-mobile-web-shell-session', mocks['./use-mobile-web-shell-session']) - -import { act } from 'react-test-renderer' -import { clientFrame, createFakeRpcClient } from './bridge-host-test-fakes' -import { - byName, - readyState, - renderScreen as mountScreen -} from './mobile-web-shell-screen-test-harness' -import { readBridgeHostMessage } from './bridge/bridge-envelope' -import { MobileWebShellScreen } from './MobileWebShellScreen' -import type { MobileWebShellSessionState } from './mobile-web-shell-session-contract' -import type { ReactTestRenderer } from 'react-test-renderer' - -const renderScreen = (state: MobileWebShellSessionState): Promise => - mountScreen(MobileWebShellScreen, dependencies, state) - -afterEach(harness.unmountRenderedScreens) - -beforeEach(() => { - harness.resetScreenDependencies(dependencies) -}) - -// Give the page the whole window; its SafeAreaViews pad from init insets like native screens. -describe('a page that owns its safe area', () => { - async function openPage(sessionId: string) { - dependencies.client = createFakeRpcClient() - const tree = await renderScreen(readyState(sessionId)) - await act(async () => { - byName(tree, 'ShellViewProbe')[0]?.props.onBridgeMessage({ - nativeEvent: { json: clientFrame({ type: 'ready' }) } - }) - }) - const root = () => tree.root.find((node) => node.props.testID === 'mobile-web-shell-ready') - const initInsets = () => - dependencies.posted.flatMap((json) => { - const read = readBridgeHostMessage(json) - return read.ok && read.message.type === 'init' ? [read.message.safeAreaInsets ?? null] : [] - }) - return { tree, root, initInsets } - } - const ownedPage = openPage - const WINDOW = { top: 44, right: 0, bottom: 8, left: 0 } - - it('draws the view edge-to-edge and hands the page the insets it now sits under', async () => { - const page = await ownedPage('session-owned') - expect(page.root().props.style[1]).toEqual({ paddingTop: 0 }) - expect(page.initInsets()).toEqual([WINDOW]) - }) - - it('gives the status bar strip to the update banner while it shows', async () => { - dependencies.updateNotice = 'update-failed' - const page = await ownedPage('session-owned-banner') - expect(page.root().props.style[1]).toEqual({ paddingTop: 44 }) - expect(page.initInsets()).toEqual([{ ...WINDOW, top: 0 }]) - const dismiss = byName(page.tree, 'Pressable').find( - (node) => node.props.accessibilityLabel === 'Dismiss notice' - ) - expect(dismiss).toBeDefined() - await act(async () => { - dismiss?.props.onPress() - }) - expect(page.root().props.style[1]).toEqual({ paddingTop: 0 }) - expect(page.initInsets()).toEqual([{ ...WINDOW, top: 0 }, WINDOW]) - }) -}) diff --git a/mobile/src/mobile-web-shell/mobile-web-shell-session-grants.test.ts b/mobile/src/mobile-web-shell/mobile-web-shell-session-grants.test.ts deleted file mode 100644 index d62c374c7b7..00000000000 --- a/mobile/src/mobile-web-shell/mobile-web-shell-session-grants.test.ts +++ /dev/null @@ -1,107 +0,0 @@ -import { describe, expect, it } from 'vitest' -import type { - CachedGeneration, - MobileWebShellManifestFacts -} from './mobile-web-shell-session-contract' -import { - CACHED, - MANIFEST, - MANIFEST_WIRE, - PAGE_ROUTES, - awaitingManifest, - manifestFacts, - run, - LINK_LOST -} from './mobile-web-shell-session-test-fixtures' - -// Fallback must restore cached routes/grants; the replacement manifest must not grant old bytes capabilities they never declared. -describe('falling back to the cached generation after a failed download', () => { - const cachedOnlyNavigate: CachedGeneration = { ...CACHED, routes: PAGE_ROUTES } - // Use a distinct build id to force download instead of the same-build cache path. - const manifestWithClipboard: MobileWebShellManifestFacts = manifestFacts({ - ...MANIFEST_WIRE, - buildId: 'd'.repeat(64), - routes: [{ pathname: '/h/[hostId]', grants: ['navigate', 'native.clipboard.read'] }] - }) - - it('opens it under its own grants, not the ones the newer manifest declared', () => { - const fetching = run(awaitingManifest(cachedOnlyNavigate).session, { - type: 'manifest-read', - manifest: manifestWithClipboard - }) - expect([...fetching.session.routeGrants]).toEqual(['navigate', 'native.clipboard.read']) - const step = run(fetching.session, { type: 'download-failed', cause: LINK_LOST }) - expect(step.session.state.kind).toBe('activating') - expect([...step.session.routeGrants]).toEqual(['navigate']) - }) - - it('carries a verb declared in the manifest through to the session grants', () => { - const step = run(awaitingManifest(null).session, { - type: 'manifest-read', - manifest: manifestFacts({ - ...MANIFEST_WIRE, - routes: [{ pathname: '/h/[hostId]', grants: ['navigate', 'native.clipboard.write'] }] - }) - }) - expect([...step.session.routeGrants]).toEqual(['navigate', 'native.clipboard.write']) - }) -}) - -// Carry pageRouteGrants through downloads too; otherwise first installs/updates treat every target as unpaired and hand all hops to native. -describe('the route grants a downloaded generation is activated under', () => { - const TWO_ROUTES = [ - { pathname: '/h/[hostId]', grants: ['navigate', 'storage'] }, - { pathname: '/h/[hostId]/tasks', grants: ['navigate', 'native.clipboard.write'] } - ] - const DOWNLOADED: MobileWebShellManifestFacts = manifestFacts({ - ...MANIFEST_WIRE, - buildId: 'c'.repeat(64), - routes: TWO_ROUTES - }) - - function activate(session: Parameters[0], manifest: MobileWebShellManifestFacts) { - return run( - session, - { type: 'manifest-read', manifest }, - { type: 'download-staged' }, - { - type: 'activated', - generationDirectory: '/cache/gen', - sessionId: 'session-downloaded', - buildId: manifest.buildId, - totalBytes: manifest.totalBytes, - elapsedMs: 9 - } - ) - } - - it('is the manifest it downloaded, on a cold cache', () => { - const step = activate(awaitingManifest(null).session, DOWNLOADED) - expect(step.session.state.kind).toBe('ready') - expect(step.session.pageRouteGrants).toEqual(TWO_ROUTES) - }) - - it('is the manifest it matched, on a cached hit', () => { - const step = run(awaitingManifest(CACHED).session, { - type: 'manifest-read', - manifest: MANIFEST - }) - expect(step.session.state.kind).toBe('activating') - expect(step.session.pageRouteGrants).toEqual(PAGE_ROUTES) - }) - - it("replaces the previous generation's entries when the generation changes", () => { - // Seed older pairs so a missed update exposes stale grants as well as empty defaults. - const first = run(awaitingManifest(CACHED).session, { - type: 'manifest-read', - manifest: MANIFEST - }) - expect(first.session.pageRouteGrants).toEqual(PAGE_ROUTES) - const step = activate( - run(first.session, { type: 'retry-pressed' }, { type: 'cache-read', generation: null }) - .session, - DOWNLOADED - ) - expect(step.session.pageRouteGrants).toEqual(TWO_ROUTES) - }) -}) diff --git a/mobile/src/mobile-web-shell/mobile-web-shell-session.test.ts b/mobile/src/mobile-web-shell/mobile-web-shell-session.test.ts index 9e9e4764106..8c1b0a31e56 100644 --- a/mobile/src/mobile-web-shell/mobile-web-shell-session.test.ts +++ b/mobile/src/mobile-web-shell/mobile-web-shell-session.test.ts @@ -8,162 +8,11 @@ import { readySession, run, started, - BUNDLE_REFUSED, - LINK_LOST, - withoutRecord + BUNDLE_REFUSED } from './mobile-web-shell-session-test-fixtures' import { shellPageFrame } from './shell-page-frame' -const NO_BUNDLE_WALL = { kind: 'wall', verdict: { kind: 'blocked', reason: 'bundle-unavailable' } } - -describe('the gates decide whether a step is taken at all', () => { - it('picks the flow back up if that status ever becomes readable', () => { - const unreadable = started({ statusReadable: false, hostCapabilities: [] }) - const step = run(unreadable.session, { type: 'gates-changed', gates: gates() }) - expect(step.session.state).toEqual({ kind: 'checking' }) - expect(step.effects).toEqual([{ kind: 'open-cache' }]) - }) -}) - -describe('the offline rule', () => { - it('opens a cache read that lands mid-dial without asking for the manifest', () => { - const dialling = run(started().session, { - type: 'gates-changed', - gates: gates({ reachability: 'connecting' }) - }) - const step = run(dialling.session, { type: 'cache-read', generation: CACHED }) - expect(step.session.state).toEqual({ kind: 'activating', source: 'cache' }) - expect(step.effects).toEqual([ - { - kind: 'open-generation', - directory: CACHED.directory, - buildId: CACHED.buildId, - totalBytes: CACHED.totalBytes - } - ]) - }) - - it('restarts the flow when the host becomes reachable while offline is showing', () => { - const offline = run(started({ reachability: 'unreachable' }).session, { - type: 'cache-read', - generation: null - }) - const step = run(offline.session, { type: 'gates-changed', gates: gates() }) - expect(step.effects).toEqual([{ kind: 'open-cache' }]) - }) -}) - -describe('the connected flow', () => { - it('opens a same-build hit without paging, under the fresh grants', () => { - // Use unservable cached routes to prove fresh manifest grants decide the online same-build session. - const stale = { ...CACHED, routes: [{ pathname: '/h/[hostId]', grants: ['teleport'] }] } - const step = run(awaitingManifest(stale).session, { type: 'manifest-read', manifest: MANIFEST }) - expect(step.session.state).toEqual({ kind: 'activating', source: 'cache' }) - // Opening must not rewrite the manifest while the native view reads it. - expect(step.effects).toEqual([ - { - kind: 'open-generation', - directory: CACHED.directory, - buildId: CACHED.buildId, - totalBytes: CACHED.totalBytes - } - ]) - expect(step.session.routeGrants).toEqual(['navigate']) - }) -}) - -describe('a read the link cut short falls back to what is on disk', () => { - function manifestInFlight() { - return awaitingManifest(CACHED) - } - - it('opens the cached generation when the socket drops before the reachability change does', () => { - const step = run(manifestInFlight().session, { type: 'download-failed', cause: LINK_LOST }) - expect(step.session.state).toEqual({ kind: 'activating', source: 'cache' }) - expect(withoutRecord(step.effects)).toEqual([ - { - kind: 'open-generation', - directory: CACHED.directory, - buildId: CACHED.buildId, - totalBytes: CACHED.totalBytes - } - ]) - const ready = run(step.session, { - type: 'activated', - generationDirectory: CACHED.directory, - sessionId: 'session-one', - buildId: CACHED.buildId, - totalBytes: CACHED.totalBytes, - elapsedMs: 12 - }) - expect(ready.session.state).toMatchObject({ kind: 'ready', buildId: CACHED.buildId }) - }) -}) - -describe('a displayed generation is not restarted by the gates', () => { - it.each(['connected', 'unreachable', 'connecting'] as const)( - 'keeps a ready session when reachability becomes %s', - (reachability) => { - const ready = readySession() - const step = run(ready.session, { type: 'gates-changed', gates: gates({ reachability }) }) - expect(step.session.state).toEqual(ready.session.state) - expect(step.effects).toEqual([]) - } - ) - - it('keeps a wall and a terminal failure', () => { - const wall = started({ hostCapabilities: [] }) - expect(run(wall.session, { type: 'gates-changed', gates: gates() }).effects).toEqual([]) - const failed = run(awaitingManifest(null).session, { - type: 'download-failed', - cause: BUNDLE_REFUSED - }) - expect(run(failed.session, { type: 'gates-changed', gates: gates() }).effects).toEqual([]) - }) -}) - describe('recovery follows the shell view contract', () => { - it('takes a recovery through the gate rather than back to a manifest check', () => { - const ready = readySession() - // Store unreadable reconnect gates under ready without restarting the running workspace. - const stale = run(ready.session, { - type: 'gates-changed', - gates: gates({ statusReadable: false, hostCapabilities: [] }) - }) - expect(stale.session.state).toMatchObject({ kind: 'ready' }) - const step = run(stale.session, { type: 'shell-failed', reason: 'generation-unreadable' }) - expect(step.session.state).toEqual({ - kind: 'failed', - reason: 'status-unreadable', - retriedOnce: true - }) - expect(step.effects).toEqual([{ kind: 'delete-cache' }]) - const rearmed = run(step.session, { type: 'gates-changed', gates: gates() }) - expect(rearmed.session.state).toEqual({ kind: 'checking' }) - expect(rearmed.effects).toEqual([{ kind: 'open-cache' }]) - }) - - it('walls a ready page as soon as the host stops serving a bundle', () => { - const stale = run(readySession().session, { - type: 'gates-changed', - gates: gates({ hostCapabilities: [] }) - }) - expect(stale.session.state).toEqual(NO_BUNDLE_WALL) - }) - - it('deletes the suspect cache and reads it again when the recovery lands mid-reconnect', () => { - const dialling = run(readySession().session, { - type: 'gates-changed', - gates: gates({ reachability: 'connecting' }) - }) - const step = run(dialling.session, { type: 'shell-failed', reason: 'generation-unreadable' }) - expect(step.session.state).toEqual({ kind: 'checking' }) - expect(step.effects).toEqual([{ kind: 'delete-cache' }, { kind: 'open-cache' }]) - expect(run(step.session, { type: 'gates-changed', gates: gates() }).effects).toEqual([ - { kind: 'open-cache' } - ]) - }) - it('is terminal the second time an unreadable generation needs a refetch', () => { const unreadable = { type: 'shell-failed', reason: 'generation-unreadable' } as const const first = run(readySession().session, unreadable) @@ -263,24 +112,6 @@ describe('a result from a superseded flow reports into nothing', () => { ]) }) - it('drops the manifest of a run the socket drop replaced, so no download is asked for', () => { - const first = awaitingManifest(null) - const restarted = run(first.session, { - type: 'gates-changed', - gates: gates({ reachability: 'unreachable' }) - }) - const stale = run(restarted.session, { - type: 'manifest-read', - flow: first.session.flow, - manifest: MANIFEST - }) - expect(stale.effects).toEqual([]) - expect(stale.session.state).toEqual({ kind: 'checking' }) - const current = run(stale.session, { type: 'cache-read', generation: null }) - expect(current.session.state).toEqual({ kind: 'offline' }) - expect(current.effects).toEqual([]) - }) - it('keeps a workspace on screen when the manifest read the drop abandoned finally rejects', () => { // Settle the abandoned RPC only after socket loss opens cache, exposing any missing flow guard. const inFlight = awaitingManifest(CACHED) @@ -308,20 +139,6 @@ describe('a result from a superseded flow reports into nothing', () => { }) expect(late.session.state).toEqual(ready.session.state) }) - - it('applies a remount of the current flow and ignores one from a replaced run', () => { - const ready = readySession() - const remounting = run(ready.session, { type: 'shell-failed', reason: 'render-process-gone' }) - const stale = run(remounting.session, { - type: 'remounted', - flow: remounting.session.flow - 1, - sessionId: 'session-stale' - }) - expect(stale.session.state).toEqual(ready.session.state) - expect( - run(stale.session, { type: 'remounted', sessionId: 'session-two' }).session.state - ).toMatchObject({ sessionId: 'session-two' }) - }) }) describe('a reconnect does not refill the remount budget', () => { @@ -356,98 +173,10 @@ describe('only the state that mounted the view hears the view', () => { { kind: 'read-manifest' } ]) }) - - it('leaves a wall standing when a view that is no longer mounted reports a failure', () => { - const wall = started({ hostCapabilities: [] }) - const step = run(wall.session, { type: 'shell-failed', reason: 'isolation-unavailable' }) - expect(step.session.state).toEqual(wall.session.state) - expect(step.effects).toEqual([]) - }) -}) - -describe('a gates change that says nothing new starts nothing', () => { - it('leaves a check in flight alone rather than sweeping and reading a second time', () => { - const checking = started() - const again = run(checking.session, { type: 'gates-changed', gates: gates() }) - expect(again.effects).toEqual([]) - expect(again.session.flow).toBe(checking.session.flow) - }) - - it('keeps a first open checking while the dial retries, then says offline when it stops', () => { - const retrying = gates({ reachability: 'unreachable', retrying: true }) - const waiting = run(started(retrying).session, { type: 'cache-read', generation: null }) - expect(waiting.session.state).toEqual({ kind: 'checking' }) - - const gaveUp = run(waiting.session, { - type: 'gates-changed', - gates: gates({ reachability: 'unreachable' }) - }) - expect(gaveUp.effects).toEqual([{ kind: 'open-cache' }]) - const offline = run(gaveUp.session, { type: 'cache-read', generation: null }) - expect(offline.session.state).toEqual({ kind: 'offline' }) - }) - - it('still opens a cached page at once while the dial retries', () => { - const retrying = gates({ reachability: 'unreachable', retrying: true }) - const step = run(started(retrying).session, { type: 'cache-read', generation: CACHED }) - const offline = gates({ reachability: 'unreachable' }) - const unretried = run(started(offline).session, { type: 'cache-read', generation: CACHED }) - expect(step.session.state).toEqual(unretried.session.state) - expect(step.effects).toEqual(unretried.effects) - expect(step.session.state.kind).toBe('activating') - }) - - it('holds the offline screen through a reconnect cycle that never reaches the host', () => { - const offline = run(started({ reachability: 'unreachable' }).session, { - type: 'cache-read', - generation: null - }) - const cycled = run( - offline.session, - { type: 'gates-changed', gates: gates({ reachability: 'unreachable' }) }, - { type: 'gates-changed', gates: gates({ reachability: 'unreachable' }) } - ) - expect(cycled.effects).toEqual([]) - expect(cycled.session.state).toEqual({ kind: 'offline' }) - }) - - it('restarts on the verdict that changed, not on the object that was rebuilt', () => { - const checking = started({ statusPending: true }) - const settled = run(checking.session, { type: 'gates-changed', gates: gates() }) - expect(settled.effects).toEqual([{ kind: 'open-cache' }]) - }) - - it('walls a check in flight when the host stops serving a bundle', () => { - const checking = started() - const step = run(checking.session, { - type: 'gates-changed', - gates: gates({ hostCapabilities: [] }) - }) - expect(step.session.state).toEqual(NO_BUNDLE_WALL) - }) }) // A finished WebView load can still have failed script evaluation; only page ready proves its code ran. describe('the page has to speak for the document that loaded', () => { - it('arms nothing when the page spoke first, because there is nothing left to wait for', () => { - const step = run(readySession().session, { type: 'page-ready' }, { type: 'document-loaded' }) - expect(step.effects).toEqual([]) - expect(step.session.pageReady).toBe(true) - }) - - it('remounts the same files when the wait expires', () => { - const ready = run(readySession().session, { type: 'document-loaded' }) - const step = run(ready.session, { type: 'page-ready-deadline' }) - expect(step.effects).toEqual([{ kind: 'remount' }]) - expect(step.session.retriedOnce).toBe(false) - }) - - it('retires both waits once the page speaks', () => { - expect(run(readySession().session, { type: 'page-ready' }).effects).toEqual([ - { kind: 'cancel-deadlines' } - ]) - }) - it('does nothing when the wait expires after the page has spoken', () => { const step = run( readySession().session, @@ -459,26 +188,6 @@ describe('the page has to speak for the document that loaded', () => { expect(step.session.state.kind).toBe('ready') }) - it('drops the expiry of a wait a restarted flow left behind', () => { - const ready = run(readySession().session, { type: 'document-loaded' }) - const step = run( - ready.session, - { type: 'retry-pressed' }, - { type: 'page-ready-deadline', flow: ready.session.flow } - ) - expect(step.session.state.kind).toBe('checking') - expect(step.session.retriedOnce).toBe(false) - }) - - it('makes the second document prove itself, rather than riding the first one word', () => { - const spoken = run(readySession().session, { type: 'page-ready' }) - const remounted = run(spoken.session, { type: 'remounted', sessionId: 'session-two' }) - expect(remounted.session.pageReady).toBe(false) - expect(run(remounted.session, { type: 'document-loaded' }).effects).toEqual([ - { kind: 'await-page-ready' } - ]) - }) - it('leaves a remounted document its own wait when the first one expires late', () => { const first = run(readySession().session, { type: 'document-loaded' }, { type: 'page-ready' }) const armed = first.session.flow @@ -502,42 +211,10 @@ describe('the view has to finish the document it was given', () => { const step = run(started.session, { type: 'document-load-deadline' }) expect(step.effects).toEqual([{ kind: 'remount' }]) }) - - it('does nothing once the document finished or the page spoke', () => { - const loaded = run(readySession().session, { type: 'document-loaded' }) - expect(run(loaded.session, { type: 'document-load-deadline' }).effects).toEqual([]) - const spoke = run(readySession().session, { type: 'page-ready' }) - expect(run(spoke.session, { type: 'document-load-deadline' }).session.state.kind).toBe('ready') - }) - - it('drops the wait a replaced document left behind', () => { - const ready = readySession() - const armed = ready.session.flow - const started = run(ready.session, { type: 'document-started' }) - const step = run(started.session, { type: 'document-load-deadline', flow: armed }) - expect(step.effects).toEqual([]) - expect(step.session.state.kind).toBe('ready') - }) }) // Neither WebView commit nor page ready proves paint; keep the cover until the page reports a frame. describe('the page reporting a frame on screen', () => { - it('keeps the frame covered past ready until the report', () => { - const spoken = run(readySession().session, { type: 'page-ready' }) - expect(spoken.session.pagePainted).toBe(false) - expect(shellPageFrame(spoken.session)).toBe('unpainted') - const painted = run(spoken.session, { type: 'page-painted' }) - expect(painted.session.pagePainted).toBe(true) - expect(shellPageFrame(painted.session)).toBe('painted') - }) - - it('makes a remounted document report its own frame', () => { - const painted = run(readySession().session, { type: 'page-ready' }, { type: 'page-painted' }) - const remounted = run(painted.session, { type: 'remounted', sessionId: 'session-two' }) - expect(remounted.session.pagePainted).toBe(false) - expect(shellPageFrame(remounted.session)).toBe('unpainted') - }) - it('makes the document that replaced a painted one inside this mount report its own frame', () => { const painted = run(readySession().session, { type: 'page-ready' }, { type: 'page-painted' }) expect(shellPageFrame(painted.session)).toBe('painted') @@ -547,29 +224,6 @@ describe('the page reporting a frame on screen', () => { expect(shellPageFrame(reasked.session)).toBe('unpainted') expect(shellPageFrame(run(reasked.session, { type: 'page-painted' }).session)).toBe('painted') }) - - it('retires the wait the document it replaced armed', () => { - const loaded = run(readySession().session, { type: 'document-loaded' }) - expect(loaded.effects).toEqual([{ kind: 'await-page-ready' }]) - const armed = loaded.session.flow - const spoken = run(loaded.session, { type: 'page-ready' }) - const restarted = run(spoken.session, { type: 'document-started' }) - const expired = run(restarted.session, { type: 'page-ready-deadline', flow: armed }) - expect(expired.session.state.kind).toBe('ready') - const reloaded = run(restarted.session, { type: 'document-loaded' }) - expect(reloaded.effects).toEqual([{ kind: 'await-page-ready' }]) - }) - - it('keeps the frame of a document that repeats its own handshake', () => { - const painted = run( - readySession().session, - { type: 'page-ready' }, - { type: 'page-painted' }, - { type: 'page-ready' } - ) - expect(painted.session.pagePainted).toBe(true) - expect(shellPageFrame(painted.session)).toBe('painted') - }) }) describe('a cached page opened before the verdict', () => { @@ -600,27 +254,6 @@ describe('a cached page opened before the verdict', () => { expect(staged.effects).toEqual([{ kind: 'stage-update' }]) }) - it('lets the desktop manifest decide when the verdict puts it outside the window', () => { - const blocked = run(openedWhileDialling().session, { - type: 'gates-changed', - gates: gates({ hostStatus: { protocolVersion: 10, minCompatibleMobileVersion: 99 } }) - }) - expect(blocked.session.state).toEqual({ kind: 'checking' }) - expect(blocked.effects).toEqual([{ kind: 'open-cache' }]) - }) - - it('shows the status failure when the status it waited for cannot be read', () => { - const unreadable = run(openedWhileDialling().session, { - type: 'gates-changed', - gates: gates({ statusReadable: false, hostCapabilities: [] }) - }) - expect(unreadable.session.state).toEqual({ - kind: 'failed', - reason: 'status-unreadable', - retriedOnce: false - }) - }) - it('walls a page that already talked when a new connection puts it outside the window', () => { const talked = run(openedWhileDialling().session, { type: 'gates-changed', gates: gates() }) const reconnected = run( diff --git a/mobile/src/mobile-web-shell/mobile-web-shell-update-failure-record.test.ts b/mobile/src/mobile-web-shell/mobile-web-shell-update-failure-record.test.ts deleted file mode 100644 index 1a878da8aa3..00000000000 --- a/mobile/src/mobile-web-shell/mobile-web-shell-update-failure-record.test.ts +++ /dev/null @@ -1,228 +0,0 @@ -import { describe, expect, it } from 'vitest' -import { - BUNDLE_REFUSED, - CACHED, - CACHED_BELOW_HOST_FLOOR, - LINK_LOST, - MANIFEST_WIRE, - awaitingManifest, - gates, - manifestFacts, - run -} from './mobile-web-shell-session-test-fixtures' -import type { MobileWebShellStep } from './mobile-web-shell-session-contract' -import type { MobileWebShellUpdateFailureFacts } from './mobile-web-shell-update-failure' - -// Require one record per failed-read outcome with cause/builds/verdict; release console logs cannot provide this evidence. -const NEWER = manifestFacts({ ...MANIFEST_WIRE, buildId: 'c'.repeat(64) }) - -function recorded(step: MobileWebShellStep): MobileWebShellUpdateFailureFacts[] { - return step.effects.flatMap((effect) => - effect.kind === 'record-update-failure' ? [effect.failure] : [] - ) -} - -function refusedUnder( - patch: Parameters[0], - cached = CACHED, - cause = BUNDLE_REFUSED -): MobileWebShellStep { - const fetching = run(awaitingManifest(cached).session, { type: 'manifest-read', manifest: NEWER }) - const moved = run(fetching.session, { type: 'gates-changed', gates: gates(patch) }) - return run(moved.session, { type: 'download-failed', cause }) -} - -describe('every exit from a failed update read leaves one record', () => { - it('nothing on disk: the failure screen, with the offered generation named', () => { - const fetching = run(awaitingManifest(null).session, { type: 'manifest-read', manifest: NEWER }) - const step = run(fetching.session, { type: 'download-failed', cause: BUNDLE_REFUSED }) - expect(step.session.state).toMatchObject({ kind: 'failed', reason: 'download-failed' }) - expect(recorded(step)).toEqual([ - { - reason: 'asset-checksum-mismatch', - hostCode: null, - offeredBuildId: NEWER.buildId, - cachedBuildId: null, - outcome: 'failed', - wall: null - } - ]) - }) - - it('the manifest read itself failed: nothing was offered, the cached generation opens', () => { - const step = run(awaitingManifest(CACHED).session, { - type: 'download-failed', - cause: { reason: 'host-refused', hostCode: 'mobile_web_bundle_read_limited' } - }) - expect(step.session.state).toEqual({ kind: 'activating', source: 'cache' }) - expect(recorded(step)).toEqual([ - { - reason: 'host-refused', - hostCode: 'mobile_web_bundle_read_limited', - offeredBuildId: null, - cachedBuildId: CACHED.buildId, - outcome: 'opened-cached', - wall: null - } - ]) - }) - - it('a refused download falls back to the cached generation under the notice', () => { - const step = refusedUnder({}) - expect(step.session.updateNotice).toBe('update-failed') - expect(recorded(step)).toEqual([ - { - reason: 'asset-checksum-mismatch', - hostCode: null, - offeredBuildId: NEWER.buildId, - cachedBuildId: CACHED.buildId, - outcome: 'opened-cached', - wall: null - } - ]) - }) - - it('a link that went is recorded too, though the screen carries no notice for it', () => { - const step = refusedUnder({}, CACHED, LINK_LOST) - expect(step.session.updateNotice).toBeNull() - expect(recorded(step)).toMatchObject([{ reason: 'connection-lost', outcome: 'opened-cached' }]) - }) - - it('no client to ask is recorded as its own reason', () => { - const step = refusedUnder({}, CACHED, { reason: 'no-connection', hostCode: null }) - expect(recorded(step)).toMatchObject([{ reason: 'no-connection', outcome: 'opened-cached' }]) - }) - - it('a cached generation the host has moved past is walled, and the verdict is kept', () => { - const step = refusedUnder({}, CACHED_BELOW_HOST_FLOOR) - expect(step.session.state).toMatchObject({ kind: 'wall' }) - expect(recorded(step)).toMatchObject([ - { outcome: 'wall', wall: 'bundle-too-old-for-host', cachedBuildId: CACHED.buildId } - ]) - }) - - it('a cached generation that never carried this route shows the download failure', () => { - const step = refusedUnder({}, { ...CACHED, routes: [] }) - expect(step.session.state).toMatchObject({ kind: 'failed', reason: 'download-failed' }) - expect(recorded(step)).toMatchObject([{ outcome: 'failed', wall: null }]) - }) - - it('gates gone offline under the fetch open the cache unjudged', () => { - const step = refusedUnder({ reachability: 'unreachable' }, CACHED_BELOW_HOST_FLOOR) - expect(step.session.state).toEqual({ kind: 'activating', source: 'cache' }) - expect(recorded(step)).toMatchObject([{ outcome: 'opened-cached', wall: null }]) - }) - - it('gates with an unreadable status answer the status failure', () => { - const step = refusedUnder({ statusReadable: false }) - expect(step.session.state).toMatchObject({ kind: 'failed', reason: 'status-unreadable' }) - expect(recorded(step)).toMatchObject([{ outcome: 'failed' }]) - }) - - it('gates that dropped the bundle capability wall the host', () => { - const step = refusedUnder({ hostCapabilities: [] }) - expect(step.session.state).toMatchObject({ kind: 'wall' }) - expect(recorded(step)).toMatchObject([{ outcome: 'wall', wall: 'bundle-unavailable' }]) - }) - - it('gates still dialling or pending open the cached generation before the verdict', () => { - expect(recorded(refusedUnder({ reachability: 'connecting' }))).toMatchObject([ - { outcome: 'opened-cached' } - ]) - expect(recorded(refusedUnder({ statusPending: true }))).toMatchObject([ - { outcome: 'opened-cached' } - ]) - }) - - it('a stale flow reports into nothing and records nothing', () => { - const fetching = run(awaitingManifest(CACHED).session, { - type: 'manifest-read', - manifest: NEWER - }) - const step = run(fetching.session, { - type: 'download-failed', - flow: fetching.session.flow - 1, - cause: BUNDLE_REFUSED - }) - expect(recorded(step)).toEqual([]) - }) - - it('a new flow forgets the generation the last one was offered', () => { - const fetching = run(awaitingManifest(null).session, { type: 'manifest-read', manifest: NEWER }) - const failed = run(fetching.session, { type: 'download-failed', cause: BUNDLE_REFUSED }) - const retried = run( - failed.session, - { type: 'retry-pressed' }, - { type: 'cache-read', generation: null } - ) - const step = run(retried.session, { type: 'download-failed', cause: LINK_LOST }) - expect(recorded(step)).toMatchObject([{ offeredBuildId: null }]) - }) -}) - -describe('a newer generation committed clears the record, and nothing else does', () => { - function forgets(step: MobileWebShellStep): boolean { - return step.effects.some((effect) => effect.kind === 'forget-update-failures') - } - - function activated(buildId: string) { - return { - type: 'activated', - generationDirectory: '/cache/gen', - sessionId: 'session-one', - buildId, - totalBytes: 1, - elapsedMs: 1 - } as const - } - - it('forgets once the offered generation lands', () => { - const fetching = run(awaitingManifest(CACHED).session, { - type: 'manifest-read', - manifest: NEWER - }) - const step = run(fetching.session, { type: 'download-staged' }, activated(NEWER.buildId)) - expect(step.session.state).toMatchObject({ kind: 'ready', buildId: NEWER.buildId }) - expect(forgets(step)).toBe(true) - }) - - it('forgets when the host moved between the manifest read and the fetch', () => { - // Fetch rereads the manifest, so a committed download can be newer than the offered build and must still clear failure history. - const MOVED = 'd'.repeat(64) - const fetching = run(awaitingManifest(CACHED).session, { - type: 'manifest-read', - manifest: NEWER - }) - const step = run(fetching.session, { type: 'download-staged' }, activated(MOVED)) - expect(step.session.state).toMatchObject({ kind: 'ready', buildId: MOVED }) - expect(forgets(step)).toBe(true) - }) - - it('keeps the record when the fallback opens the cached generation', () => { - const fetching = run(awaitingManifest(CACHED).session, { - type: 'manifest-read', - manifest: NEWER - }) - const failed = run(fetching.session, { type: 'download-failed', cause: BUNDLE_REFUSED }) - expect(forgets(run(failed.session, activated(CACHED.buildId)))).toBe(false) - }) - - it('keeps it for a same-build cache hit, which committed nothing', () => { - const hit = run(awaitingManifest(CACHED).session, { - type: 'manifest-read', - manifest: manifestFacts(MANIFEST_WIRE) - }) - expect(forgets(run(hit.session, activated(CACHED.buildId)))).toBe(false) - }) - - it('keeps it for an offline open', () => { - const offline = run( - awaitingManifest(null).session, - { type: 'gates-changed', gates: gates({ reachability: 'unreachable' }) }, - { type: 'retry-pressed' }, - { type: 'cache-read', generation: CACHED } - ) - expect(offline.session.state).toEqual({ kind: 'activating', source: 'cache' }) - expect(forgets(run(offline.session, activated(CACHED.buildId)))).toBe(false) - }) -}) diff --git a/mobile/src/mobile-web-shell/shell-failure-recovery.test.ts b/mobile/src/mobile-web-shell/shell-failure-recovery.test.ts index a96422228d4..ca3b21c13df 100644 --- a/mobile/src/mobile-web-shell/shell-failure-recovery.test.ts +++ b/mobile/src/mobile-web-shell/shell-failure-recovery.test.ts @@ -19,12 +19,6 @@ describe('a failed document', () => { }) }) - it('still remounts silently when the renderer dies after a page failure was remounted', () => { - const lost = run(readySession().session, DOCUMENT_FAILED, REMOUNTED, RENDERER_GONE) - expect(lost.effects).toEqual([{ kind: 'remount' }]) - expect(lost.session.state.kind).toBe('ready') - }) - // Refilling on paint would loop a page that paints and then faults: remount, paint, fault, forever. it('fails visibly when the remounted page paints and then faults again', () => { const painted = { type: 'page-painted' } as const @@ -39,21 +33,9 @@ describe('a failed document', () => { expect(failed.effects).toEqual([]) expect(failed.session.state).toMatchObject({ kind: 'failed', reason: 'document-load-failed' }) }) - - it('still remounts a failed document after a renderer-loss remount', () => { - const failed = run(readySession().session, RENDERER_GONE, REMOUNTED, DOCUMENT_FAILED) - expect(failed.effects).toEqual([{ kind: 'remount' }]) - }) }) describe('try again after a failed document', () => { - it('deletes the files that failed before checking the host again', () => { - const failed = run(readySession().session, DOCUMENT_FAILED, REMOUNTED, DOCUMENT_FAILED) - const retried = run(failed.session, { type: 'retry-pressed' }) - expect(retried.effects).toEqual([{ kind: 'delete-cache' }, { kind: 'open-cache' }]) - expect(retried.session.pageRemountedOnce).toBe(false) - }) - it('keeps the cache when the renderer was what failed', () => { const failed = run(readySession().session, RENDERER_GONE, REMOUNTED, RENDERER_GONE) expect(failed.session.state).toMatchObject({ kind: 'failed', reason: 'render-process-gone' }) diff --git a/mobile/src/mobile-web-shell/shell-lifecycle-log.test.ts b/mobile/src/mobile-web-shell/shell-lifecycle-log.test.ts index 768b385fac8..59d39dec987 100644 --- a/mobile/src/mobile-web-shell/shell-lifecycle-log.test.ts +++ b/mobile/src/mobile-web-shell/shell-lifecycle-log.test.ts @@ -1,270 +1,10 @@ import { describe, expect, it, vi } from 'vitest' -import { buildConnectionDiagnosticsReport } from '../diagnostics/connection-diagnostics-report' -import type { ConnectionLogEntry } from '../transport/types' -import { - CACHED, - MANIFEST, - createMobileWebShellSession, - gates, - ROUTE, - stamp -} from './mobile-web-shell-session-test-fixtures' -import { reduceMobileWebShellSession } from './mobile-web-shell-session' -import type { - MobileWebShellSession, - MobileWebShellSessionEvent -} from './mobile-web-shell-session-contract' -import { connectionLogStore } from '../transport/persisted-connection-log-store' -import { bridgeDiagnosticLine, frameWithoutHostLine } from './shell-bridge-log-lines' -import { recordShellLifecycleLine, type ShellLifecycleLine } from './shell-lifecycle-line-recorder' -import { - EMPTY_SHELL_LOG_TRACE, - pageFaultLine, - shellSessionStepLines, - shellStallLine, - traceShellStep, - type ShellLogTrace -} from './shell-lifecycle-log' +import { pageFaultLine } from './shell-lifecycle-log' vi.mock('@react-native-async-storage/async-storage', () => ({ default: { getItem: vi.fn(async () => null), setItem: vi.fn(async () => undefined) } })) -type Pending = Parameters[1] - -type Replayed = { - session: MobileWebShellSession - trace: ShellLogTrace - lines: ShellLifecycleLine[] -} - -function replay( - events: readonly Pending[], - from: Omit = { - session: createMobileWebShellSession(ROUTE), - trace: EMPTY_SHELL_LOG_TRACE - } -): Replayed { - let { session, trace } = from - const lines: ShellLifecycleLine[] = [] - for (const pending of events) { - const event: MobileWebShellSessionEvent = stamp(session.flow, pending) - const next = reduceMobileWebShellSession(session, event).session - trace = traceShellStep(trace, session, event, next) - lines.push(...shellSessionStepLines(session, event, next, trace)) - session = next - } - return { session, trace, lines } -} - -function stall(replayed: Omit): ShellLifecycleLine | null { - return shellStallLine(replayed.session.state, replayed.session, replayed.trace) -} - -const ACTIVATED = { - type: 'activated', - generationDirectory: '/Users/someone/Library/Caches/gen-1', - sessionId: 'session-one', - buildId: MANIFEST.buildId, - totalBytes: MANIFEST.totalBytes, - elapsedMs: 1234 -} as const - -const DOWNLOAD_OPEN: readonly Pending[] = [ - { type: 'gates-changed', gates: gates() }, - { type: 'cache-read', generation: null }, - { type: 'manifest-read', manifest: MANIFEST }, - { - type: 'fetch-progress', - completedAssets: 1, - totalAssets: MANIFEST.totalAssets, - receivedBytes: 10, - totalBytes: MANIFEST.totalBytes - }, - { - type: 'fetch-progress', - completedAssets: 2, - totalAssets: MANIFEST.totalAssets, - receivedBytes: 20, - totalBytes: MANIFEST.totalBytes - }, - { type: 'download-staged' }, - ACTIVATED -] - -function present(line: ShellLifecycleLine | null): ShellLifecycleLine[] { - expect(line).not.toBeNull() - return line === null ? [] : [line] -} - -function summary(lines: readonly ShellLifecycleLine[]): string[] { - return lines.map( - (line) => `${line.code} ${line.message}${line.detail ? ` | ${line.detail}` : ''}` - ) -} - -const PAGE_LOAD: readonly Pending[] = [ - { type: 'document-started' }, - { type: 'document-loaded' }, - { type: 'page-ready' } -] - -const BUILD = MANIFEST.buildId.slice(0, 8) - -describe('shell lifecycle log lines', () => { - it('writes exactly one line for a healthy cached open: the paint', () => { - const { lines } = replay([ - { type: 'gates-changed', gates: gates() }, - { type: 'cache-read', generation: CACHED }, - { type: 'manifest-read', manifest: MANIFEST }, - ACTIVATED, - ...PAGE_LOAD, - { type: 'page-ready' }, - { type: 'page-painted' }, - { type: 'page-painted' }, - { type: 'page-back-claim', claimed: true } - ]) - expect(summary(lines)).toEqual([ - `web-shell-page Web shell: page painted | source=cache build=${BUILD} activatedMs=1234` - ]) - }) - - it('adds only the download milestones to a downloading open, and no progress ticks', () => { - const { lines } = replay([...DOWNLOAD_OPEN, ...PAGE_LOAD, { type: 'page-painted' }]) - expect(summary(lines)).toEqual([ - `web-shell-flow Web shell: downloading app | ${MANIFEST.totalAssets} assets, ${MANIFEST.totalBytes} bytes`, - 'web-shell-flow Web shell: activating app | source=download', - `web-shell-page Web shell: page painted | source=download build=${BUILD} activatedMs=1234` - ]) - expect(JSON.stringify(lines)).not.toContain('/Users/someone') - }) - - it('logs the wall a host with no page earns', () => { - const { session, lines } = replay([ - { type: 'gates-changed', gates: gates({ hostCapabilities: [] }) } - ]) - expect(session.state.kind).toBe('wall') - expect(summary(lines)).toEqual([ - 'web-shell-flow Web shell: blocked by version check | reason=bundle-unavailable' - ]) - }) - - it('logs a missed ready deadline but not the remount it earns', () => { - const opened = replay(DOWNLOAD_OPEN) - const { lines } = replay([{ type: 'document-loaded' }, { type: 'page-ready-deadline' }], opened) - expect(summary(lines)).toEqual([ - 'web-shell-page Web shell: page never said ready before the deadline' - ]) - }) - - it('logs a document that never finished loading but not the remount it earns', () => { - const opened = replay(DOWNLOAD_OPEN) - const { lines } = replay( - [{ type: 'document-started' }, { type: 'document-load-deadline' }], - opened - ) - expect(summary(lines)).toEqual([ - 'web-shell-page Web shell: document never finished loading before the deadline' - ]) - }) - - it('logs a view failure but not the remount it earns', () => { - const opened = replay(DOWNLOAD_OPEN) - const { lines } = replay( - [ - { type: 'shell-failed', reason: 'render-process-gone' }, - { type: 'remounted', sessionId: 'session-two' } - ], - opened - ) - expect(summary(lines)).toEqual([ - 'web-shell-page Web shell: page load failed | reason=render-process-gone' - ]) - }) - - it('ignores results from a superseded flow', () => { - const opened = replay(DOWNLOAD_OPEN) - const { lines } = replay( - [ - { type: 'page-ready-deadline', flow: opened.session.flow - 1 }, - { ...ACTIVATED, flow: 0 } - ], - opened - ) - expect(lines).toEqual([]) - }) - - it('logs a failed download with its closed reason code', () => { - const { lines } = replay([ - { type: 'gates-changed', gates: gates() }, - { type: 'cache-read', generation: null }, - { type: 'download-failed', cause: { reason: 'connection-lost', hostCode: null } } - ]) - expect(summary(lines)).toEqual([ - 'web-shell-flow Web shell: app download failed | reason=connection-lost', - 'web-shell-flow Web shell: failed | reason=download-failed retried=no' - ]) - }) -}) - -describe('shell stall lines', () => { - it('names what a checking session waits on: the gates, then the cache', () => { - const fresh = replay([]) - expect(stall(fresh)).toMatchObject({ - code: 'web-shell-stalled', - message: 'Web shell: still checking host after 15s', - detail: 'gates=none cache=unread' - }) - expect( - stall(replay([{ type: 'gates-changed', gates: gates({ reachability: 'connecting' }) }])) - ).toMatchObject({ detail: 'gates=dialling cache=unread' }) - const opened = replay([{ type: 'gates-changed', gates: gates() }]) - expect(opened.session.state.kind).toBe('checking') - expect(stall(opened)).toMatchObject({ detail: 'gates=open cache=unread' }) - // With empty cache, trace alone distinguishes a manifest wait from an unfinished cache read. - const awaitingManifest = replay([{ type: 'cache-read', generation: null }], opened) - expect(stall(awaitingManifest)).toMatchObject({ detail: 'gates=open cache=read' }) - }) - - it('names how far a stalled download got', () => { - const fetching = replay(DOWNLOAD_OPEN.slice(0, 4)) - expect(stall(fetching)).toMatchObject({ - message: 'Web shell: download made no progress for 15s', - detail: `assets=1/${MANIFEST.totalAssets} bytes=10/${MANIFEST.totalBytes}` - }) - }) - - it('names an activation that never finished', () => { - expect(stall(replay(DOWNLOAD_OPEN.slice(0, 6)))).toMatchObject({ - message: 'Web shell: still activating after 15s', - detail: 'source=download' - }) - }) - - it('tells a page that keeps refusing init from one that took it and never drew', () => { - const opened = replay(DOWNLOAD_OPEN) - expect(stall(opened)).toMatchObject({ - message: 'Web shell: page has not drawn after 15s', - detail: `build=${BUILD} page ready=no readyAsks=0 documentLoaded=no` - }) - const refusing = replay([...PAGE_LOAD, { type: 'page-ready' }, { type: 'page-ready' }], opened) - expect(stall(refusing)).toMatchObject({ - detail: `build=${BUILD} page ready=yes readyAsks=3 documentLoaded=yes` - }) - const reloaded = replay([{ type: 'document-started' }, { type: 'page-ready' }], refusing) - expect(stall(reloaded)).toMatchObject({ - detail: `build=${BUILD} page ready=yes readyAsks=1 documentLoaded=no` - }) - expect(stall(replay([{ type: 'page-painted' }], reloaded))).toBeNull() - }) - - it('stays quiet for states nobody waits in', () => { - expect( - stall(replay([{ type: 'gates-changed', gates: gates({ hostCapabilities: [] }) }])) - ).toBeNull() - }) -}) - describe('shell failure details', () => { it('keeps device paths out of a page fault', () => { expect( @@ -276,119 +16,3 @@ describe('shell failure details', () => { ).toBe('TypeError: x is undefined at [path]') }) }) - -describe('recording shell lines', () => { - it('writes a flapping host line once until a different shell line is written', () => { - const host = 'flapping-host' - const checking = replay([ - { type: 'gates-changed', gates: gates({ reachability: 'unreachable' }) }, - { type: 'cache-read', generation: null }, - { type: 'gates-changed', gates: gates({ reachability: 'connecting' }) } - ]).lines - expect(summary(checking)).toEqual([ - 'web-shell-flow Web shell: host unreachable and no app cached', - 'web-shell-flow Web shell: checking host' - ]) - for (let cycle = 0; cycle < 3; cycle += 1) { - for (const line of checking) { - recordShellLifecycleLine(host, line) - } - } - const messages = () => connectionLogStore.get(host).map((entry) => entry.message) - expect(messages()).toEqual([ - 'Web shell: host unreachable and no app cached', - 'Web shell: checking host' - ]) - recordShellLifecycleLine(host, frameWithoutHostLine({ clientReady: true, snapshotReady: true })) - recordShellLifecycleLine(host, checking[1]!) - recordShellLifecycleLine('other-host', checking[1]!) - expect(messages().slice(2)).toEqual([ - 'Web shell: page frame with no bridge host', - 'Web shell: checking host' - ]) - expect(connectionLogStore.get('other-host')).toHaveLength(1) - }) -}) - -describe('shell lifecycle lines in the exported report', () => { - function entries(lines: readonly ShellLifecycleLine[]): ConnectionLogEntry[] { - return lines.map((line, index) => ({ id: `e${index}`, ts: 1_000 + index * 1_000, ...line })) - } - - it('shows where a connected session stalled without changing the connection verdict', () => { - const opened = replay(DOWNLOAD_OPEN) - const page = replay(PAGE_LOAD, opened) - const report = buildConnectionDiagnosticsReport({ - hostName: 'Desk', - endpoint: 'ws://192.168.1.2:6768', - state: 'connected', - reconnectAttempts: 0, - lastConnectedAt: 500, - platform: 'ios', - appVersion: '0.0.56', - bridgeProtocolVersion: 1, - entries: entries([...opened.lines, ...page.lines, ...present(stall(page))]), - nowMs: 60_000 - }) - expect(report).toContain('Bridge protocol: 1') - expect(report).toContain('Likely cause: Connection is healthy.') - expect(report).toContain('[web-shell-flow] Web shell: activating app') - expect(report).toContain( - `[warn] [web-shell-stalled] Web shell: page has not drawn after 15s — build=${BUILD} page ready=yes readyAsks=1 documentLoaded=yes` - ) - }) - - it('never reads shell lines as a connection failure', () => { - const failed = replay([ - { type: 'gates-changed', gates: gates() }, - { type: 'cache-read', generation: null }, - { type: 'download-failed', cause: { reason: 'connection-lost', hostCode: null } } - ]) - const report = buildConnectionDiagnosticsReport({ - hostName: 'Desk', - endpoint: 'ws://192.168.1.2:6768', - state: 'disconnected', - reconnectAttempts: 1, - lastConnectedAt: null, - platform: 'ios', - appVersion: '0.0.56', - bridgeProtocolVersion: 1, - entries: entries([ - ...failed.lines, - ...present(stall(replay(DOWNLOAD_OPEN.slice(0, 6)))), - ...present(stall(replay([]))), - ...present(bridgeDiagnosticLine({ kind: 'refused', refusal: 'oversized' })), - frameWithoutHostLine({ clientReady: false, snapshotReady: false }) - ]), - nowMs: 60_000 - }) - expect(report).toContain( - 'Likely cause: No single failure cause can be determined from the recorded events.' - ) - }) - - it('leaves an earlier connection failure as the likely cause', () => { - const timeout: ConnectionLogEntry = { - id: 'timeout', - ts: 500, - level: 'error', - code: 'connect-timeout', - message: 'WebSocket connect timeout' - } - const report = buildConnectionDiagnosticsReport({ - hostName: 'Desk', - endpoint: 'ws://192.168.1.2:6768', - state: 'disconnected', - reconnectAttempts: 1, - lastConnectedAt: null, - platform: 'ios', - appVersion: '0.0.56', - bridgeProtocolVersion: 1, - entries: [timeout, ...entries(replay(DOWNLOAD_OPEN).lines)], - nowMs: 60_000 - }) - expect(report).toContain( - 'Likely cause: The saved direct endpoint did not answer before the connection timeout.' - ) - }) -}) diff --git a/mobile/src/mobile-web-shell/shell-page-frame.test.ts b/mobile/src/mobile-web-shell/shell-page-frame.test.ts deleted file mode 100644 index 52ea1c84973..00000000000 --- a/mobile/src/mobile-web-shell/shell-page-frame.test.ts +++ /dev/null @@ -1,44 +0,0 @@ -import { describe, expect, it } from 'vitest' -import type { MobileWebShellSessionState } from './mobile-web-shell-session-contract' -import { shellPageFrame } from './shell-page-frame' - -const READY: MobileWebShellSessionState = { - kind: 'ready', - generationDirectory: '/cache/gen', - sessionId: 'session-a', - buildId: 'build-a', - totalBytes: 1, - elapsedMs: 1, - compat: { - schemaVersion: 1, - runtimeProtocolVersion: 1, - minCompatibleRuntimeProtocolVersion: 1, - pageVersion: 1 - } -} - -function frame(patch: { state?: MobileWebShellSessionState; pagePainted?: boolean }) { - return shellPageFrame({ state: patch.state ?? READY, pagePainted: patch.pagePainted ?? false }) -} - -describe('how long the shell keeps its own frame up', () => { - it('has nothing to cover before a generation is on screen', () => { - for (const state of [ - { kind: 'checking' }, - { kind: 'activating', source: 'download' }, - { kind: 'offline' }, - { kind: 'route-unavailable' } - ] as const satisfies readonly MobileWebShellSessionState[]) { - expect(frame({ state }), state.kind).toBe('pending') - } - }) - - it('covers a mounted view until the page reports a frame, handshake or not', () => { - // Ready precedes tree construction; keep the cover over the empty view until paint. - expect(frame({})).toBe('unpainted') - }) - - it('uncovers on the page reporting a frame', () => { - expect(frame({ pagePainted: true })).toBe('painted') - }) -}) diff --git a/mobile/src/mobile-web-shell/use-mobile-web-shell-bridge.test.ts b/mobile/src/mobile-web-shell/use-mobile-web-shell-bridge.test.ts index 3576ecc2188..26744bc0b42 100644 --- a/mobile/src/mobile-web-shell/use-mobile-web-shell-bridge.test.ts +++ b/mobile/src/mobile-web-shell/use-mobile-web-shell-bridge.test.ts @@ -9,16 +9,11 @@ import { act, create, type ReactTestRenderer } from 'react-test-renderer' import { afterEach, beforeEach, describe, expect, it, vi, type MockInstance } from 'vitest' import type { OrcaMobileWebShellViewHandle } from '../../modules/orca-mobile-web-shell/src' import { BRIDGE_NATIVE_VERB_NAMES } from './bridge/bridge-native-verbs' -import { - BRIDGE_HAPTICS_GRANT, - BRIDGE_HAPTICS_NOTIFY, - type BridgeHapticsKind -} from './bridge/bridge-haptics-notify' +import { BRIDGE_HAPTICS_GRANT, type BridgeHapticsKind } from './bridge/bridge-haptics-notify' import { BRIDGE_SCREENCAST_BINARY_GRANT } from './bridge/bridge-screencast-grant' import { BRIDGE_BACK_CLAIM_NOTIFY, BRIDGE_BACK_FRAME } from './bridge/bridge-page-back' import { BRIDGE_FAULT_GRANT, - BRIDGE_NAVIGATE_BACK_NOTIFY, readBridgeHostMessage, type BridgeHostMessage } from './bridge/bridge-envelope' @@ -44,7 +39,6 @@ import { useMobileWebShellBridge, type MobileWebShellBridgeView } from './use-mobile-web-shell-bridge' -import { connectionLogStore } from '../transport/persisted-connection-log-store' const ID = bridgeId(1) const DIRECTORY = '/caches/mobile-web/deadbeef/generations/a1b2' @@ -307,19 +301,6 @@ beforeEach(() => { }) describe('the bridge channel', () => { - it('is closed until the session is ready and opens with it', async () => { - const mounted = await mount({ kind: 'checking' }) - expect(mounted.probe.view?.bridgeEnabled).toBe(false) - await mounted.deliver(clientFrame({ type: 'ready' })) - expect(mounted.posted).toEqual([]) - await mounted.update(readyState('session-one')) - expect(mounted.probe.view?.bridgeEnabled).toBe(true) - await mounted.deliver(clientFrame({ type: 'ready' })) - expect(mounted.frames('session-one')).toEqual([ - expect.objectContaining({ type: 'init', sessionId: 'session-one', buildId: 'build-a' }) - ]) - }) - it('does not rebuild the host for a route object the caller built again', async () => { const mounted = await mount(readyState('session-one')) await mounted.deliver(clientFrame({ type: 'ready' })) @@ -354,24 +335,6 @@ describe('the bridge channel', () => { }) expect(mounted.faults).toEqual([]) }) - - it('logs a frame it dropped for want of a host once per session, naming what is missing', async () => { - doubles.client = null - const dropped = () => - connectionLogStore - .get('host-1') - .filter((entry) => entry.message === 'Web shell: page frame with no bridge host') - const before = dropped().length - const mounted = await mount(readyState('session-one')) - await mounted.deliver(clientFrame({ type: 'ready' })) - await mounted.deliver(clientFrame({ type: 'ready' })) - expect(dropped().slice(before)).toEqual([ - expect.objectContaining({ detail: 'client=null snapshot=ok' }) - ]) - await mounted.update(readyState('session-two')) - await mounted.deliver(clientFrame({ type: 'ready' })) - expect(dropped().slice(before)).toHaveLength(2) - }) }) describe('teardown', () => { @@ -389,15 +352,6 @@ describe('teardown', () => { expect(mounted.frames('session-two')).toEqual([]) }) - it(`routes the next session's frames to the next host`, async () => { - const mounted = await mount(readyState('session-one')) - await mounted.update(readyState('session-two')) - await mounted.deliver(clientFrame({ type: 'ready' })) - expect(mounted.frames('session-two')).toEqual([ - expect.objectContaining({ type: 'init', sessionId: 'session-two' }) - ]) - }) - it('disposes when the session leaves ready, and answers nothing after', async () => { const mounted = await mount(readyState('session-one')) await mounted.deliver(clientFrame({ type: 'ready' })) @@ -410,59 +364,7 @@ describe('teardown', () => { expect(fakeClient().requests).toEqual([]) }) - it('carries the dropped-frame total from the host to the screen', async () => { - const mounted = await mount(readyState('session-one')) - await mounted.deliver(clientFrame({ type: 'ready' })) - await mounted.deliver( - clientFrame({ - type: 'subscribe', - id: ID, - method: 'browser.screencast', - params: {}, - wantsBinary: true - }) - ) - const oversized = { - opcode: 1 as const, - seq: 1, - format: 'jpeg' as const, - metadata: {}, - image: new Uint8Array(500_000) - } - await act(async () => { - fakeClient().streams[0]?.emitBinary?.(oversized) - fakeClient().streams[0]?.emitBinary?.({ ...oversized, seq: 2 }) - }) - expect(mounted.probe.droppedBinaryFrames).toEqual([0, 1, 2]) - expect(fakeClient().streams[0]?.unsubscribes).toBe(0) - }) - // Reset drop counts with host ownership so the next host’s first drop cannot look like recovered frames. - it('resets the dropped-frame total when the host is rebuilt', async () => { - const mounted = await mount(readyState('session-one')) - await mounted.deliver(clientFrame({ type: 'ready' })) - await mounted.deliver( - clientFrame({ - type: 'subscribe', - id: ID, - method: 'browser.screencast', - params: {}, - wantsBinary: true - }) - ) - await act(async () => { - fakeClient().streams[0]?.emitBinary?.({ - opcode: 1 as const, - seq: 1, - format: 'jpeg' as const, - metadata: {}, - image: new Uint8Array(500_000) - }) - }) - expect(mounted.probe.droppedBinaryFrames).toEqual([0, 1]) - await mounted.update(readyState('session-two')) - expect(mounted.probe.droppedBinaryFrames).toEqual([0, 1, 0]) - }) it('disposes on unmount and settles what was in flight as delivery-unknown', async () => { const mounted = await mount(readyState('session-one')) @@ -490,24 +392,6 @@ describe('teardown', () => { }) }) -describe('diagnostics', () => { - it('names the notification it refused and why, rather than blaming the view', async () => { - const mounted = await mount(readyState('session-one')) - await mounted.deliver( - clientFrame({ - type: 'notify', - name: BRIDGE_FAULT_GRANT, - error: { category: 'Error', message: 'too early', isRpcDeliveryUnknown: false } - }) - ) - expect(mounted.faults).toEqual([]) - expect(warned).toHaveBeenCalledWith(expect.stringContaining('refused a page notification'), { - name: BRIDGE_FAULT_GRANT, - why: 'before-ready' - }) - }) -}) - describe('client changes', () => { // Client replacement preserves the live document/session; retain its Back state so an open sheet cannot lose the next press. it('keeps delivering Back to an open sheet after the host is rebuilt under it', async () => { @@ -590,107 +474,6 @@ function newProbe(): Probe { } } -describe('the props one render passed', () => { - // Verify callback freshness without host rebuild: pending requests stay open and drop totals announce once. - it('routes each of them into the latest render, without rebuilding the host', async () => { - const posted: PostedFrame[] = [] - const first = newProbe() - const second = newProbe() - const firstFaults: BridgeErrorCapture[] = [] - const secondFaults: BridgeErrorCapture[] = [] - const firstReadies: string[] = [] - const secondReadies: string[] = [] - const render = (probe: Probe, faults: BridgeErrorCapture[], readies: string[]): ReactElement => - createElement(Harness, { session: readyState('session-one'), posted, probe, faults, readies }) - const rendered: { tree: ReactTestRenderer | null } = { tree: null } - await act(async () => { - rendered.tree = createTracked(render(first, firstFaults, firstReadies)) - }) - const deliver = async (probe: Probe, json: string): Promise => { - await act(async () => { - probe.view?.onBridgeMessage({ nativeEvent: { json } }) - }) - } - await deliver(first, clientFrame({ type: 'ready' })) - await deliver(first, clientFrame({ type: 'request', id: ID, method: 'status.get' })) - expect(fakeClient().requests.map((request) => request.method)).toEqual(['status.get']) - await act(async () => { - rendered.tree?.update(render(second, secondFaults, secondReadies)) - }) - for (const json of [ - clientFrame({ type: 'notify', name: 'navigate', href: '/h/host-1/session/wt-2' }), - clientFrame({ type: 'notify', name: 'externalLink', url: 'https://example.com/y' }), - clientFrame({ type: 'notify', name: BRIDGE_HAPTICS_NOTIFY, kind: 'selection' }), - clientFrame({ type: 'notify', name: BRIDGE_NAVIGATE_BACK_NOTIFY }), - clientFrame({ type: 'notify', name: 'storage', key: 'orca:pins:host-1', value: '["wt-2"]' }), - clientFrame({ - type: 'notify', - name: BRIDGE_FAULT_GRANT, - error: { category: 'Error', message: 'the route threw', isRpcDeliveryUnknown: false } - }), - clientFrame({ type: 'ready' }) - ]) { - await deliver(second, json) - } - expect({ - navigations: first.navigations, - externalLinks: first.externalLinks, - haptics: first.haptics, - backPops: first.backPops, - storageWrites: first.storageWrites, - faults: firstFaults, - readies: firstReadies - }).toEqual({ - navigations: [], - externalLinks: [], - haptics: [], - backPops: 0, - storageWrites: [], - faults: [], - readies: ['session-one'] - }) - expect({ - navigations: second.navigations, - externalLinks: second.externalLinks, - haptics: second.haptics, - backPops: second.backPops, - storageWrites: second.storageWrites, - faults: secondFaults, - readies: secondReadies - }).toEqual({ - navigations: ['/h/host-1/session/wt-2'], - externalLinks: ['https://example.com/y'], - haptics: ['selection'], - backPops: 1, - storageWrites: [{ key: 'orca:pins:host-1', value: '["wt-2"]' }], - faults: [{ category: 'Error', message: 'the route threw', isRpcDeliveryUnknown: false }], - readies: ['session-one'] - }) - const answered = posted.map((frame) => { - const read = readBridgeHostMessage(frame.json) - if (!read.ok) { - throw new Error(`the page would refuse this frame: ${read.refusal}`) - } - return read.message.type - }) - expect(answered.filter((type) => type === 'error')).toEqual([]) - expect(first.droppedBinaryFrames).toEqual([0]) - expect(second.droppedBinaryFrames).toEqual([]) - fakeClient().requests[0]?.resolve(rpcSuccess('wire-1', 'ok')) - await flushBridge() - const replied = posted.map((frame) => { - const read = readBridgeHostMessage(frame.json) - if (!read.ok) { - throw new Error(`the page would refuse this frame: ${read.refusal}`) - } - return read.message - }) - expect(replied.filter((frame) => frame.type === 'reply')).toEqual([ - { v: 1, type: 'reply', id: ID, payload: rpcSuccess('wire-1', 'ok') } - ]) - }) -}) - describe('a session that handshook before this host existed', () => { // Seed rebuilt hosts from reducer-owned handshake state because client replacement leaves the same document mounted. it('serves a request from a page that never said `ready` to this host', async () => { diff --git a/mobile/src/notifications/push-registration-cancellation.test.ts b/mobile/src/notifications/push-registration-cancellation.test.ts index c205d5927b7..c9e4d355971 100644 --- a/mobile/src/notifications/push-registration-cancellation.test.ts +++ b/mobile/src/notifications/push-registration-cancellation.test.ts @@ -1,4 +1,3 @@ -import { ensureDesktopNotificationChannel } from './desktop-notification-channel' vi.mock('./desktop-notification-channel', () => ({ ensureDesktopNotificationChannel: vi.fn(async () => {}) })) @@ -131,24 +130,6 @@ it('does not register with stale consent after the user disables notifications d ) }) -it('waits for notification channel readiness before requesting a token', async () => { - const pending = deferred() - vi.mocked(ensureDesktopNotificationChannel).mockReturnValueOnce(pending.promise) - const connection = client() - attachPushRegistration('host', connection as never) - await vi.waitFor(() => expect(ensureDesktopNotificationChannel).toHaveBeenCalled()) - expect(getDevicePushToken).not.toHaveBeenCalled() - expect(connection.sendRequest.mock.calls.map(([method]) => method)).not.toContain( - 'notifications.registerPush' - ) - pending.resolve() - await vi.waitFor(() => - expect(connection.sendRequest.mock.calls.map(([method]) => method)).toContain( - 'notifications.registerPush' - ) - ) -}) - it('completes disable while native token acquisition remains unresolved, and rejects late tokens', async () => { vi.useFakeTimers() storage.set( diff --git a/mobile/src/platform/keyboard-occlusion.web.test.tsx b/mobile/src/platform/keyboard-occlusion.web.test.tsx deleted file mode 100644 index ffb61d8e1fb..00000000000 --- a/mobile/src/platform/keyboard-occlusion.web.test.tsx +++ /dev/null @@ -1,346 +0,0 @@ -// @vitest-environment happy-dom -import { createElement } from 'react' -import { act, create } from 'react-test-renderer' -import { afterEach, beforeEach, describe, expect, it } from 'vitest' -import { - currentSoftKeyboardHeight, - subscribeSoftKeyboard, - useKeyboardOcclusion, - publishShellKeyboardSource -} from './keyboard-occlusion.web' - -class FakeVisualViewport extends EventTarget { - height: number - offsetTop = 0 - scale: number | undefined = 1 - readonly counts = { resize: 0, scroll: 0 } - - constructor(height: number) { - super() - this.height = height - } - - override addEventListener(type: string, listener: EventListenerOrEventListenerObject): void { - if (type === 'resize' || type === 'scroll') { - this.counts[type] += 1 - } - super.addEventListener(type, listener) - } - - override removeEventListener(type: string, listener: EventListenerOrEventListenerObject): void { - if (type === 'resize' || type === 'scroll') { - this.counts[type] -= 1 - } - super.removeEventListener(type, listener) - } - - resizeTo(height: number, offsetTop = 0): void { - this.height = height - this.offsetTop = offsetTop - this.dispatchEvent(new Event('resize')) - } - - zoomTo(scale: number): void { - this.scale = scale - this.height = LAYOUT_HEIGHT / scale - this.offsetTop = 0 - this.dispatchEvent(new Event('resize')) - } - - scrollTo(offsetTop: number): void { - this.offsetTop = offsetTop - this.dispatchEvent(new Event('scroll')) - } -} - -const LAYOUT_HEIGHT = 800 -let viewport: FakeVisualViewport | null = null -let lift = 0 - -function Harness(): null { - lift = useKeyboardOcclusion() - return null -} - -async function mount(): Promise> { - let tree: ReturnType | null = null - await act(async () => { - tree = create(createElement(Harness)) - }) - if (tree === null) { - throw new Error('the harness did not mount') - } - return tree -} - -beforeEach(() => { - lift = 0 - viewport = new FakeVisualViewport(LAYOUT_HEIGHT) - Object.defineProperty(window, 'innerHeight', { value: LAYOUT_HEIGHT, configurable: true }) - Object.defineProperty(window, 'visualViewport', { value: viewport, configurable: true }) -}) - -afterEach(() => { - Object.defineProperty(window, 'visualViewport', { value: undefined, configurable: true }) -}) - -describe('the keyboard the browser reports', () => { - it('reads nothing covered while the visual viewport fills the layout one', async () => { - await mount() - expect(lift).toBe(0) - }) - - it('lifts by the strip the visual viewport stops covering', async () => { - await mount() - await act(async () => viewport?.resizeTo(464)) - expect(lift).toBe(336) - }) - - it('counts an offset visual viewport, which a height alone would read as keyboard', async () => { - // Subtract offsetTop too so a scrolled viewport is not mistaken for extra keyboard height. - await mount() - await act(async () => viewport?.resizeTo(464, 100)) - expect(lift).toBe(236) - }) - - it('follows a scroll that moves the offset without resizing anything', async () => { - await mount() - await act(async () => viewport?.resizeTo(464)) - await act(async () => viewport?.scrollTo(50)) - expect(lift).toBe(286) - }) - - it('drops back to nothing when the keyboard closes', async () => { - await mount() - await act(async () => viewport?.resizeTo(464)) - await act(async () => viewport?.resizeTo(LAYOUT_HEIGHT)) - expect(lift).toBe(0) - }) - - it('reads the keyboard already up at mount, which sends no event', async () => { - viewport?.resizeTo(464) - await mount() - expect(lift).toBe(336) - }) - - it('never reports a negative strip, whatever the two viewports disagree about', async () => { - await mount() - await act(async () => viewport?.resizeTo(LAYOUT_HEIGHT + 120)) - expect(lift).toBe(0) - }) - - it('reads a pinch zoom as no keyboard, because geometry alone cannot tell them apart', async () => { - await mount() - await act(async () => viewport?.zoomTo(2)) - expect(lift).toBe(0) - }) - - it('goes back to measuring once the zoom is released', async () => { - await mount() - await act(async () => viewport?.zoomTo(2)) - await act(async () => viewport?.zoomTo(1)) - await act(async () => viewport?.resizeTo(464)) - expect(lift).toBe(336) - }) - - it('answers 0 for a keyboard raised while the page is zoomed, which is the accepted loss', async () => { - // Geometry cannot separate keyboard from pinch zoom; inputs stay at least 16px to avoid iOS focus zoom. - await mount() - await act(async () => viewport?.zoomTo(2)) - await act(async () => viewport?.resizeTo(232)) - expect(viewport?.scale).toBe(2) - expect(lift).toBe(0) - }) - - it('takes a viewport that reports no scale as unzoomed', async () => { - // Missing scale on older WebViews must not suppress every keyboard. - await mount() - await act(async () => { - if (viewport !== null) { - viewport.scale = undefined - viewport.resizeTo(464) - } - }) - expect(lift).toBe(336) - }) - - it('answers 0 when the effect finds no visual viewport to subscribe to', async () => { - Object.defineProperty(window, 'visualViewport', { value: undefined, configurable: true }) - await mount() - expect(lift).toBe(0) - }) - - it('removes both listeners on unmount', async () => { - const tree = await mount() - expect(viewport?.counts).toEqual({ resize: 1, scroll: 1 }) - await act(async () => tree.unmount()) - expect(viewport?.counts).toEqual({ resize: 0, scroll: 0 }) - }) -}) - -describe('the keyboard as events, for a sheet', () => { - it('shows by the uncovered strip and hides once when it closes', () => { - const calls: string[] = [] - const unsubscribe = subscribeSoftKeyboard( - (height, duration) => calls.push(`show ${height} ${duration}`), - (duration) => calls.push(`hide ${duration}`) - ) - viewport?.resizeTo(464) - viewport?.resizeTo(LAYOUT_HEIGHT) - viewport?.resizeTo(LAYOUT_HEIGHT) - expect(calls).toEqual(['show 336 0', 'hide 0']) - unsubscribe() - expect(viewport?.counts).toEqual({ resize: 0, scroll: 0 }) - }) - - it('hides a keyboard that was already up when it subscribed', async () => { - viewport?.resizeTo(464) - const calls: string[] = [] - const unsubscribe = subscribeSoftKeyboard( - (height) => calls.push(`show ${height}`), - (duration) => calls.push(`hide ${duration}`) - ) - viewport?.resizeTo(LAYOUT_HEIGHT) - expect(calls).toEqual(['hide 0']) - unsubscribe() - viewport?.resizeTo(464) - await mount() - expect(lift).toBe(336) - await act(async () => viewport?.resizeTo(LAYOUT_HEIGHT)) - expect(lift).toBe(0) - }) - - it('stays silent while the visual viewport covers nothing', () => { - const calls: string[] = [] - const unsubscribe = subscribeSoftKeyboard( - () => calls.push('show'), - () => calls.push('hide') - ) - viewport?.resizeTo(LAYOUT_HEIGHT) - expect(calls).toEqual([]) - unsubscribe() - }) - - it('reads a keyboard already up, and 0 without a visual viewport', () => { - viewport?.resizeTo(464) - expect(currentSoftKeyboardHeight()).toBe(336) - Object.defineProperty(window, 'visualViewport', { value: undefined, configurable: true }) - expect(currentSoftKeyboardHeight()).toBe(0) - expect(() => - subscribeSoftKeyboard( - () => {}, - () => {} - )() - ).not.toThrow() - }) -}) - -let keyboardHeight = 0 - -function StateHarness(): null { - keyboardHeight = useKeyboardOcclusion() - return null -} - -async function mountState(): Promise> { - let tree: ReturnType | null = null - await act(async () => { - tree = create(createElement(StateHarness)) - }) - if (tree === null) { - throw new Error('the harness did not mount') - } - return tree -} - -function createShellKeyboard(initial = 0) { - let height = initial - const listeners = new Set<(height: number) => void>() - return { - source: { - read: () => height, - subscribe: (listener: (height: number) => void) => { - listeners.add(listener) - return () => { - listeners.delete(listener) - } - } - }, - move: (next: number) => { - height = next - for (const listener of listeners) { - listener(next) - } - }, - listenerCount: () => listeners.size - } -} - -describe('the state a native screen reads, from the browser outside the shell', () => { - it('is open exactly while something is covered', async () => { - const tree = await mountState() - expect(keyboardHeight).toBe(0) - await act(async () => viewport?.resizeTo(464)) - expect(keyboardHeight).toBe(336) - await act(async () => viewport?.resizeTo(LAYOUT_HEIGHT)) - expect(keyboardHeight).toBe(0) - await act(async () => tree.unmount()) - }) -}) - -// Shell WebViews zero IME insets, so visualViewport cannot measure the keyboard; use bridge heights. -describe('the keyboard the shell says covers the page', () => { - afterEach(() => { - publishShellKeyboardSource(null) - }) - - it('answers the height the shell sent, and ignores the visual viewport', async () => { - const shell = createShellKeyboard() - publishShellKeyboardSource(shell.source) - const tree = await mountState() - const lifted = await mount() - // Pixel_API_37: the suggestion strip grows IME height from 312 to 346. - for (const height of [312, 346]) { - await act(async () => shell.move(height)) - expect(keyboardHeight).toBe(height) - expect(lift).toBe(height) - } - await act(async () => viewport?.resizeTo(464)) - expect(keyboardHeight).toBe(346) - await act(async () => shell.move(0)) - expect(keyboardHeight).toBe(0) - expect(lift).toBe(0) - await act(async () => { - tree.unmount() - lifted.unmount() - }) - expect(shell.listenerCount()).toBe(0) - }) - - it('reads a keyboard already up at mount, which the shell sent in the first init', async () => { - publishShellKeyboardSource(createShellKeyboard(312).source) - expect(currentSoftKeyboardHeight()).toBe(312) - const tree = await mountState() - expect(keyboardHeight).toBe(312) - await act(async () => tree.unmount()) - }) - - it('hands a sheet each height as a show and the close as one hide', () => { - const shell = createShellKeyboard() - publishShellKeyboardSource(shell.source) - const calls: string[] = [] - const unsubscribe = subscribeSoftKeyboard( - (height, duration) => calls.push(`show ${height} ${duration}`), - (duration) => calls.push(`hide ${duration}`) - ) - viewport?.resizeTo(464) - shell.move(312) - shell.move(346) - shell.move(0) - shell.move(0) - expect(calls).toEqual(['show 312 0', 'show 346 0', 'hide 0']) - unsubscribe() - expect(shell.listenerCount()).toBe(0) - expect(viewport?.counts).toEqual({ resize: 0, scroll: 0 }) - }) -}) diff --git a/mobile/src/platform/text-input-selection-reveal.web.test.tsx b/mobile/src/platform/text-input-selection-reveal.web.test.tsx deleted file mode 100644 index b59e749295e..00000000000 --- a/mobile/src/platform/text-input-selection-reveal.web.test.tsx +++ /dev/null @@ -1,78 +0,0 @@ -// @vitest-environment happy-dom -import { act, useRef } from 'react' -import { createRoot } from 'react-dom/client' -import { TextInput } from 'react-native' -import type * as ReactNative from 'react-native' -import { expect, it, vi } from 'vitest' -import { useTextInputSelectionReveal } from './text-input-selection-reveal.web' - -vi.mock('react-native', () => vi.importActual('react-native-web')) - -it('reveals the current caret after the field is capped and preserves later manual scrolling', async () => { - const resized: (() => void)[] = [] - class LayoutObserver implements ResizeObserver { - constructor(callback: ResizeObserverCallback) { - resized.push(() => callback([], this)) - } - observe() {} - unobserve() {} - disconnect() {} - } - vi.stubGlobal('ResizeObserver', LayoutObserver) - let height = 60 - let caretTop = 120 - vi.spyOn(HTMLTextAreaElement.prototype, 'clientWidth', 'get').mockReturnValue(300) - vi.spyOn(HTMLTextAreaElement.prototype, 'clientHeight', 'get').mockImplementation(() => height) - vi.spyOn(HTMLSpanElement.prototype, 'getClientRects').mockImplementation(() => { - const rect = new DOMRect(0, caretTop, 1, 20) - return { - 0: rect, - length: 1, - item: () => rect, - [Symbol.iterator]: function* (): Generator { - yield rect - } - } - }) - function Editor() { - const input = useRef(null) - useTextInputSelectionReveal(input) - return ( - - ) - } - const container = document.createElement('div') - document.body.append(container) - const root = createRoot(container) - const paint = () => new Promise((resolve) => requestAnimationFrame(() => resolve())) - try { - await act(async () => root.render()) - const field = container.querySelector('textarea')! - field.focus() - field.setSelectionRange(field.value.length, field.value.length) - await act(async () => { - height = 40 - resized.forEach((resize) => resize()) - await paint() - }) - expect(field.scrollTop).toBe(100) - await act(async () => { - caretTop = 40 - field.setSelectionRange(4, 4) - field.dispatchEvent(new Event('select')) - await paint() - }) - expect(field.scrollTop).toBe(40) - expect(field.selectionStart).toBe(4) - field.scrollTop = 65 - field.dispatchEvent(new Event('scroll')) - await act(paint) - expect(field.scrollTop).toBe(65) - expect(document.activeElement).toBe(field) - } finally { - await act(async () => root.unmount()) - container.remove() - vi.restoreAllMocks() - vi.unstubAllGlobals() - } -}) diff --git a/mobile/src/query/host-query-errors.test.ts b/mobile/src/query/host-query-errors.test.ts deleted file mode 100644 index e6226ef19e4..00000000000 --- a/mobile/src/query/host-query-errors.test.ts +++ /dev/null @@ -1,39 +0,0 @@ -import { afterEach, beforeEach, expect, it, vi } from 'vitest' -import { LogicalClientCutoverError } from '../transport/stable-logical-rpc-client' -import { createOrcaQueryClient } from './orca-query-client' - -beforeEach(() => { - vi.useFakeTimers() -}) - -afterEach(() => { - vi.useRealTimers() -}) - -it('retries a read cut by a connection migration once and lands its data', async () => { - const queryClient = createOrcaQueryClient() - const queryFn = vi - .fn<() => Promise>() - .mockRejectedValueOnce(new LogicalClientCutoverError()) - .mockResolvedValueOnce('rows') - - const read = queryClient.query({ queryKey: ['orca', 'host-1', 'test.read'], queryFn }) - await vi.advanceTimersByTimeAsync(250) - - await expect(read).resolves.toBe('rows') - expect(queryFn).toHaveBeenCalledTimes(2) -}) - -it('leaves a read refused while disconnected to the connected edge', async () => { - const queryClient = createOrcaQueryClient() - const queryFn = vi - .fn<() => Promise>() - .mockRejectedValue(new Error('Not connected: test.read')) - - const read = queryClient.query({ queryKey: ['orca', 'host-1', 'test.read'], queryFn }) - const settled = expect(read).rejects.toThrow('Not connected: test.read') - await vi.advanceTimersByTimeAsync(5_000) - - await settled - expect(queryFn).toHaveBeenCalledTimes(1) -})