mirror of
https://github.com/stablyai/orca.git
synced 2026-11-16 10:58:10 +00:00
Merge remote-tracking branch 'origin/main' into brennanb2025/claude-ask-previews
This commit is contained in:
@@ -123,6 +123,12 @@ graph. Local affected tests do not replace CI.
|
||||
|
||||
Use `pnpm test`, not raw `vitest`: only it keeps the transform cache that makes repeat runs fast.
|
||||
|
||||
Most unit files share a worker and its module cache with the files before them. After each file
|
||||
the worker undoes mocks, fake timers, stubs, env, cwd, and leftover timers, listeners, and globals.
|
||||
Files using `vi.doMock`, `vi.resetModules`, a DOM environment, or direct `globalThis` writes keep
|
||||
their own worker. If a file passes alone but fails after others, add `// @orca-isolated-worker`
|
||||
to it; `ORCA_VITEST_ISOLATE_EVERY_FILE=1` isolates every file to confirm a leak.
|
||||
|
||||
To reduce main-process rebuild CPU and memory when you do not need its source maps,
|
||||
set `ORCA_DEV_MAIN_SOURCEMAPS=0` before `pnpm dev`. In Bash/zsh:
|
||||
|
||||
|
||||
@@ -342,12 +342,6 @@ jobs:
|
||||
if [ "$PREFLIGHT_PHASE_SELECTED" != true ] || [ "$PREFLIGHT_PRIOR_SUCCESS" != true ]; then exit 0; fi
|
||||
node config/scripts/preflight/changed-checks/check-changed-code-quality.mjs "${{ github.event.pull_request.base.sha }}"
|
||||
|
||||
- name: Verify locked audit tools
|
||||
if: needs.code_paths.outputs.static_analysis == 'true'
|
||||
env:
|
||||
ORCA_BACKGROUND_LAUNCH: '1'
|
||||
run: node config/scripts/dependency-security/audit-tools/verify-locked-audit-tools.mjs
|
||||
|
||||
- name: Enforce React Doctor on changed lines
|
||||
if: needs.code_paths.outputs.static_analysis == 'true'
|
||||
run: node config/scripts/static-analysis/react-doctor/check-react-doctor-changed.mjs "${{ github.event.pull_request.base.sha }}"
|
||||
|
||||
@@ -13,4 +13,3 @@ To update a tool, change its exact version in this package's manifest, run
|
||||
`pnpm --dir config/audit-tools install --ignore-scripts`, and review both the manifest
|
||||
and generated lockfile. The workspace enforces a three-day release delay and
|
||||
disables install scripts. Keep its package-manager pin aligned with the root.
|
||||
Run `node config/scripts/verify-locked-audit-tools.mjs` to exercise both tools.
|
||||
|
||||
@@ -0,0 +1,47 @@
|
||||
import { readFileSync } from 'node:fs'
|
||||
import { resolve } from 'node:path'
|
||||
import type { Options } from '@vitejs/plugin-react'
|
||||
|
||||
// Hand-kept list plus every file still in a hazard ratchet; compiled, these would run differently.
|
||||
const UNCOMPILED_FILE_LISTS = [
|
||||
'config/react-compiler-uncompiled-files.txt',
|
||||
'config/render-path-translate-baseline.txt',
|
||||
'config/react-compiler-hazard-baseline.txt'
|
||||
]
|
||||
|
||||
function listedFiles(list: string): string[] {
|
||||
return readFileSync(resolve(list), 'utf8')
|
||||
.split('\n')
|
||||
.map((line) => line.trim())
|
||||
.filter((line) => line && !line.startsWith('#'))
|
||||
.map((line) => line.replace(/^\d+\s+/, '').split('#')[0])
|
||||
}
|
||||
|
||||
export function reactCompilerExcludedFiles(): string[] {
|
||||
return [...new Set(UNCOMPILED_FILE_LISTS.flatMap(listedFiles))]
|
||||
}
|
||||
|
||||
export function isReactCompilerEnabled(): boolean {
|
||||
return process.env.ORCA_REACT_COMPILER !== '0'
|
||||
}
|
||||
|
||||
export const REACT_COMPILER_OPTIONS = { target: '19' } as const
|
||||
|
||||
function escapeRegExp(text: string): string {
|
||||
return text.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')
|
||||
}
|
||||
|
||||
export function reactCompilerExcludePattern(): RegExp {
|
||||
return new RegExp(`/(?:${reactCompilerExcludedFiles().map(escapeRegExp).join('|')})$`)
|
||||
}
|
||||
|
||||
// ORCA_REACT_COMPILER=0 builds without the compiler for bisecting.
|
||||
export function reactPluginOptions(): Options {
|
||||
if (!isReactCompilerEnabled()) {
|
||||
return {}
|
||||
}
|
||||
return {
|
||||
compiler: REACT_COMPILER_OPTIONS,
|
||||
exclude: [/\/node_modules\//, reactCompilerExcludePattern()]
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
import { createRequire } from 'node:module'
|
||||
|
||||
// Why: hook-harness tests mock React or call hooks outside render; there, run uncached like uncompiled code.
|
||||
const require = createRequire(import.meta.url)
|
||||
const react: {
|
||||
__CLIENT_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE: { H: unknown }
|
||||
} = require('react')
|
||||
const internals = react.__CLIENT_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE
|
||||
const runtime: { c: (size: number) => unknown[] } = require('react/compiler-runtime')
|
||||
const sentinel = Symbol.for('react.memo_cache_sentinel')
|
||||
const uncached = (size: number): unknown[] => Array.from({ length: size }, () => sentinel)
|
||||
|
||||
export function c(size: number): unknown[] {
|
||||
if (!internals.H) {
|
||||
return uncached(size)
|
||||
}
|
||||
try {
|
||||
return runtime.c(size)
|
||||
} catch (error) {
|
||||
if (error instanceof Error && error.message.startsWith('Invalid hook call')) {
|
||||
return uncached(size)
|
||||
}
|
||||
throw error
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,66 @@
|
||||
import { resolve } from 'node:path'
|
||||
import { normalizePath, type Plugin } from 'vite'
|
||||
import {
|
||||
REACT_COMPILER_OPTIONS,
|
||||
isReactCompilerEnabled,
|
||||
reactCompilerExcludePattern
|
||||
} from './react-compiler'
|
||||
|
||||
const rendererSource = /\/src\/renderer\/src\/.*\.tsx?$/
|
||||
// Only shipped code is compiled; tests, fixtures, mocks and harnesses run as written.
|
||||
const testSupport =
|
||||
/\/__(?:mocks|fixtures|tests)__\/|\.(?:test|spec|bench)\.tsx?$|[.-]test-|[.-]fixtures?\.tsx?$/
|
||||
const importsVitest = /\bfrom ['"]vitest['"]/
|
||||
const runtimeFallback = normalizePath(
|
||||
resolve(import.meta.dirname, 'vitest-compiler-runtime-fallback.ts')
|
||||
)
|
||||
|
||||
// Why: @vitejs/plugin-react skips the compiler for vitest's server consumer, so call it directly.
|
||||
export function vitestReactCompiler(): Plugin[] {
|
||||
if (!isReactCompilerEnabled()) {
|
||||
return []
|
||||
}
|
||||
const excluded = reactCompilerExcludePattern()
|
||||
return [
|
||||
{
|
||||
name: 'vitest-react-compiler',
|
||||
enforce: 'pre',
|
||||
configureVitest({ defineCacheKeyGenerator }) {
|
||||
// Ratchet baselines move files in and out of compilation without touching their source.
|
||||
defineCacheKeyGenerator(({ id }) =>
|
||||
excluded.test(normalizePath(id.split('?')[0])) ? 'react-compiler:excluded' : ''
|
||||
)
|
||||
},
|
||||
async transform(source, id) {
|
||||
const filename = normalizePath(id.split('?')[0])
|
||||
if (
|
||||
!rendererSource.test(filename) ||
|
||||
testSupport.test(filename) ||
|
||||
excluded.test(filename) ||
|
||||
importsVitest.test(source)
|
||||
) {
|
||||
return null
|
||||
}
|
||||
const { transform } = await import('oxc-transform-react')
|
||||
const result = await transform(filename, source, {
|
||||
jsx: { runtime: 'automatic', development: true },
|
||||
reactCompiler: REACT_COMPILER_OPTIONS,
|
||||
sourcemap: true
|
||||
})
|
||||
const diagnostics = result.errors.map(
|
||||
(e) => `${e.message}${e.codeframe ? `\n${e.codeframe}` : ''}`
|
||||
)
|
||||
if (result.fatal) {
|
||||
this.error(diagnostics.join('\n\n') || `React Compiler transform failed: ${filename}`)
|
||||
}
|
||||
return {
|
||||
code: result.code.replace(
|
||||
/from ["']react\/compiler-runtime["']/,
|
||||
`from ${JSON.stringify(runtimeFallback)}`
|
||||
),
|
||||
map: result.map
|
||||
}
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -225,7 +225,7 @@
|
||||
1 src/renderer/src/lib/default-creation-host.ts # the sanctioned reader of the default host
|
||||
1 src/renderer/src/lib/launch-ai-vault-session.ts
|
||||
1 src/renderer/src/lib/local-preflight-context.ts
|
||||
2 src/renderer/src/lib/provider-runtime-context.ts
|
||||
2 src/renderer/src/runtime/hosts/observations/provider-runtime-context.ts
|
||||
2 src/renderer/src/lib/repo-runtime-owner.ts
|
||||
1 src/renderer/src/lib/runtime-session-mirror-owners.ts
|
||||
1 src/renderer/src/lib/runtime-session-mirror-targets.ts
|
||||
|
||||
@@ -7,7 +7,7 @@
|
||||
1 src/renderer/src/components/settings/browser/profiles/BrowserSessionCookiesSection.tsx
|
||||
1 src/renderer/src/components/settings/browser/routing/BrowserSshWorkspaceRoutingSetting.tsx
|
||||
1 src/renderer/src/components/settings/quick-commands/QuickCommandsToolbar.tsx
|
||||
1 src/renderer/src/components/settings/repository/execution/RepositoryHostSetupsSection.tsx
|
||||
1 src/renderer/src/components/settings/repository/hosts/RepositoryHostSetupsSection.tsx
|
||||
1 src/renderer/src/components/sidebar/host-admission/ssh/AddRemoteHostSshConfigPicker.tsx
|
||||
4 src/renderer/src/components/status-bar/SshStatusSegment.tsx
|
||||
1 src/renderer/src/components/status-bar/resource-usage-popover-body.tsx
|
||||
|
||||
@@ -60,31 +60,45 @@
|
||||
"kind": "object-property:keywords",
|
||||
"text": "ghostty",
|
||||
"dynamic": false,
|
||||
"count": 2
|
||||
"count": 1
|
||||
},
|
||||
{
|
||||
"filePath": "src/renderer/src/components/settings/terminal/configuration/terminal-config-import-search.ts",
|
||||
"kind": "object-property:keywords",
|
||||
"text": "ghostty",
|
||||
"dynamic": false,
|
||||
"count": 1
|
||||
},
|
||||
{
|
||||
"filePath": "src/renderer/src/components/settings/terminal/platform/terminal-advanced-platform-search.ts",
|
||||
"kind": "object-property:keywords",
|
||||
"text": "Ghostty",
|
||||
"dynamic": false,
|
||||
"count": 2
|
||||
"count": 1
|
||||
},
|
||||
{
|
||||
"filePath": "src/renderer/src/components/settings/terminal/platform/terminal-advanced-platform-search.ts",
|
||||
"filePath": "src/renderer/src/components/settings/terminal/configuration/terminal-config-import-search.ts",
|
||||
"kind": "object-property:keywords",
|
||||
"text": "Ghostty",
|
||||
"dynamic": false,
|
||||
"count": 1
|
||||
},
|
||||
{
|
||||
"filePath": "src/renderer/src/components/settings/terminal/configuration/terminal-config-import-search.ts",
|
||||
"kind": "object-property:keywords",
|
||||
"text": "Kitty",
|
||||
"dynamic": false,
|
||||
"count": 1
|
||||
},
|
||||
{
|
||||
"filePath": "src/renderer/src/components/settings/terminal/platform/terminal-advanced-platform-search.ts",
|
||||
"filePath": "src/renderer/src/components/settings/terminal/configuration/terminal-config-import-search.ts",
|
||||
"kind": "object-property:keywords",
|
||||
"text": "kitty",
|
||||
"dynamic": false,
|
||||
"count": 1
|
||||
},
|
||||
{
|
||||
"filePath": "src/renderer/src/components/settings/terminal/platform/terminal-advanced-platform-search.ts",
|
||||
"filePath": "src/renderer/src/components/settings/terminal/configuration/terminal-config-import-search.ts",
|
||||
"kind": "object-property:keywords",
|
||||
"text": "kitty.conf",
|
||||
"dynamic": false,
|
||||
|
||||
@@ -6,7 +6,6 @@
|
||||
config/scripts/performance/session-search/session-search-tool-heavy-corpus.ts src/main/ai-vault/session-transcript-reader.ts
|
||||
config/scripts/runtime-verification/desktop-transport/run-linux-lid-sleep-assertion-docker.mjs src/main/linux-lid-sleep-assertion.ts
|
||||
config/scripts/runtime-verification/desktop-transport/run-ssh-staged-upload-reliability.mjs src/main/ssh/ssh-relay-install-namespace.test.ts
|
||||
config/scripts/session-search-file-id-e2e/run.ts src/main/ai-vault/session-scanner-service-entry.ts
|
||||
config/scripts/static-analysis/ratchets/renderer-state/check-layout-writer-ratchets.mjs src/renderer/src/runtime/remote-workspace-frozen/
|
||||
config/scripts/workflow/source-routing/pr-code-change-scope.mjs src/main/runtime/runtime-worktree-agent-
|
||||
config/scripts/workflow/source-routing/pr-code-change-scope.mjs src/shared/agent-session-mutation-envelope
|
||||
|
||||
@@ -422,11 +422,11 @@
|
||||
1 src/renderer/src/components/settings/privacy/PrivacyPane.tsx
|
||||
1 src/renderer/src/components/settings/quick-commands/QuickCommandsPane.tsx
|
||||
1 src/renderer/src/components/settings/repository/RepositoryFormatterSection.tsx
|
||||
2 src/renderer/src/components/settings/repository/RepositoryGitHubAccountSection.tsx
|
||||
2 src/renderer/src/components/settings/repository/source-control/RepositoryGitHubAccountSection.tsx
|
||||
3 src/renderer/src/components/settings/repository/RepositoryJiraProjectSection.tsx
|
||||
2 src/renderer/src/components/settings/repository/execution/RepositoryForkSyncSection.tsx
|
||||
3 src/renderer/src/components/settings/repository/execution/RepositoryHostSetupActions.tsx
|
||||
2 src/renderer/src/components/settings/repository/execution/SparsePresetSettingsSection.tsx
|
||||
2 src/renderer/src/components/settings/repository/source-control/RepositoryForkSyncSection.tsx
|
||||
3 src/renderer/src/components/settings/repository/hosts/RepositoryHostSetupActions.tsx
|
||||
2 src/renderer/src/components/settings/repository/worktrees/SparsePresetSettingsSection.tsx
|
||||
2 src/renderer/src/components/settings/repository/identity/RepositoryIconPicker.tsx
|
||||
1 src/renderer/src/components/settings/repository/mcp/McpConfigSection.tsx
|
||||
9 src/renderer/src/components/settings/repository/source-control/repository-source-control-ai-global-ux.ts
|
||||
@@ -441,7 +441,7 @@
|
||||
1 src/renderer/src/components/settings/session-history/SessionHistoryServerRow.tsx
|
||||
2 src/renderer/src/components/settings/session-history/SessionHistorySettingsPane.tsx
|
||||
1 src/renderer/src/components/settings/session-history/SessionSearchAdvancedSection.tsx
|
||||
1 src/renderer/src/components/settings/session-history/use-session-search-status.ts
|
||||
1 src/renderer/src/components/session-search/use-session-search-status.ts
|
||||
1 src/renderer/src/components/settings/shortcuts/ShortcutRecorderButton.tsx
|
||||
2 src/renderer/src/components/settings/source-control/AutoRenameBranchFromWorkSetting.tsx
|
||||
1 src/renderer/src/components/settings/source-control/CommitMessageAiPane.tsx
|
||||
@@ -449,7 +449,7 @@
|
||||
1 src/renderer/src/components/settings/ssh/SshPane.tsx
|
||||
1 src/renderer/src/components/settings/ssh/server-actions/SshHostDeltaMoveDialog.tsx
|
||||
1 src/renderer/src/components/settings/ssh/server-actions/SshHostKeepServerVersionDialog.tsx
|
||||
1 src/renderer/src/components/settings/ssh/server-actions/SshHostMoveAnywayAction.tsx
|
||||
1 src/renderer/src/components/ssh-host-recovery/SshHostMoveAnywayAction.tsx
|
||||
1 src/renderer/src/components/settings/ssh/server-actions/SshHostRecoverServerAction.tsx
|
||||
1 src/renderer/src/components/settings/ssh/server-actions/SshHostRestartServerAction.tsx
|
||||
1 src/renderer/src/components/settings/ssh/ssh-hosts-header-slot.tsx
|
||||
|
||||
@@ -0,0 +1,37 @@
|
||||
# Renderer files React Compiler skips; compiled, they would run differently. Hand-maintained.
|
||||
# Files in config/render-path-translate-baseline.txt and config/react-compiler-hazard-baseline.txt
|
||||
# are skipped too. Remove a line once its file is safe to compile.
|
||||
|
||||
# Render-time reads of providerRuntimeSessionGeneration (lib/provider-runtime-context.ts; hazard live-read-in-memo-block).
|
||||
src/renderer/src/components/feature-wall/FeatureWallSetupChecklist.tsx
|
||||
src/renderer/src/components/feature-wall/use-integration-connection-status.ts
|
||||
src/renderer/src/components/integrations/task-trackers/jira-integration-card.tsx
|
||||
src/renderer/src/components/integrations/task-trackers/linear-integration-card.tsx
|
||||
src/renderer/src/components/new-workspace/use-jira-source-connection.ts
|
||||
src/renderer/src/components/new-workspace/use-work-item-source-foundation.ts
|
||||
src/renderer/src/components/settings/skills/linear/LinearAgentSkillPane.tsx
|
||||
src/renderer/src/components/settings/tasks/use-task-source-provider-readiness.ts
|
||||
src/renderer/src/components/sidebar/workspace-card/details/use-worktree-card-review-details.ts
|
||||
src/renderer/src/components/task-page/jira/Content.tsx
|
||||
src/renderer/src/components/task-page/jira/use-task-page-jira-list-projection.ts
|
||||
src/renderer/src/components/task-page/jira/use-task-page-jira-list-state.ts
|
||||
src/renderer/src/hooks/use-integration-provider-status-refresh.ts
|
||||
|
||||
# structuredSessionSelectionAuthority/Controller read module state the selection lifetime replaces (live-read-in-memo-block).
|
||||
src/renderer/src/components/native-chat/session/options/structured/use-structured-agent-session-option-state.ts
|
||||
|
||||
# applyTerminalColdActivation mutates controller refs during render on the terminal hot path.
|
||||
src/renderer/src/components/use-terminal-controller.ts
|
||||
|
||||
# Caches keyed on a TanStack virtualizer, which mutates in place (hazard virtualizer-in-memo-block).
|
||||
src/renderer/src/components/editor/combined-diff/scroll-viewport/combined-diff-section-list.tsx
|
||||
src/renderer/src/components/editor/markdown-preview/search/use-markdown-preview-search-reveal.ts
|
||||
src/renderer/src/components/editor/markdown-preview/viewport/use-markdown-preview-scroll-anchor.ts
|
||||
src/renderer/src/components/github-item-dialog/inspect-pull-request/pr-files-combined-diff-body.tsx
|
||||
src/renderer/src/components/right-sidebar/file-explorer/panel/FileExplorerVirtualRows.tsx
|
||||
src/renderer/src/components/right-sidebar/file-explorer/tree/FileExplorerFilesTreePane.tsx
|
||||
src/renderer/src/components/sidebar/worktree-list/viewport/VirtualizedWorktreeViewport.tsx
|
||||
|
||||
# The workbench subtree relies on the shell re-rendering on every app render.
|
||||
src/renderer/src/app-shell/AppWorkspaceShell.tsx
|
||||
src/renderer/src/app-shell/use-app-chrome-layout.ts
|
||||
@@ -5,11 +5,7 @@ import {
|
||||
withScratch,
|
||||
copyWrittenBundle
|
||||
} from '../../mobile-web-app/mobile-web-app-bundle-test-fixture.mjs'
|
||||
import {
|
||||
bundleMobileWebApp,
|
||||
renameOutputsByContent,
|
||||
routeChunkNames
|
||||
} from './build-mobile-web-app-bundle.mjs'
|
||||
import { bundleMobileWebApp } from './build-mobile-web-app-bundle.mjs'
|
||||
import { MOBILE_WEB_APP_ROUTE_ROOT } from '../../mobile-web-app/mobile-web-app-route-manifest.mjs'
|
||||
import { verifyMobileWebAppBundle } from './verify-mobile-web-app-bundle.mjs'
|
||||
import {
|
||||
@@ -141,33 +137,3 @@ describe('the verifier', () => {
|
||||
240_000
|
||||
)
|
||||
})
|
||||
|
||||
describe('naming an output by its bytes', () => {
|
||||
it('refuses two outputs that name each other', () => {
|
||||
const emitted = (text) => new TextEncoder().encode(text)
|
||||
const metafile = {
|
||||
outputs: {
|
||||
'dist/a.js': { imports: [{ path: 'dist/b.js', kind: 'import-statement' }] },
|
||||
'dist/b.js': { imports: [{ path: 'dist/a.js', kind: 'import-statement' }] }
|
||||
}
|
||||
}
|
||||
// Cycles have no final dependency names/content hash; fail if esbuild ever stops emitting a DAG.
|
||||
expect(() =>
|
||||
renameOutputsByContent(metafile, [
|
||||
{ path: 'dist/a.js', contents: emitted('import "/assets/b.js"') },
|
||||
{ path: 'dist/b.js', contents: emitted('import "/assets/a.js"') }
|
||||
])
|
||||
).toThrow(/output cycle/)
|
||||
})
|
||||
|
||||
it('refuses a route it cannot find an output for', async () => {
|
||||
await withScratch(async (scratch) => {
|
||||
const module = join(scratch, 'index.tsx')
|
||||
await writeFile(module, 'export default function Route() { return null }\n')
|
||||
// Only metafile maps routes to chunks; missing output must fail before phones request undefined/404.
|
||||
expect(() =>
|
||||
routeChunkNames({ outputs: {} }, [{ key: './index.tsx', module }], new Map())
|
||||
).toThrow(/\.\/index\.tsx reached no output/)
|
||||
})
|
||||
})
|
||||
})
|
||||
|
||||
@@ -1,50 +0,0 @@
|
||||
import { existsSync } from 'node:fs'
|
||||
import { mkdtemp, rm } from 'node:fs/promises'
|
||||
import { tmpdir } from 'node:os'
|
||||
import { join } from 'node:path'
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import {
|
||||
contentTypeForExtension,
|
||||
hashedAsset,
|
||||
sha256Hex,
|
||||
writeMobileWebBundleTree
|
||||
} from './mobile-web-bundle-manifest.mjs'
|
||||
|
||||
describe('hashedAsset', () => {
|
||||
it('refuses an extension with no registered content type', () => {
|
||||
// Unknown content type must fail rather than leave phone guessing how to serve addressed bytes.
|
||||
expect(() => hashedAsset(Buffer.from('body'), 'wasm')).toThrow(/no content type registered/)
|
||||
})
|
||||
})
|
||||
|
||||
describe('writeMobileWebBundleTree', () => {
|
||||
it('marks a dark build outside the manifest, so its buildId is the same tree’s', async () => {
|
||||
const outDir = await mkdtemp(join(tmpdir(), 'mobile-web-bundle-manifest-'))
|
||||
try {
|
||||
const bytes = Buffer.from('<!doctype html>\n', 'utf8')
|
||||
const tree = (env) =>
|
||||
writeMobileWebBundleTree({
|
||||
outDir,
|
||||
written: [
|
||||
{
|
||||
path: 'index.html',
|
||||
bytes,
|
||||
sha256: sha256Hex(bytes),
|
||||
byteLength: bytes.byteLength,
|
||||
contentType: contentTypeForExtension('html')
|
||||
}
|
||||
],
|
||||
desktopVersion: '1.0.0',
|
||||
protocolWindow: { runtimeProtocolVersion: 3, minCompatibleRuntimeProtocolVersion: 3 },
|
||||
env
|
||||
})
|
||||
const dark = await tree({ ORCA_SIDEBAR_INPUTS: 'main' })
|
||||
expect(existsSync(join(outDir, 'ORCA_SIDEBAR_INPUTS_MAIN'))).toBe(true)
|
||||
const off = await tree({})
|
||||
expect(existsSync(join(outDir, 'ORCA_SIDEBAR_INPUTS_MAIN'))).toBe(false)
|
||||
expect(dark.manifest.buildId).toBe(off.manifest.buildId)
|
||||
} finally {
|
||||
await rm(outDir, { recursive: true, force: true })
|
||||
}
|
||||
})
|
||||
})
|
||||
@@ -1,99 +0,0 @@
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import {
|
||||
MOBILE_WEB_BUNDLE_MAX_ROUTE_GRANTS,
|
||||
MobileWebBundleRouteSchema
|
||||
} from '../../../../src/shared/mobile-web-bundle/manifest-contract.ts'
|
||||
import { resolveMobileWebPageRoutes } from './build-mobile-web-app-bundle.mjs'
|
||||
import { MOBILE_WEB_PAGE_ROUTES } from './mobile-web-page-routes.mjs'
|
||||
import { routePathnameFromKey } from '../../mobile-web-app/mobile-web-app-route-manifest.mjs'
|
||||
|
||||
// Test declared screens separately from bundle mechanics so route inventory can grow without coupling builder test size.
|
||||
|
||||
describe('the page routes the manifest declares', () => {
|
||||
it('turns a route key into the URL pattern expo-router gives it', () => {
|
||||
expect(routePathnameFromKey('./h/[hostId]/index.tsx')).toBe('/h/[hostId]')
|
||||
expect(routePathnameFromKey('./h/[hostId]/tasks.tsx')).toBe('/h/[hostId]/tasks')
|
||||
expect(routePathnameFromKey('./h/[hostId]/session/[worktreeId].tsx')).toBe(
|
||||
'/h/[hostId]/session/[worktreeId]'
|
||||
)
|
||||
})
|
||||
|
||||
it('answers null for a layout, which is not a screen anyone navigates to', () => {
|
||||
expect(routePathnameFromKey('./h/_layout.tsx')).toBeNull()
|
||||
expect(routePathnameFromKey('./h/[hostId]/_layout.tsx')).toBeNull()
|
||||
})
|
||||
|
||||
// Synthetic optional-grant input checks member-by-member mapping; newly declared field must survive builder map before reaching phone.
|
||||
it('carries an optional grant list through, and writes no key for a route without one', () => {
|
||||
expect(
|
||||
resolveMobileWebPageRoutes(
|
||||
['./h/[hostId]/index.tsx', './h/[hostId]/tasks.tsx'],
|
||||
[
|
||||
{
|
||||
pathname: '/h/[hostId]',
|
||||
grants: ['navigate'],
|
||||
optionalGrants: ['externalNavigation']
|
||||
},
|
||||
{ pathname: '/h/[hostId]/tasks', grants: ['navigate'], optionalGrants: [] }
|
||||
]
|
||||
)
|
||||
).toEqual([
|
||||
{ pathname: '/h/[hostId]', grants: ['navigate'], optionalGrants: ['externalNavigation'] },
|
||||
{ pathname: '/h/[hostId]/tasks', grants: ['navigate'] }
|
||||
])
|
||||
})
|
||||
|
||||
it('carries the host-area declaration through, and writes no key where there is none', () => {
|
||||
expect(
|
||||
resolveMobileWebPageRoutes(
|
||||
['./h/[hostId]/index.tsx', './h/[hostId]/tasks.tsx'],
|
||||
[
|
||||
{ pathname: '/h/[hostId]', grants: ['navigate'], canOwnHostArea: true },
|
||||
{ pathname: '/h/[hostId]/tasks', grants: ['navigate'] }
|
||||
]
|
||||
)
|
||||
).toEqual([
|
||||
{ pathname: '/h/[hostId]', grants: ['navigate'], canOwnHostArea: true },
|
||||
{ pathname: '/h/[hostId]/tasks', grants: ['navigate'] }
|
||||
])
|
||||
})
|
||||
|
||||
/**
|
||||
* The wide iPad's host-area session is granted every served route's list, so its in-page hops
|
||||
* stay in the page. Bounded by what one route can be granted, so that grant never outgrows one route's.
|
||||
*/
|
||||
|
||||
// The phone refuses the whole manifest over one bad route, which takes every page down.
|
||||
it('declares only routes the manifest schema accepts', () => {
|
||||
for (const route of MOBILE_WEB_PAGE_ROUTES) {
|
||||
expect(
|
||||
MobileWebBundleRouteSchema.safeParse(route).error?.issues ?? [],
|
||||
route.pathname
|
||||
).toEqual([])
|
||||
}
|
||||
})
|
||||
|
||||
it('holds the optional lane to the manifest grammar and its own ceiling', () => {
|
||||
// Released shells read each list against the ceiling on its own, so the writer bounds each the same way.
|
||||
const withOptional = (optionalGrants, grants = []) =>
|
||||
MobileWebBundleRouteSchema.safeParse({ pathname: '/h/[hostId]', grants, optionalGrants })
|
||||
.success
|
||||
expect(withOptional(['externalNavigation'])).toBe(true)
|
||||
expect(withOptional(['native.externalNavigation'])).toBe(false)
|
||||
const names = (count, prefix) =>
|
||||
Array.from({ length: count }, (_value, index) => `${prefix}${String(index)}`)
|
||||
const cap = MOBILE_WEB_BUNDLE_MAX_ROUTE_GRANTS
|
||||
expect(withOptional(names(cap, 'opt'), names(cap, 'req'))).toBe(true)
|
||||
expect(withOptional(names(cap + 1, 'opt'))).toBe(false)
|
||||
})
|
||||
|
||||
it('fails the build on a declaration the bundle cannot render', () => {
|
||||
// Declared-but-unbundled route opens page then paints Unmatched; catch mismatch at declaration.
|
||||
expect(() =>
|
||||
resolveMobileWebPageRoutes(
|
||||
['./h/[hostId]/index.tsx'],
|
||||
[{ pathname: '/h/[hostId]/gone', grants: [] }]
|
||||
)
|
||||
).toThrow('has no module in the bundle')
|
||||
})
|
||||
})
|
||||
@@ -1,19 +0,0 @@
|
||||
import { mkdtemp, rm, writeFile } from 'node:fs/promises'
|
||||
import { tmpdir } from 'node:os'
|
||||
import { join } from 'node:path'
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import { assertNoCarriageReturnsInSource } from './mobile-web-source-line-endings.mjs'
|
||||
|
||||
describe('assertNoCarriageReturnsInSource', () => {
|
||||
it('rejects a CRLF source file, because CRLF changes every asset hash and the buildId', async () => {
|
||||
const scratch = await mkdtemp(join(tmpdir(), 'orca-mobile-web-eol-'))
|
||||
try {
|
||||
await writeFile(join(scratch, 'route.tsx'), 'const a = 1\r\nconst b = 2\r\n', 'utf8')
|
||||
await expect(assertNoCarriageReturnsInSource(scratch)).rejects.toThrow(
|
||||
/CRLF in mobile web source/
|
||||
)
|
||||
} finally {
|
||||
await rm(scratch, { recursive: true, force: true })
|
||||
}
|
||||
})
|
||||
})
|
||||
@@ -5190,8 +5190,8 @@
|
||||
"src/renderer/src/components/github/github-work-item-mutation-target.test.ts": 348,
|
||||
"src/renderer/src/components/github/use-image-input.test.ts": 2619,
|
||||
"src/renderer/src/components/gitlab-item-dialog/use-gitlab-primary-actions.test.ts": 2141,
|
||||
"src/renderer/src/components/host-picker/bounded-host-list.test.tsx": 667,
|
||||
"src/renderer/src/components/host-picker/host-list-surfaces.large-config.test.tsx": 2963,
|
||||
"src/renderer/src/components/host-picker/HostListSearchField.test.tsx": 667,
|
||||
"src/renderer/src/components/sidebar/project-admission/host-selection/AddRepoHostSelector.large-config.test.tsx": 2963,
|
||||
"src/renderer/src/components/jira-attachment-image.test.tsx": 2117,
|
||||
"src/renderer/src/components/jira-connect-scoped-token.test.tsx": 1047,
|
||||
"src/renderer/src/components/jira-issue-assignee-control.test.tsx": 2875,
|
||||
@@ -5606,7 +5606,7 @@
|
||||
"src/renderer/src/components/settings/form-controls/SettingsFormControls.segmented-control.test.tsx": 730,
|
||||
"src/renderer/src/components/settings/shortcuts/ShortcutFilterRail.test.ts": 273,
|
||||
"src/renderer/src/components/settings/shortcuts/ShortcutsPane.provenance.test.tsx": 2302,
|
||||
"src/renderer/src/components/settings/repository/execution/SparsePresetSettingsSection.test.tsx": 744,
|
||||
"src/renderer/src/components/settings/repository/worktrees/SparsePresetSettingsSection.test.tsx": 744,
|
||||
"src/renderer/src/components/settings/ssh/server-actions/SshHostDeltaMoveDialog.test.tsx": 438,
|
||||
"src/renderer/src/components/settings/ssh/server-actions/SshHostRecoverServerAction.test.tsx": 669,
|
||||
"src/renderer/src/components/settings/ssh/SshPane.test.tsx": 1699,
|
||||
@@ -5636,23 +5636,23 @@
|
||||
"src/renderer/src/components/settings/notifications/notification-host-pending-save.test.tsx": 2029,
|
||||
"src/renderer/src/components/settings/repository/RepositoryJiraProjectSection.test.tsx": 463,
|
||||
"src/renderer/src/components/settings/repository/RepositoryPaneDraftInput.test.tsx": 314,
|
||||
"src/renderer/src/components/settings/repository/execution/RepositoryHostSetupsSection.settings-entry.test.tsx": 2007,
|
||||
"src/renderer/src/components/settings/repository/execution/RepositoryWorktreeDefaultsSection.test.tsx": 495,
|
||||
"src/renderer/src/components/settings/repository/hosts/RepositoryHostSetupsSection.settings-entry.test.tsx": 2007,
|
||||
"src/renderer/src/components/settings/repository/worktrees/RepositoryWorktreeDefaultsSection.test.tsx": 495,
|
||||
"src/renderer/src/components/settings/repository/identity/RepositoryIconPicker.github-avatar-refresh.test.tsx": 615,
|
||||
"src/renderer/src/components/settings/runtime-environments/pairing/runtime-share-computer-button.test.tsx": 2092,
|
||||
"src/renderer/src/components/settings/navigation/settings-project-list.test.ts": 99,
|
||||
"src/renderer/src/components/settings/source-control/source-control-action-card-layout.test.tsx": 4551,
|
||||
"src/renderer/src/components/settings/source-control/source-control-action-permission-draft.test.tsx": 6938,
|
||||
"src/renderer/src/components/settings/ssh/targets/ssh-target-draft.test.ts": 72,
|
||||
"src/renderer/src/components/ssh-host-form/ssh-target-draft.test.ts": 72,
|
||||
"src/renderer/src/components/settings/ssh/targets/ssh-target-list-model.test.ts": 56,
|
||||
"src/renderer/src/components/integrations/task-trackers/linear-integration-card.test.tsx": 1414,
|
||||
"src/renderer/src/components/settings/appearance/themes/use-catalog-app-themes.test.ts": 2159,
|
||||
"src/renderer/src/components/settings/form-controls/use-debounced-settings-text-draft.test.ts": 308,
|
||||
"src/renderer/src/components/settings/repository/execution/use-repository-hook-settings-draft.test.tsx": 586,
|
||||
"src/renderer/src/components/settings/repository/hooks/use-repository-hook-settings-draft.test.tsx": 586,
|
||||
"src/renderer/src/components/settings/repository/hooks/use-repository-issue-command-wsl-stopped.test.ts": 523,
|
||||
"src/renderer/src/components/settings/runtime-environments/catalog/use-runtime-environment-catalog.test.tsx": 2252,
|
||||
"src/renderer/src/components/settings/runtime-environments/catalog/use-runtime-environment-mutation-actions.test.tsx": 2069,
|
||||
"src/renderer/src/components/settings/session-history/use-session-search-status.test.tsx": 477,
|
||||
"src/renderer/src/components/session-search/use-session-search-status.test.tsx": 477,
|
||||
"src/renderer/src/components/settings/accounts/usage/use-zcode-plan-credentials.test.tsx": 880,
|
||||
"src/renderer/src/lib/directory-path-suggestion-filter.scan-budget.test.ts": 68,
|
||||
"src/renderer/src/lib/directory-path-suggestion-filter.test.ts": 51,
|
||||
|
||||
@@ -1,118 +0,0 @@
|
||||
import assert from 'node:assert/strict'
|
||||
import { copyFileSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs'
|
||||
import { join, resolve } from 'node:path'
|
||||
import { parse } from 'yaml'
|
||||
import { runProcessSync } from '@orca/process-host'
|
||||
import { auditToolEntry, installAuditTools } from './run-audit-tool.mjs'
|
||||
|
||||
const root = resolve(import.meta.dirname, '../../../..')
|
||||
const installed = installAuditTools(root)
|
||||
assert.equal(installed.code, 0, 'Frozen, script-free audit tool install failed')
|
||||
|
||||
const scratch = join(root, 'tmp')
|
||||
mkdirSync(scratch, { recursive: true })
|
||||
const fixture = mkdtempSync(join(scratch, 'locked audit tools '))
|
||||
const toolManifest = JSON.parse(readFileSync(join(root, 'config/audit-tools/package.json'), 'utf8'))
|
||||
|
||||
function command(program, args, expectedCode = 0) {
|
||||
const result = runProcessSync({ program, args, cwd: fixture, timeoutMs: 60_000 })
|
||||
assert.equal(result.timedOut, false, `${program} timed out`)
|
||||
assert.equal(result.signal, null, `${program} received ${result.signal}`)
|
||||
assert.equal(result.code, expectedCode, `${result.stdout}\n${result.stderr}`)
|
||||
return result.stdout
|
||||
}
|
||||
|
||||
function tool(name, args, expectedCode = 0) {
|
||||
return command(process.execPath, [auditToolEntry(name, root), ...args], expectedCode)
|
||||
}
|
||||
|
||||
function write(file, value) {
|
||||
writeFileSync(join(fixture, file), value)
|
||||
}
|
||||
|
||||
const cleanComponent = 'export default function App() { return <button>Ready</button> }\n'
|
||||
const indexKeyComponent =
|
||||
'export default function App() { return <div>{["one"].map((text, index) => <span key={index}>{text}</span>)}</div> }\n'
|
||||
const doctorArgs = [
|
||||
'.',
|
||||
'--yes',
|
||||
'--no-dead-code',
|
||||
'--no-supply-chain',
|
||||
'--no-telemetry',
|
||||
'--no-cache',
|
||||
'--json',
|
||||
'--blocking',
|
||||
'warning'
|
||||
]
|
||||
|
||||
try {
|
||||
command('git', ['init', '--quiet'])
|
||||
command('git', ['config', 'core.hooksPath', join(fixture, '.git', 'disabled-hooks')])
|
||||
command('git', ['config', 'commit.gpgSign', 'false'])
|
||||
write(
|
||||
'package.json',
|
||||
JSON.stringify({ name: 'locked-audit-smoke', private: true, dependencies: { react: '19.2.8' } })
|
||||
)
|
||||
write('App.tsx', cleanComponent)
|
||||
write('knip.json', JSON.stringify({ entry: ['App.tsx'], project: ['*.tsx'] }))
|
||||
|
||||
for (const name of ['react-doctor', 'knip']) {
|
||||
assert.equal(tool(name, ['--version']).trim(), toolManifest.dependencies[name])
|
||||
}
|
||||
|
||||
const clean = JSON.parse(tool('react-doctor', doctorArgs))
|
||||
assert.equal(clean.ok, true)
|
||||
assert.ok(clean.projects.some((project) => project.analyzedFiles.includes('App.tsx')))
|
||||
tool('knip', ['--config', 'knip.json', '--files'])
|
||||
|
||||
write('App.tsx', indexKeyComponent)
|
||||
command('git', ['add', '.'])
|
||||
command('git', [
|
||||
'-c',
|
||||
'user.name=Audit tool smoke',
|
||||
'-c',
|
||||
'user.email=audit-smoke@example.invalid',
|
||||
'commit',
|
||||
'--quiet',
|
||||
'-m',
|
||||
'Baseline'
|
||||
])
|
||||
write('Changed.tsx', indexKeyComponent.replace('function App', 'function Changed'))
|
||||
command('git', ['add', 'Changed.tsx'])
|
||||
const changed = JSON.parse(
|
||||
tool('react-doctor', [...doctorArgs, '--scope', 'lines', '--base', 'HEAD'], 1)
|
||||
)
|
||||
assert.ok(changed.diagnostics.some((item) => item.filePath.endsWith('Changed.tsx')))
|
||||
assert.ok(changed.diagnostics.every((item) => !item.filePath.endsWith('App.tsx')))
|
||||
|
||||
write('Orphan.tsx', 'export const orphan = true\n')
|
||||
assert.match(tool('knip', ['--config', 'knip.json', '--files'], 1), /Orphan\.tsx/)
|
||||
|
||||
const stale = join(fixture, 'config', 'audit-tools')
|
||||
mkdirSync(stale, { recursive: true })
|
||||
mkdirSync(join(fixture, 'config', 'patches'), { recursive: true })
|
||||
const toolPolicy = parse(
|
||||
readFileSync(join(root, 'config/audit-tools/pnpm-workspace.yaml'), 'utf8')
|
||||
)
|
||||
for (const patch of Object.values(toolPolicy.patchedDependencies ?? {})) {
|
||||
copyFileSync(join(root, 'config/audit-tools', patch), join(stale, patch))
|
||||
}
|
||||
for (const file of ['pnpm-lock.yaml', 'pnpm-workspace.yaml']) {
|
||||
copyFileSync(join(root, 'config', 'audit-tools', file), join(stale, file))
|
||||
}
|
||||
writeFileSync(
|
||||
join(stale, 'package.json'),
|
||||
JSON.stringify({
|
||||
...toolManifest,
|
||||
dependencies: { ...toolManifest.dependencies, knip: '0.0.0' }
|
||||
})
|
||||
)
|
||||
const rejected = installAuditTools(fixture, (spec) => runProcessSync({ ...spec, stdio: 'pipe' }))
|
||||
assert.notEqual(rejected.code, 0, 'A stale tool lockfile was accepted')
|
||||
assert.match(`${rejected.stdout}\n${rejected.stderr}`, /OUTDATED_LOCKFILE/)
|
||||
console.log(
|
||||
'Locked audit tools: real analysis, changed-line filtering, findings and stale-lock rejection passed'
|
||||
)
|
||||
} finally {
|
||||
rmSync(fixture, { recursive: true, force: true })
|
||||
}
|
||||
@@ -1,4 +1,4 @@
|
||||
import { mkdtemp, rm, writeFile } from 'node:fs/promises'
|
||||
import { mkdtemp, rm } from 'node:fs/promises'
|
||||
import { tmpdir } from 'node:os'
|
||||
import path from 'node:path'
|
||||
import process from 'node:process'
|
||||
@@ -36,29 +36,4 @@ describe('validate-plugin-files', () => {
|
||||
expect(result.code).toBe(1)
|
||||
expect(result.stderr).toContain('panel/index.html')
|
||||
}, 60_000)
|
||||
|
||||
it('passes a scaffolded plugin, explaining why there is no release entry outside Git', async () => {
|
||||
const dir = path.join(await tempRoot(), 'dusk')
|
||||
await createPluginFromTemplate({ dir, template: 'theme', publisher: 'acme' })
|
||||
const result = await validate(dir)
|
||||
expect(result.code, result.stderr).toBe(0)
|
||||
expect(result.stdout).toContain('not in a Git repository')
|
||||
}, 60_000)
|
||||
|
||||
it('passes a language pack that translates protected copy, warning that Orca ignores it', async () => {
|
||||
const dir = path.join(await tempRoot(), 'portuguese')
|
||||
await createPluginFromTemplate({ dir, template: 'language-pack', publisher: 'acme' })
|
||||
await writeFile(
|
||||
path.join(dir, 'locales', 'pt-BR.json'),
|
||||
JSON.stringify({
|
||||
common: { cancel: 'Cancelar' },
|
||||
components: { 'native-chat': { approval: { allow: 'Permitir', deny: 'Negar' } } }
|
||||
})
|
||||
)
|
||||
const result = await validate(dir)
|
||||
expect(result.code, result.stderr).toBe(0)
|
||||
expect(result.stderr).toContain(
|
||||
'warning: contributes.languagePacks "pt-BR" (locales/pt-BR.json): 2 protected strings are ignored'
|
||||
)
|
||||
}, 60_000)
|
||||
})
|
||||
|
||||
@@ -272,6 +272,7 @@ const RATCHET_SHARED_MODULES = {
|
||||
'config/scripts/static-analysis/ratchets/react-compiler/react-compiler-hazards.mjs': [
|
||||
'check-react-compiler-compat-ratchet.mjs'
|
||||
],
|
||||
'config/react-compiler-uncompiled-files.txt': ['check-react-compiler-compat-ratchet.mjs'],
|
||||
'config/scripts/localization/reactive-translate/render-path-translate.mjs': [
|
||||
'check-render-path-translate-ratchet.mjs'
|
||||
]
|
||||
|
||||
@@ -1,80 +0,0 @@
|
||||
# Windows session-search file-ID integration reproduction
|
||||
|
||||
Opt-in Windows/NTFS harness for #20551. Run from the fix workspace root with
|
||||
dependencies, the Electron binary, and Git object `9845bef63a6` available.
|
||||
Everything generated stays under ignored `notes/search-ipc/`; each run gets fresh
|
||||
roots and a profile. No real transcripts, WSL discovery, desktop windows, or user
|
||||
profile are used. The synthetic file is recreated until NTFS assigns a real inode
|
||||
above `Number.MAX_SAFE_INTEGER`; failure to obtain one fails the test.
|
||||
|
||||
```powershell
|
||||
$env:ORCA_BACKGROUND_LAUNCH='1'
|
||||
pnpm exec esbuild config/scripts/session-search-file-id-e2e/run.ts --bundle --platform=node --format=esm --packages=external --outfile=notes/search-ipc/run.mjs
|
||||
node notes/search-ipc/run.mjs red
|
||||
# Expected exit 1: initial indexing/query succeeds, subsequent reconciliation fails.
|
||||
node notes/search-ipc/run.mjs green
|
||||
# Expected exit 0 for both the lifecycle and fresh-host restart phases.
|
||||
node config/scripts/session-search-file-id-e2e/verify.cjs
|
||||
```
|
||||
|
||||
Run red and green sequentially: their build step reuses the exported source tree.
|
||||
The verifier checks the expected red failure, green reports, identical oracle
|
||||
expressions after formatting normalization, and that exactly the two file-ID
|
||||
SELECT source files differ. It does not turn an arbitrary red failure into success.
|
||||
|
||||
## Exact topology
|
||||
|
||||
The runner exports **LOCAL integration overlay** #20516 head
|
||||
`9845bef63a6d0b80ec37af82b5b275287b8e17df` with `git archive`, then bundles the real
|
||||
scanner entry and parent modules with esbuild. It does not check out, stage, or
|
||||
push overlay sources. Green changes only the two SELECT projections to the CAST
|
||||
expressions in #20551; red retains the original projections. CLI #20514 is unused.
|
||||
|
||||
An isolated, windowless Electron host installs the production child search
|
||||
enablement using fixture settings. The production shared scanner client invokes
|
||||
`spawnAiVaultServiceProcess`, which forks Electron with `ELECTRON_RUN_AS_NODE=1`
|
||||
and the real `session-scanner-service-entry`. That child owns the production
|
||||
instance, indexer, SQLite search engine, and IPC request handling.
|
||||
|
||||
Marker queries come from **separate Node client processes over a real Windows
|
||||
named pipe**, through production `UnixSocketTransport`, production `RpcDispatcher`
|
||||
and `AI_VAULT_METHODS`, then the search registry/service and scanner IPC. Status
|
||||
polls and default-off/disabled responses also exercise registered handlers directly.
|
||||
An independent read-only SQLite connection verifies active FTS rows and committed
|
||||
file metadata against filesystem size/mtime. The transcript-consumer observation
|
||||
logs actual replace/append modes without supplying messages or search results.
|
||||
|
||||
Labelled fixture seams, identical in both variants:
|
||||
|
||||
- Parent root resolution returns the existing `isolatedScanRoots` fixture.
|
||||
- `getSettings` supplies the isolated JSON policy; real enablement/settings-change functions apply it.
|
||||
- The child's allowlisted environment includes `ORCA_BACKGROUND_LAUNCH=1`.
|
||||
- Passive child PID, IPC, stderr, and transcript-read observations are added.
|
||||
- The unused default RPC method catalog is excluded; the dispatcher receives the production `AI_VAULT_METHODS` explicitly. Its runtime context supplies only a fixture runtime ID.
|
||||
|
||||
## Oracle and evidence
|
||||
|
||||
Default-off creates no DB and returns disabled. Enablement indexes the marker;
|
||||
two **real default 20-second recent timer cycles** and two explicit full passes
|
||||
preserve it. An append becomes searchable; a rename replacement with equal byte
|
||||
length and exactly restored mtime removes the old marker and adds the new one.
|
||||
The scanner restarts, then a second Electron host opens the same profile/DB and
|
||||
queries again. Disablement followed by an append, explicit reconcile, and 21-second
|
||||
wait leaves the DB unchanged and the new marker absent.
|
||||
|
||||
`red-latest.json` / `green-latest.json` locate each run. Reports contain parent and
|
||||
scanner PIDs, executable/Node/Electron versions, IPC events, raw unsafe inode,
|
||||
queries, DB metadata, read modes, and scanner exit codes. `*-stages.jsonl` gives
|
||||
live progress; `process-*.log` preserves complete output. `comparison.json` records
|
||||
the two-source-only comparison. The production scanner shutdown protocol closes
|
||||
only recorded children; the runner waits for its own Electron hosts and external
|
||||
clients. Profiles/DBs remain as evidence, not running services.
|
||||
|
||||
## Boundaries not exercised
|
||||
|
||||
This is not a packaged/full Orca desktop launch. The host and scanner are bundled
|
||||
from production sources by this harness, not electron-vite's complete app build.
|
||||
The actual runtime authentication/metadata server, CLI routing, remote SSH/relay
|
||||
transport, and UI are not exercised. Named-pipe framing and dispatcher are real,
|
||||
but the harness connects them directly with a fixture token; it makes no claim
|
||||
about production authentication. No session-search UI exists in this topology.
|
||||
@@ -1,30 +0,0 @@
|
||||
const { connect } = require('node:net')
|
||||
const assert = require('node:assert/strict')
|
||||
assert.equal(process.env.ORCA_BACKGROUND_LAUNCH, '1')
|
||||
const socket = connect(process.argv[2])
|
||||
let buffer = ''
|
||||
socket.setEncoding('utf8')
|
||||
socket.setTimeout(10_000, () => socket.destroy(new Error('RPC client timeout')))
|
||||
socket.on('connect', () =>
|
||||
socket.write(
|
||||
`${JSON.stringify({
|
||||
id: 'file-id-query',
|
||||
authToken: 'isolated-fixture',
|
||||
method: 'aiVault.searchSessions',
|
||||
params: JSON.parse(process.argv[3])
|
||||
})}\n`
|
||||
)
|
||||
)
|
||||
socket.on('data', (chunk) => {
|
||||
buffer += String(chunk)
|
||||
const newline = buffer.indexOf('\n')
|
||||
if (newline === -1) {
|
||||
return
|
||||
}
|
||||
console.log(JSON.stringify({ pid: process.pid, response: JSON.parse(buffer.slice(0, newline)) }))
|
||||
socket.end()
|
||||
})
|
||||
socket.on('error', (error) => {
|
||||
console.error(error)
|
||||
process.exitCode = 1
|
||||
})
|
||||
@@ -1,325 +0,0 @@
|
||||
const { app } = require('electron')
|
||||
const assert = require('node:assert/strict')
|
||||
const fs = require('node:fs/promises')
|
||||
const { existsSync, appendFileSync } = require('node:fs')
|
||||
const { join } = require('node:path')
|
||||
const { DatabaseSync } = require('node:sqlite')
|
||||
const output = process.argv[2]
|
||||
const phase = process.argv[3]
|
||||
const profile = join(output, 'profile')
|
||||
app.setPath('userData', profile)
|
||||
app.setPath('sessionData', join(profile, 'chromium'))
|
||||
app.disableHardwareAcceleration()
|
||||
globalThis.__fileIdChildren = []
|
||||
const report = {
|
||||
phase,
|
||||
pid: process.pid,
|
||||
execPath: process.execPath,
|
||||
versions: process.versions,
|
||||
stages: [],
|
||||
children: [],
|
||||
stderr: [],
|
||||
ipc: []
|
||||
}
|
||||
globalThis.__fileIdObserveChild = (child) => {
|
||||
globalThis.__fileIdChildren.push(child)
|
||||
child.stderr.on('data', (chunk) => report.stderr.push(String(chunk)))
|
||||
child.on('message', (message) =>
|
||||
report.ipc.push({ pid: child.pid, type: message.type, operation: message.operation })
|
||||
)
|
||||
}
|
||||
const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms))
|
||||
const sessionId = 'aaaaaaaa-bbbb-4ccc-8ddd-eeeeeeeeeeee'
|
||||
const markers = {
|
||||
initial: 'quartzinitialmarker',
|
||||
append: 'cobaltappendedmarker',
|
||||
replacement: 'velvetreplacedmarker',
|
||||
disabled: 'tungstendisabledmarker'
|
||||
}
|
||||
let api
|
||||
let registration
|
||||
let transport
|
||||
const endpoint = `\\\\.\\pipe\\orca-file-id-${process.pid}`
|
||||
let settings = {}
|
||||
let transcript
|
||||
const database = join(profile, 'ai-vault', 'session-search.sqlite')
|
||||
function record(stage, data = {}) {
|
||||
const entry = { stage, at: Date.now(), ...data }
|
||||
report.stages.push(entry)
|
||||
appendFileSync(join(output, `${phase}-stages.jsonl`), `${JSON.stringify(entry)}\n`)
|
||||
console.log(stage, JSON.stringify(data))
|
||||
}
|
||||
function inspect(marker) {
|
||||
const db = new DatabaseSync(database, { readOnly: true })
|
||||
try {
|
||||
const query = db.prepare(
|
||||
'SELECT CAST(ino AS TEXT) AS ino, byte_offset, size_bytes, mtime_ms FROM files WHERE path = ?'
|
||||
)
|
||||
const rows = db
|
||||
.prepare(`SELECT s.session_id FROM messages_fts f JOIN messages m ON m.id=f.rowid
|
||||
JOIN sessions s ON s.id=m.session_row_id WHERE messages_fts MATCH ?`)
|
||||
.all(marker)
|
||||
return { file: query.get(transcript), sessions: rows.map((row) => row.session_id) }
|
||||
} finally {
|
||||
db.close()
|
||||
}
|
||||
}
|
||||
async function query(marker, present) {
|
||||
const result = await api.runProcess({
|
||||
program: process.env.ORCA_FILE_ID_NODE,
|
||||
args: [
|
||||
join(output, 'client.cjs'),
|
||||
endpoint,
|
||||
JSON.stringify({ query: `"${marker}"`, scope: 'conversation', freshness: 'indexed' })
|
||||
],
|
||||
env: process.env,
|
||||
timeoutMs: 15_000
|
||||
})
|
||||
assert.equal(result.code, 0, result.stderr)
|
||||
const external = JSON.parse(result.stdout)
|
||||
assert.equal(external.response.ok, true, JSON.stringify(external))
|
||||
const response = external.response.result
|
||||
assert.equal(response.kind, 'results', JSON.stringify(response))
|
||||
assert.equal(
|
||||
response.hits.some((hit) => hit.sessionId === sessionId),
|
||||
present,
|
||||
`RPC ${marker}`
|
||||
)
|
||||
const disk = inspect(marker)
|
||||
assert.equal(disk.sessions.includes(sessionId), present, `DB ${marker}`)
|
||||
const actual = await fs.stat(transcript)
|
||||
assert.equal(
|
||||
disk.file.byte_offset,
|
||||
actual.size,
|
||||
'Committed cursor covers actual transcript bytes'
|
||||
)
|
||||
assert.equal(disk.file.size_bytes, actual.size)
|
||||
assert.equal(disk.file.mtime_ms, actual.mtimeMs)
|
||||
record('query', { marker, present, clientPid: external.pid, endpoint, response, disk })
|
||||
}
|
||||
async function status() {
|
||||
return api.rpc('aiVault.searchStatus', {})
|
||||
}
|
||||
async function waitFor(predicate, label, timeout = 30_000) {
|
||||
const until = Date.now() + timeout
|
||||
while (Date.now() < until) {
|
||||
const current = await status()
|
||||
if (predicate(current)) {
|
||||
return current
|
||||
}
|
||||
await sleep(200)
|
||||
}
|
||||
throw new Error(`Timed out: ${label}`)
|
||||
}
|
||||
async function policy(next) {
|
||||
const before = settings
|
||||
settings = next
|
||||
await fs.writeFile(join(profile, 'fixture-settings.json'), JSON.stringify(settings))
|
||||
api.applySessionSearchSettingsChange(before, settings)
|
||||
}
|
||||
async function stopChild() {
|
||||
const children = [...globalThis.__fileIdChildren]
|
||||
api.resetAiVaultScannerServiceForTests()
|
||||
for (const child of children) {
|
||||
const until = Date.now() + 5000
|
||||
while (child.exitCode === null && child.signalCode === null && Date.now() < until) {
|
||||
await sleep(50)
|
||||
}
|
||||
assert.ok(
|
||||
child.exitCode !== null || child.signalCode !== null,
|
||||
`Child ${child.pid} did not exit`
|
||||
)
|
||||
if (!report.children.some((row) => row.pid === child.pid)) {
|
||||
report.children.push({
|
||||
pid: child.pid,
|
||||
spawnfile: child.spawnfile,
|
||||
spawnargs: child.spawnargs,
|
||||
exitCode: child.exitCode,
|
||||
signalCode: child.signalCode
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
async function run() {
|
||||
assert.equal(process.env.ORCA_BACKGROUND_LAUNCH, '1')
|
||||
await fs.mkdir(profile, { recursive: true })
|
||||
api = require('./production.js')
|
||||
api.setAppEnvironment({
|
||||
getPath: (name) => (name === 'userData' ? profile : app.getPath(name)),
|
||||
getAppPath: () => output,
|
||||
getVersion: () => app.getVersion(),
|
||||
isPackaged: () => false,
|
||||
onWillQuit: (handler) => app.on('will-quit', handler),
|
||||
exit: (code) => app.exit(code),
|
||||
getAppMetrics: () => app.getAppMetrics()
|
||||
})
|
||||
const dispatcher = new api.RpcDispatcher({
|
||||
methods: api.AI_VAULT_METHODS,
|
||||
runtime: { getRuntimeId: () => `file-id-${process.pid}` }
|
||||
})
|
||||
transport = new api.UnixSocketTransport({ endpoint, kind: 'named-pipe' })
|
||||
transport.onMessage((message, reply) => {
|
||||
void dispatcher
|
||||
.dispatch(JSON.parse(message))
|
||||
.then((response) => reply(JSON.stringify(response)))
|
||||
})
|
||||
await transport.start()
|
||||
record('rpc-transport', {
|
||||
endpoint,
|
||||
auth: 'fixture; production auth/metadata server not booted',
|
||||
methods: 'production AI_VAULT_METHODS',
|
||||
dispatcher: 'production RpcDispatcher'
|
||||
})
|
||||
const roots = {
|
||||
...api.isolatedScanRoots(join(output, 'roots')),
|
||||
wslHomeDirs: [],
|
||||
additionalCodexSessionsDirs: [],
|
||||
executionHostId: 'local'
|
||||
}
|
||||
process.env.ORCA_FILE_ID_ROOTS = JSON.stringify(roots)
|
||||
await fs.mkdir(roots.claudeProjectsDir, { recursive: true })
|
||||
transcript = join(roots.claudeProjectsDir, `${sessionId}.jsonl`)
|
||||
if (phase === 'restart') {
|
||||
settings = JSON.parse(await fs.readFile(join(profile, 'fixture-settings.json'), 'utf8'))
|
||||
assert.equal(settings.aiVaultSearch.enabled, true)
|
||||
const beforeRestart = inspect(markers.replacement)
|
||||
registration = api.installChildSessionSearchService({
|
||||
dataRoot: profile,
|
||||
getSettings: () => settings
|
||||
})
|
||||
await waitFor((s) => s.filesIndexed === 1 && s.phase === 'current', 'Electron host restart')
|
||||
await query(markers.append, false)
|
||||
await query(markers.replacement, true)
|
||||
assert.deepEqual(inspect(markers.replacement), beforeRestart)
|
||||
record('app-host-restart-same-db')
|
||||
await disableAndCheck()
|
||||
return
|
||||
}
|
||||
const body = `${api.claudeLines([markers.initial], sessionId, 0).join('\n')}\n`
|
||||
await fs.writeFile(transcript, body)
|
||||
let raw = await fs.stat(transcript, { bigint: true })
|
||||
for (let n = 0; raw.ino <= BigInt(Number.MAX_SAFE_INTEGER) && n < 512; n++) {
|
||||
await fs.unlink(transcript)
|
||||
await fs.writeFile(transcript, body)
|
||||
raw = await fs.stat(transcript, { bigint: true })
|
||||
}
|
||||
assert.ok(raw.ino > BigInt(Number.MAX_SAFE_INTEGER), 'NTFS must supply an actual unsafe inode')
|
||||
record('fixture', {
|
||||
transcript,
|
||||
rawIno: raw.ino.toString(),
|
||||
numericIno: BigInt(Number(raw.ino)).toString()
|
||||
})
|
||||
registration = api.installChildSessionSearchService({
|
||||
dataRoot: profile,
|
||||
getSettings: () => settings
|
||||
})
|
||||
assert.ok(registration)
|
||||
assert.equal((await status()).enabled, false)
|
||||
assert.deepEqual(await api.rpc('aiVault.searchSessions', { query: markers.initial }), {
|
||||
kind: 'unavailable',
|
||||
reason: 'disabled'
|
||||
})
|
||||
assert.equal(existsSync(database), false)
|
||||
record('default-off')
|
||||
await policy({ aiVaultSearch: { enabled: true, historyDays: null } })
|
||||
const initial = await waitFor(
|
||||
(s) => s.filesIndexed === 1 && s.phase === 'current',
|
||||
'initial indexing'
|
||||
)
|
||||
assert.equal(inspect(markers.initial).file.ino, BigInt(Number(raw.ino)).toString())
|
||||
await query(markers.initial, true)
|
||||
record('initial-indexing', { status: initial })
|
||||
let recent = initial
|
||||
for (let n = 0; n < 2; n++) {
|
||||
const previous = recent
|
||||
recent = await waitFor(
|
||||
(s) => s.lastReconcileAt > previous.lastReconcileAt,
|
||||
'recent timer reconciliation'
|
||||
)
|
||||
assert.equal(
|
||||
recent.lastSweepCompletedAt,
|
||||
initial.lastSweepCompletedAt,
|
||||
'Expected a recent pass'
|
||||
)
|
||||
await query(markers.initial, true)
|
||||
record('recent-pass', { status: recent })
|
||||
}
|
||||
for (let n = 0; n < 2; n++) {
|
||||
await api.reconcileSessionSearchInService()
|
||||
await query(markers.initial, true)
|
||||
record('full-pass', { status: await status() })
|
||||
}
|
||||
await fs.appendFile(
|
||||
transcript,
|
||||
`${api.claudeLines([markers.append], sessionId, 10).join('\n')}\n`
|
||||
)
|
||||
const frozen = new Date(Math.floor((await fs.stat(transcript)).mtimeMs))
|
||||
await fs.utimes(transcript, frozen, frozen)
|
||||
await api.reconcileSessionSearchInService()
|
||||
await query(markers.append, true)
|
||||
const before = await fs.stat(transcript)
|
||||
const replacement = `${transcript}.replacement`
|
||||
const replacementBody = (await fs.readFile(transcript, 'utf8')).replaceAll(
|
||||
markers.append,
|
||||
markers.replacement
|
||||
)
|
||||
assert.equal(Buffer.byteLength(replacementBody), before.size)
|
||||
await fs.writeFile(replacement, replacementBody)
|
||||
await fs.rename(replacement, transcript)
|
||||
await fs.utimes(transcript, before.atime, before.mtime)
|
||||
const after = await fs.stat(transcript)
|
||||
assert.equal(after.size, before.size)
|
||||
assert.equal(after.mtimeMs, before.mtimeMs)
|
||||
assert.notEqual(after.ino, before.ino)
|
||||
await api.reconcileSessionSearchInService()
|
||||
await query(markers.append, false)
|
||||
await query(markers.replacement, true)
|
||||
record('replacement', { beforeIno: before.ino, afterIno: after.ino })
|
||||
await stopChild()
|
||||
await waitFor((s) => s.filesIndexed === 1 && s.phase === 'current', 'scanner restart')
|
||||
await query(markers.append, false)
|
||||
await query(markers.replacement, true)
|
||||
record('service-restart')
|
||||
}
|
||||
async function disableAndCheck() {
|
||||
await policy({ aiVaultSearch: { enabled: false, historyDays: null } })
|
||||
await waitFor((s) => !s.enabled, 'disable')
|
||||
const snapshot = inspect(markers.replacement)
|
||||
await fs.appendFile(
|
||||
transcript,
|
||||
`${api.claudeLines([markers.disabled], sessionId, 20).join('\n')}\n`
|
||||
)
|
||||
await api.reconcileSessionSearchInService()
|
||||
await sleep(21_000)
|
||||
assert.deepEqual(await api.rpc('aiVault.searchSessions', { query: markers.disabled }), {
|
||||
kind: 'unavailable',
|
||||
reason: 'disabled'
|
||||
})
|
||||
assert.deepEqual(inspect(markers.replacement), snapshot)
|
||||
assert.deepEqual(inspect(markers.disabled).sessions, [])
|
||||
record('disabled-no-indexing')
|
||||
}
|
||||
app.whenReady().then(async () => {
|
||||
try {
|
||||
await run()
|
||||
report.ok = true
|
||||
} catch (error) {
|
||||
report.ok = false
|
||||
report.error = error.stack
|
||||
console.error(error)
|
||||
} finally {
|
||||
registration?.dispose()
|
||||
await transport?.stop()
|
||||
if (api) {
|
||||
await stopChild().catch((error) => {
|
||||
report.cleanupError = String(error)
|
||||
report.ok = false
|
||||
})
|
||||
}
|
||||
if (report.stderr.some((text) => text.includes('[ai-vault-search]'))) {
|
||||
report.ok = false
|
||||
}
|
||||
await fs.writeFile(join(output, `report-${phase}.json`), JSON.stringify(report, null, 2))
|
||||
app.exit(report.ok ? 0 : 1)
|
||||
}
|
||||
})
|
||||
@@ -1,194 +0,0 @@
|
||||
import assert from 'node:assert/strict'
|
||||
import { mkdir, readFile, writeFile, copyFile } from 'node:fs/promises'
|
||||
import { resolve, join, relative } from 'node:path'
|
||||
import { createHash } from 'node:crypto'
|
||||
import { build } from 'esbuild'
|
||||
import { runProcess } from '@orca/process-host'
|
||||
|
||||
const root = process.cwd()
|
||||
const evidence = resolve('notes/search-ipc')
|
||||
const overlay = join(evidence, 'overlay')
|
||||
const wiring = '9845bef63a6'
|
||||
const mode = process.argv[2]
|
||||
assert.equal(process.platform, 'win32', 'This harness requires native Windows and NTFS')
|
||||
assert.ok(mode === 'red' || mode === 'green', 'Pass red or green')
|
||||
assert.equal(process.env.ORCA_BACKGROUND_LAUNCH, '1')
|
||||
const output = join(evidence, mode, String(Date.now()))
|
||||
await mkdir(output, { recursive: true })
|
||||
|
||||
async function command(program: string, args: string[]) {
|
||||
const result = await runProcess({ program, args, cwd: root, timeoutMs: 120_000 })
|
||||
assert.equal(result.code, 0, result.stderr)
|
||||
return result.stdout.trim()
|
||||
}
|
||||
|
||||
// The overlay is exported, never checked out or staged on the fix branch.
|
||||
await mkdir(overlay, { recursive: true })
|
||||
await command('git', [
|
||||
'archive',
|
||||
'--format=tar',
|
||||
`--output=${join(evidence, 'overlay.tar')}`,
|
||||
wiring,
|
||||
'src'
|
||||
])
|
||||
await command('tar', [
|
||||
'-xf',
|
||||
relative(root, join(evidence, 'overlay.tar')),
|
||||
'-C',
|
||||
relative(root, overlay)
|
||||
])
|
||||
const edits: { path: string; sha256: string }[] = []
|
||||
function replaceOnce(source: string, before: string, after: string) {
|
||||
assert.equal(source.split(before).length, 2, `Expected exactly one injection: ${before}`)
|
||||
return source.replace(before, after)
|
||||
}
|
||||
|
||||
const adapter = join(output, 'adapter.mjs')
|
||||
const source = (path: string) => JSON.stringify(join(overlay, 'src', path))
|
||||
await writeFile(
|
||||
adapter,
|
||||
`
|
||||
export { installChildSessionSearchService, applySessionSearchSettingsChange } from ${source('main/ai-vault-search/session-search-enablement.ts')};
|
||||
export { resetAiVaultScannerServiceForTests, reconcileSessionSearchInService } from ${source('main/ai-vault/session-scanner-service-spawn.ts')};
|
||||
export { setAppEnvironment } from ${source('shared/app-environment.ts')};
|
||||
export { isolatedScanRoots } from ${source('main/ai-vault/session-scanner-test-fixtures.ts')};
|
||||
export { claudeLines } from ${source('main/ai-vault-search/session-search-indexer-test-fixture.ts')};
|
||||
export { runProcess } from '@orca/process-host';
|
||||
export { UnixSocketTransport } from ${source('main/runtime/rpc/unix-socket-transport.ts')};
|
||||
export { RpcDispatcher } from ${source('main/runtime/rpc/dispatcher.ts')};
|
||||
export { AI_VAULT_METHODS } from ${source('main/runtime/rpc/methods/ai-vault.ts')};
|
||||
import { buildRegistry } from ${source('main/runtime/rpc/core.ts')};
|
||||
import { AI_VAULT_METHODS } from ${source('main/runtime/rpc/methods/ai-vault.ts')};
|
||||
const registry = buildRegistry(AI_VAULT_METHODS);
|
||||
export async function rpc(name, params) {
|
||||
const method = registry.get(name);
|
||||
if (!method || !name.startsWith('aiVault.search')) throw new Error('Unexpected method');
|
||||
return method.handler(method.params.parse(params), {});
|
||||
}
|
||||
`
|
||||
)
|
||||
|
||||
await build({
|
||||
entryPoints: {
|
||||
production: adapter,
|
||||
'session-scanner-service-entry': join(
|
||||
overlay,
|
||||
'src/main/ai-vault/session-scanner-service-entry.ts'
|
||||
)
|
||||
},
|
||||
outdir: output,
|
||||
platform: 'node',
|
||||
format: 'cjs',
|
||||
bundle: true,
|
||||
packages: 'external',
|
||||
define: { ORCA_FEATURE_WALL_ENABLED: 'true' },
|
||||
plugins: [
|
||||
{
|
||||
name: 'labelled-local-fixtures',
|
||||
setup(api) {
|
||||
api.onLoad({ filter: /\.ts$/ }, async (args) => {
|
||||
let contents = await readFile(args.path, 'utf8')
|
||||
const path = args.path.replaceAll('\\', '/')
|
||||
if (path.endsWith('/runtime/rpc/methods/rpc-method-registry.ts')) {
|
||||
// DispatcherOptions explicitly supplies AI_VAULT_METHODS; don't load unrelated default methods.
|
||||
contents = 'export const ALL_RPC_METHODS = []'
|
||||
}
|
||||
if (path.endsWith('/cached-session-list.ts')) {
|
||||
contents = replaceOnce(
|
||||
contents,
|
||||
' const [additionalCodexHomes, wslHomeDirs] = await Promise.all([',
|
||||
' return JSON.parse(process.env.ORCA_FILE_ID_ROOTS!);\n const [additionalCodexHomes, wslHomeDirs] = await Promise.all(['
|
||||
)
|
||||
}
|
||||
if (path.endsWith('/session-scanner-service-env.ts')) {
|
||||
contents = replaceOnce(
|
||||
contents,
|
||||
" env.ELECTRON_RUN_AS_NODE = '1'",
|
||||
" env.ORCA_BACKGROUND_LAUNCH = '1'\n env.ELECTRON_RUN_AS_NODE = '1'"
|
||||
)
|
||||
}
|
||||
if (path.endsWith('/session-scanner-service-spawn.ts')) {
|
||||
contents = replaceOnce(
|
||||
contents,
|
||||
' lowerAiVaultServicePriority(child.pid)',
|
||||
' globalThis.__fileIdObserveChild?.(child)\n lowerAiVaultServicePriority(child.pid)'
|
||||
)
|
||||
}
|
||||
if (path.endsWith('/session-scanner-service-entry.ts')) {
|
||||
contents = `import { registerTranscriptConsumer } from './session-transcript-consumers';
|
||||
registerTranscriptConsumer({beginRead: start => { console.error('[file-id-read]', JSON.stringify({mode:start.mode,path:start.candidate.file.path})); return null }});
|
||||
console.error('[file-id-child]', JSON.stringify({pid:process.pid,execPath:process.execPath,versions:process.versions,background:process.env.ORCA_BACKGROUND_LAUNCH}));\n${contents}`
|
||||
}
|
||||
if (mode === 'green' && path.endsWith('/session-search-store.ts')) {
|
||||
contents = replaceOnce(
|
||||
contents,
|
||||
'SELECT path, dev, ino, mtime_ms',
|
||||
'SELECT path, CAST(dev AS REAL) AS dev, CAST(ino AS REAL) AS ino, mtime_ms'
|
||||
)
|
||||
}
|
||||
if (mode === 'green' && path.endsWith('/session-search-index-writer.ts')) {
|
||||
contents = replaceOnce(
|
||||
contents,
|
||||
'SELECT dev, ino, byte_offset',
|
||||
'SELECT CAST(dev AS REAL) AS dev, CAST(ino AS REAL) AS ino, byte_offset'
|
||||
)
|
||||
}
|
||||
edits.push({
|
||||
path: path.replace(overlay.replaceAll('\\', '/'), ''),
|
||||
sha256: createHash('sha256').update(contents).digest('hex')
|
||||
})
|
||||
return { contents, loader: 'ts' }
|
||||
})
|
||||
}
|
||||
}
|
||||
]
|
||||
})
|
||||
await copyFile(
|
||||
join(root, 'config/scripts/session-search-file-id-e2e/host.cjs'),
|
||||
join(output, 'host.cjs')
|
||||
)
|
||||
await copyFile(
|
||||
join(root, 'config/scripts/session-search-file-id-e2e/client.cjs'),
|
||||
join(output, 'client.cjs')
|
||||
)
|
||||
await writeFile(
|
||||
join(output, 'topology.json'),
|
||||
JSON.stringify(
|
||||
{
|
||||
wiring: await command('git', ['rev-parse', wiring]),
|
||||
fix: await command('git', ['rev-parse', 'HEAD']),
|
||||
mode,
|
||||
injections: [
|
||||
'isolated root resolver',
|
||||
'background child env',
|
||||
'child PID/error/read observation',
|
||||
'unused default RPC catalog excluded; explicit production AI_VAULT_METHODS'
|
||||
],
|
||||
files: edits.sort((a, b) => a.path.localeCompare(b.path))
|
||||
},
|
||||
null,
|
||||
2
|
||||
)
|
||||
)
|
||||
await writeFile(join(evidence, `${mode}-latest.json`), JSON.stringify({ output }))
|
||||
for (const phase of ['lifecycle', 'restart']) {
|
||||
console.log(JSON.stringify({ mode, phase, output }))
|
||||
const result = await runProcess({
|
||||
program: join(root, 'node_modules/electron/dist/electron.exe'),
|
||||
args: [join(output, 'host.cjs'), output, phase],
|
||||
cwd: output,
|
||||
env: {
|
||||
...process.env,
|
||||
ORCA_BACKGROUND_LAUNCH: '1',
|
||||
ELECTRON_RUN_AS_NODE: undefined,
|
||||
ORCA_FILE_ID_NODE: process.execPath
|
||||
},
|
||||
timeoutMs: 180_000
|
||||
})
|
||||
await writeFile(join(output, `process-${phase}.log`), result.stdout + result.stderr)
|
||||
console.log(JSON.stringify({ mode, phase, code: result.code, timedOut: result.timedOut, output }))
|
||||
process.exitCode = result.code ?? 1
|
||||
if (process.exitCode !== 0) {
|
||||
break
|
||||
}
|
||||
}
|
||||
@@ -1,62 +0,0 @@
|
||||
const assert = require('node:assert/strict')
|
||||
const { readFileSync, writeFileSync } = require('node:fs')
|
||||
const { join, resolve } = require('node:path')
|
||||
const { createHash } = require('node:crypto')
|
||||
const { transformSync } = require('esbuild')
|
||||
const evidence = resolve('notes/search-ipc')
|
||||
const json = (path) => JSON.parse(readFileSync(path, 'utf8'))
|
||||
const red = json(join(evidence, 'red-latest.json')).output
|
||||
const green = json(join(evidence, 'green-latest.json')).output
|
||||
const before = json(join(red, 'topology.json'))
|
||||
const after = json(join(green, 'topology.json'))
|
||||
assert.equal(before.wiring, after.wiring)
|
||||
assert.deepEqual(before.injections, after.injections)
|
||||
const oldFiles = new Map(before.files.map((row) => [row.path, row.sha256]))
|
||||
assert.equal(oldFiles.size, after.files.length)
|
||||
const changed = after.files
|
||||
.filter((row) => oldFiles.get(row.path) !== row.sha256)
|
||||
.map((row) => row.path)
|
||||
.sort()
|
||||
assert.deepEqual(changed, [
|
||||
'/src/main/ai-vault-search/session-search-index-writer.ts',
|
||||
'/src/main/ai-vault-search/session-search-store.ts'
|
||||
])
|
||||
for (const name of ['host.cjs', 'client.cjs']) {
|
||||
// Ignore formatter-only differences; preserve every expression and assertion.
|
||||
const hash = (root) =>
|
||||
createHash('sha256')
|
||||
.update(
|
||||
transformSync(readFileSync(join(root, name), 'utf8'), {
|
||||
loader: 'js',
|
||||
minifyWhitespace: true
|
||||
}).code
|
||||
)
|
||||
.digest('hex')
|
||||
assert.equal(hash(red), hash(green), `Identical oracle: ${name}`)
|
||||
}
|
||||
const failed = json(join(red, 'report-lifecycle.json'))
|
||||
assert.equal(failed.ok, false)
|
||||
assert.match(failed.stderr.join(''), /RangeError: Value is too large/)
|
||||
assert.ok(failed.stages.some((row) => row.stage === 'initial-indexing'))
|
||||
const reports = [
|
||||
json(join(green, 'report-lifecycle.json')),
|
||||
json(join(green, 'report-restart.json'))
|
||||
]
|
||||
for (const report of reports) {
|
||||
assert.equal(report.ok, true)
|
||||
assert.ok(report.ipc.some((row) => row.operation === 'searchSessions'))
|
||||
assert.ok(report.stages.some((row) => row.stage === 'query' && row.clientPid !== report.pid))
|
||||
assert.ok(report.children.every((child) => child.exitCode === 0))
|
||||
}
|
||||
assert.notEqual(reports[0].pid, reports[1].pid)
|
||||
const result = {
|
||||
ok: true,
|
||||
wiring: before.wiring,
|
||||
changed,
|
||||
red,
|
||||
green,
|
||||
parentPids: [failed.pid, ...reports.map((row) => row.pid)],
|
||||
childPids: [failed, ...reports].flatMap((report) => report.children.map((child) => child.pid))
|
||||
}
|
||||
writeFileSync(join(evidence, 'comparison.json'), JSON.stringify(result, null, 2))
|
||||
console.log(JSON.stringify(result))
|
||||
+95
-3
@@ -16,9 +16,15 @@ import {
|
||||
} from '../../ratchet-baseline/ratchet-baseline.mjs'
|
||||
import {
|
||||
HAZARD_FIXES,
|
||||
LIVE_MODULE_READERS,
|
||||
VIRTUALIZER_HOOKS,
|
||||
findLiveReadWrappers,
|
||||
findMemoizedCalls,
|
||||
findSourceHazards,
|
||||
findVirtualizerMemoFlows,
|
||||
findVirtualizerWrappers,
|
||||
hookCallLines,
|
||||
renderLiveReadLines,
|
||||
renderStoreReadLines
|
||||
} from './react-compiler-hazards.mjs'
|
||||
|
||||
@@ -28,6 +34,8 @@ import {
|
||||
const SCAN_ROOT = 'src/renderer/src'
|
||||
const BAILOUT_BASELINE = 'config/react-compiler-bailout-baseline.txt'
|
||||
const HAZARD_BASELINE = 'config/react-compiler-hazard-baseline.txt'
|
||||
// The build leaves these files uncompiled, so their hazards cannot run.
|
||||
const UNCOMPILED_LIST = 'config/react-compiler-uncompiled-files.txt'
|
||||
const COMMAND = 'pnpm check:react-compiler-compat-ratchet'
|
||||
const NOT_SHIPPED =
|
||||
/(?:^|\/)__(?:mocks|fixtures|tests)__\/|\.(?:test|spec|bench)\.[cm]?tsx?$|[.-]test-|[.-]fixtures?\.tsx?$/
|
||||
@@ -93,6 +101,59 @@ function addTo(map, key, value) {
|
||||
map.set(key, [...(map.get(key) ?? []), value])
|
||||
}
|
||||
|
||||
function readUncompiledFiles(root) {
|
||||
const file = path.join(root, UNCOMPILED_LIST)
|
||||
if (!fs.existsSync(file)) {
|
||||
return new Set()
|
||||
}
|
||||
return new Set(
|
||||
fs
|
||||
.readFileSync(file, 'utf8')
|
||||
.split('\n')
|
||||
.map((line) => line.trim())
|
||||
.filter((line) => line && !line.startsWith('#'))
|
||||
)
|
||||
}
|
||||
|
||||
/** Virtualizer hooks plus every hook that returns one, followed through wrappers of wrappers. */
|
||||
function collectVirtualizerHooks(sources) {
|
||||
const hooks = new Map(VIRTUALIZER_HOOKS)
|
||||
for (let grew = true; grew;) {
|
||||
grew = false
|
||||
for (const [rel, text] of sources) {
|
||||
for (const { name, shape } of findVirtualizerWrappers(rel, text, hooks)) {
|
||||
if (!hooks.has(name)) {
|
||||
hooks.set(name, shape)
|
||||
grew = true
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
return hooks
|
||||
}
|
||||
|
||||
/** Live module-state readers plus every plain function that calls one, followed through wrappers. */
|
||||
function collectLiveReaders(sources) {
|
||||
const readers = new Set(LIVE_MODULE_READERS)
|
||||
for (let grew = true; grew;) {
|
||||
grew = false
|
||||
for (const [rel, text] of sources) {
|
||||
for (const name of findLiveReadWrappers(rel, text, readers)) {
|
||||
if (!readers.has(name)) {
|
||||
readers.add(name)
|
||||
grew = true
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
return readers
|
||||
}
|
||||
|
||||
function sourceLineOf(text, snippet) {
|
||||
const index = text.split('\n').findIndex((line) => line.includes(snippet.split('(')[0]))
|
||||
return index === -1 ? '?' : index + 1
|
||||
}
|
||||
|
||||
async function scanFile(rel, text, result) {
|
||||
const output = await transform(rel, text, COMPILER_OPTIONS)
|
||||
if (output.fatal) {
|
||||
@@ -105,15 +166,37 @@ async function scanFile(rel, text, result) {
|
||||
const message = error.message.split('\n')[0]
|
||||
addTo(result.diagnostics, rel, { line: lineAt(bytes, error.labels[0]?.start ?? 0), message })
|
||||
}
|
||||
if (result.uncompiled.has(rel)) {
|
||||
return
|
||||
}
|
||||
for (const { fn, text: snippet } of findVirtualizerMemoFlows(
|
||||
rel,
|
||||
text,
|
||||
output.code,
|
||||
result.virtualizerHooks
|
||||
)) {
|
||||
addTo(
|
||||
result.hazards,
|
||||
`${rel}#${fn}:virtualizer-in-memo-block`,
|
||||
`${sourceLineOf(text, snippet)}: ${snippet}`
|
||||
)
|
||||
}
|
||||
for (const hazard of findSourceHazards(rel, text)) {
|
||||
addTo(result.hazards, `${rel}#${hazard.fn}:${hazard.kind}`, `${hazard.line}: ${hazard.text}`)
|
||||
}
|
||||
const storeReadFns = new Set()
|
||||
for (const { fn, kind, name } of findMemoizedCalls(rel, output.code)) {
|
||||
for (const { fn, kind, name } of findMemoizedCalls(rel, output.code, result.liveReaders)) {
|
||||
if (kind === 'store-read') {
|
||||
storeReadFns.add(fn)
|
||||
continue
|
||||
}
|
||||
if (kind === 'live-read') {
|
||||
// A call inside the source's own useMemo or a closure keeps its written behavior.
|
||||
for (const line of renderLiveReadLines(rel, text, fn, name)) {
|
||||
addTo(result.hazards, `${rel}#${fn}:live-read-in-memo-block`, `${line}: ${name}()`)
|
||||
}
|
||||
continue
|
||||
}
|
||||
const lines = hookCallLines(rel, text, fn, name)
|
||||
addTo(result.hazards, `${rel}#${fn}:hook-in-memo-block`, `${lines.join(', ')}: ${name}()`)
|
||||
}
|
||||
@@ -126,8 +209,17 @@ async function scanFile(rel, text, result) {
|
||||
}
|
||||
|
||||
export async function scanRenderer(root = process.cwd()) {
|
||||
const result = { files: 0, compiled: 0, diagnostics: new Map(), hazards: new Map() }
|
||||
const pending = [...readTrackedSources(root, [SCAN_ROOT], isScannedPath)]
|
||||
const sources = [...readTrackedSources(root, [SCAN_ROOT], isScannedPath)]
|
||||
const result = {
|
||||
files: 0,
|
||||
compiled: 0,
|
||||
diagnostics: new Map(),
|
||||
hazards: new Map(),
|
||||
uncompiled: readUncompiledFiles(root),
|
||||
virtualizerHooks: collectVirtualizerHooks(sources),
|
||||
liveReaders: collectLiveReaders(sources)
|
||||
}
|
||||
const pending = [...sources]
|
||||
result.files = pending.length
|
||||
await Promise.all(
|
||||
Array.from({ length: IN_FLIGHT }, async () => {
|
||||
|
||||
@@ -31,6 +31,16 @@ export const HAZARD_FIXES = {
|
||||
'React Compiler caches this render-time `store.getState()` snapshot on unrelated inputs, so it',
|
||||
'goes stale. Read it in the event handler or effect that uses it, or select it with a hook.'
|
||||
],
|
||||
'virtualizer-in-memo-block': [
|
||||
'A TanStack virtualizer is one object mutated in place, so React Compiler serves rows, sizes or',
|
||||
'child elements cached on it after every scroll. Add the file to',
|
||||
'config/react-compiler-uncompiled-files.txt, owners that pass the virtualizer down included.'
|
||||
],
|
||||
'live-read-in-memo-block': [
|
||||
'React Compiler caches this render-time read of module state (a provider runtime context key or a',
|
||||
'structured selection) on its arguments, so it misses the module-level change. Add the file to',
|
||||
'config/react-compiler-uncompiled-files.txt, or subscribe to the state so a change re-renders.'
|
||||
],
|
||||
'hook-in-memo-block': [
|
||||
'React Compiler memoizes this hook call inside a cached block, so it runs only when the block',
|
||||
'recomputes (a conditional hook). Call the hook in its own top-level `const` and use the variable.'
|
||||
@@ -247,16 +257,19 @@ function isStoreRead(node) {
|
||||
)
|
||||
}
|
||||
|
||||
function memoizedCallKind(node) {
|
||||
function memoizedCallKind(node, liveReaders) {
|
||||
if (isStoreRead(node)) {
|
||||
return { kind: 'store-read', name: 'getState' }
|
||||
}
|
||||
const hook = calleeName(node.expression)
|
||||
return hook && HOOK_NAME.test(hook) ? { kind: 'hook', name: hook } : null
|
||||
const callee = calleeName(node.expression)
|
||||
if (callee && liveReaders.has(callee)) {
|
||||
return { kind: 'live-read', name: callee }
|
||||
}
|
||||
return callee && HOOK_NAME.test(callee) ? { kind: 'hook', name: callee } : null
|
||||
}
|
||||
|
||||
/** Hook calls and `getState()` reads the compiler placed inside a memo-cache guarded block. */
|
||||
export function findMemoizedCalls(fileName, compiledCode) {
|
||||
/** Hook calls, `getState()` reads and live module-state reads the compiler placed inside a memo-cache guarded block. */
|
||||
export function findMemoizedCalls(fileName, compiledCode, liveReaders = new Set()) {
|
||||
if (!compiledCode.includes('compiler-runtime')) {
|
||||
return []
|
||||
}
|
||||
@@ -271,7 +284,7 @@ export function findMemoizedCalls(fileName, compiledCode) {
|
||||
if (isFunctionNode(node)) {
|
||||
return
|
||||
}
|
||||
const call = ts.isCallExpression(node) ? memoizedCallKind(node) : null
|
||||
const call = ts.isCallExpression(node) ? memoizedCallKind(node, liveReaders) : null
|
||||
// Nested guarded blocks are walked once per enclosing block; keying by node dedupes them.
|
||||
if (call) {
|
||||
found.set(node, { fn, ...call })
|
||||
@@ -315,6 +328,20 @@ export function findMemoizedStoreReads(fileName, compiledCode) {
|
||||
|
||||
/** Source lines of render-time `getState()` calls in `fnName`; a useMemo/callback read is excluded. */
|
||||
export function renderStoreReadLines(fileName, text, fnName) {
|
||||
return renderCallLines(fileName, text, fnName, isStoreRead)
|
||||
}
|
||||
|
||||
/** Source lines of render-time calls to `callee` in `fnName`; a useMemo/callback call is excluded. */
|
||||
export function renderLiveReadLines(fileName, text, fnName, callee) {
|
||||
return renderCallLines(
|
||||
fileName,
|
||||
text,
|
||||
fnName,
|
||||
(node) => ts.isCallExpression(node) && calleeName(node.expression) === callee
|
||||
)
|
||||
}
|
||||
|
||||
function renderCallLines(fileName, text, fnName, matches) {
|
||||
const sourceFile = parseModule(fileName, text)
|
||||
const lines = new Set()
|
||||
for (const { name, node: root } of listReactFunctions(sourceFile)) {
|
||||
@@ -325,7 +352,7 @@ export function renderStoreReadLines(fileName, text, fnName) {
|
||||
if (node !== root && isFunctionNode(node)) {
|
||||
return
|
||||
}
|
||||
if (isStoreRead(node)) {
|
||||
if (matches(node)) {
|
||||
lines.add(lineOf(sourceFile, node))
|
||||
}
|
||||
ts.forEachChild(node, visit)
|
||||
@@ -335,6 +362,69 @@ export function renderStoreReadLines(fileName, text, fnName) {
|
||||
return [...lines].sort((a, b) => a - b)
|
||||
}
|
||||
|
||||
// Reads of module-level state that changes without a React update; a cache keyed on props keeps the old value.
|
||||
export const LIVE_MODULE_READERS = [
|
||||
// Both fold in providerRuntimeSessionGeneration (lib/provider-runtime-context.ts).
|
||||
'getProviderRuntimeContextKey',
|
||||
'getEnvironmentRuntimeContextKey',
|
||||
// Both read the selection lifetime registry in structured-agent-session-selection-controller.ts.
|
||||
'structuredSessionSelectionAuthority',
|
||||
'structuredSessionSelectionController'
|
||||
]
|
||||
|
||||
function moduleFunctionName(node) {
|
||||
if (ts.isFunctionDeclaration(node) && node.name) {
|
||||
return node.name.text
|
||||
}
|
||||
const parent = node.parent
|
||||
return (ts.isArrowFunction(node) || ts.isFunctionExpression(node)) &&
|
||||
ts.isVariableDeclaration(parent) &&
|
||||
ts.isIdentifier(parent.name) &&
|
||||
ts.isVariableStatement(parent.parent?.parent)
|
||||
? parent.name.text
|
||||
: null
|
||||
}
|
||||
|
||||
/** Module-scope plain functions whose own body calls a live reader, so their result is live too. */
|
||||
export function findLiveReadWrappers(fileName, text, readers) {
|
||||
if (![...readers].some((reader) => text.includes(reader))) {
|
||||
return []
|
||||
}
|
||||
const sourceFile = parseModule(fileName, text)
|
||||
const wrappers = []
|
||||
for (const statement of sourceFile.statements) {
|
||||
const candidates = ts.isFunctionDeclaration(statement)
|
||||
? [statement]
|
||||
: ts.isVariableStatement(statement)
|
||||
? statement.declarationList.declarations
|
||||
.map((declaration) => declaration.initializer && unwrap(declaration.initializer))
|
||||
.filter((init) => init && (ts.isArrowFunction(init) || ts.isFunctionExpression(init)))
|
||||
: []
|
||||
for (const fn of candidates) {
|
||||
const name = moduleFunctionName(fn)
|
||||
if (!name || isReactName(name) || readers.has(name)) {
|
||||
continue
|
||||
}
|
||||
let calls = false
|
||||
const visit = (node) => {
|
||||
if (calls || (node !== fn && isFunctionNode(node))) {
|
||||
return
|
||||
}
|
||||
if (ts.isCallExpression(node) && readers.has(calleeName(node.expression) ?? '')) {
|
||||
calls = true
|
||||
return
|
||||
}
|
||||
ts.forEachChild(node, visit)
|
||||
}
|
||||
visit(fn)
|
||||
if (calls) {
|
||||
wrappers.push(name)
|
||||
}
|
||||
}
|
||||
}
|
||||
return wrappers
|
||||
}
|
||||
|
||||
/** Source lines of `hook` calls in `fnName` that sit inside a larger expression. */
|
||||
export function hookCallLines(fileName, text, fnName, hook) {
|
||||
const sourceFile = parseModule(fileName, text)
|
||||
@@ -358,3 +448,204 @@ export function hookCallLines(fileName, text, fnName, hook) {
|
||||
}
|
||||
return lines.size > 0 ? [...lines].sort((a, b) => a - b) : ['?']
|
||||
}
|
||||
|
||||
// A TanStack virtualizer is one object mutated in place, so a cache keyed on it never refreshes.
|
||||
export const VIRTUALIZER_HOOKS = new Map([
|
||||
['useVirtualizer', 'direct'],
|
||||
['useWindowVirtualizer', 'direct']
|
||||
])
|
||||
const VIRTUALIZER_NAME = /^\w*[vV]irtualizer$/
|
||||
const VIRTUALIZER_TYPE = /\bVirtualizer\s*</
|
||||
// Bound methods: passing one (e.g. as a row ref) reads no virtualizer state.
|
||||
const STABLE_VIRTUALIZER_METHODS = new Set(['measureElement', 'scrollToIndex', 'scrollToOffset'])
|
||||
|
||||
function virtualizerHookShape(expression, hooks) {
|
||||
const node = expression && unwrap(expression)
|
||||
return node && ts.isCallExpression(node)
|
||||
? (hooks.get(calleeName(node.expression) ?? '') ?? null)
|
||||
: null
|
||||
}
|
||||
|
||||
/** Hooks returning a virtualizer (`direct`) or an object with a `virtualizer` (`property`). */
|
||||
export function findVirtualizerWrappers(fileName, text, hooks = VIRTUALIZER_HOOKS) {
|
||||
if (![...hooks.keys()].some((hook) => text.includes(hook))) {
|
||||
return []
|
||||
}
|
||||
const sourceFile = parseModule(fileName, text)
|
||||
const wrappers = []
|
||||
for (const { name, node } of listReactFunctions(sourceFile)) {
|
||||
if (!HOOK_NAME.test(name) || hooks.has(name)) {
|
||||
continue
|
||||
}
|
||||
const bound = new Set()
|
||||
let shape = null
|
||||
const visit = (child) => {
|
||||
if (child !== node && isFunctionNode(child)) {
|
||||
return
|
||||
}
|
||||
if (
|
||||
ts.isVariableDeclaration(child) &&
|
||||
ts.isIdentifier(child.name) &&
|
||||
virtualizerHookShape(child.initializer, hooks) === 'direct'
|
||||
) {
|
||||
bound.add(child.name.text)
|
||||
}
|
||||
if (ts.isReturnStatement(child) && child.expression) {
|
||||
const value = unwrap(child.expression)
|
||||
if (
|
||||
(ts.isIdentifier(value) && bound.has(value.text)) ||
|
||||
virtualizerHookShape(value, hooks) === 'direct'
|
||||
) {
|
||||
shape = 'direct'
|
||||
} else if (
|
||||
ts.isObjectLiteralExpression(value) &&
|
||||
value.properties.some(
|
||||
(p) => p.name && ts.isIdentifier(p.name) && p.name.text === 'virtualizer'
|
||||
)
|
||||
) {
|
||||
shape ??= 'property'
|
||||
}
|
||||
}
|
||||
ts.forEachChild(child, visit)
|
||||
}
|
||||
visit(node)
|
||||
if (shape) {
|
||||
wrappers.push({ name, shape })
|
||||
}
|
||||
}
|
||||
return wrappers
|
||||
}
|
||||
|
||||
/** Prop and parameter names this module types as a Virtualizer. */
|
||||
function virtualizerTypedNames(fileName, text) {
|
||||
const names = new Set()
|
||||
if (!VIRTUALIZER_TYPE.test(text)) {
|
||||
return names
|
||||
}
|
||||
const sourceFile = parseModule(fileName, text)
|
||||
const visit = (node) => {
|
||||
if (
|
||||
(ts.isPropertySignature(node) || ts.isParameter(node)) &&
|
||||
node.type &&
|
||||
ts.isIdentifier(node.name) &&
|
||||
VIRTUALIZER_TYPE.test(node.type.getText(sourceFile))
|
||||
) {
|
||||
names.add(node.name.text)
|
||||
}
|
||||
ts.forEachChild(node, visit)
|
||||
}
|
||||
visit(sourceFile)
|
||||
return names
|
||||
}
|
||||
|
||||
/** Cache blocks keyed on a virtualizer that read it or pass it as a JSX prop: `{ fn, text }`. */
|
||||
export function findVirtualizerMemoFlows(
|
||||
fileName,
|
||||
sourceText,
|
||||
compiledCode,
|
||||
hooks = VIRTUALIZER_HOOKS
|
||||
) {
|
||||
if (
|
||||
!compiledCode.includes('compiler-runtime') ||
|
||||
!(
|
||||
/[vV]irtualizer/.test(compiledCode) ||
|
||||
[...hooks.keys()].some((hook) => compiledCode.includes(hook))
|
||||
)
|
||||
) {
|
||||
return []
|
||||
}
|
||||
const typed = virtualizerTypedNames(fileName, sourceText)
|
||||
const sourceFile = parseModule(fileName, compiledCode)
|
||||
const runtime = compilerCacheNames(sourceFile)
|
||||
if (runtime.size === 0) {
|
||||
return []
|
||||
}
|
||||
const caches = new Set()
|
||||
const bound = new Set()
|
||||
const isVirtualizer = (expression) => {
|
||||
const node = unwrap(expression)
|
||||
if (ts.isIdentifier(node)) {
|
||||
const name = node.text.replace(/_\d+$/, '')
|
||||
return bound.has(node.text) || VIRTUALIZER_NAME.test(name) || typed.has(name)
|
||||
}
|
||||
if (ts.isPropertyAccessExpression(node)) {
|
||||
const name = node.name.text
|
||||
return VIRTUALIZER_NAME.test(name) || typed.has(name)
|
||||
}
|
||||
return false
|
||||
}
|
||||
const keyedOnVirtualizer = (condition) => {
|
||||
let keyed = false
|
||||
const visit = (node) => {
|
||||
if (
|
||||
ts.isBinaryExpression(node) &&
|
||||
node.operatorToken.kind === ts.SyntaxKind.ExclamationEqualsEqualsToken &&
|
||||
(isVirtualizer(node.left) || isVirtualizer(node.right))
|
||||
) {
|
||||
keyed = true
|
||||
}
|
||||
if (!keyed) {
|
||||
ts.forEachChild(node, visit)
|
||||
}
|
||||
}
|
||||
visit(condition)
|
||||
return keyed
|
||||
}
|
||||
const found = new Map()
|
||||
// Closures call the live virtualizer when they run; only render-time reads and props go stale.
|
||||
const collect = (fn, node) => {
|
||||
if (isFunctionNode(node)) {
|
||||
return
|
||||
}
|
||||
const passed =
|
||||
ts.isJsxAttribute(node) &&
|
||||
node.initializer &&
|
||||
ts.isJsxExpression(node.initializer) &&
|
||||
node.initializer.expression &&
|
||||
isVirtualizer(node.initializer.expression)
|
||||
const read =
|
||||
ts.isPropertyAccessExpression(node) &&
|
||||
isVirtualizer(node.expression) &&
|
||||
!(STABLE_VIRTUALIZER_METHODS.has(node.name.text) && !ts.isCallExpression(node.parent))
|
||||
if (passed || read) {
|
||||
found.set(node, { fn, text: node.getText(sourceFile).split('\n')[0].slice(0, 100) })
|
||||
return
|
||||
}
|
||||
ts.forEachChild(node, (child) => collect(fn, child))
|
||||
}
|
||||
const visit = (fn, node) => {
|
||||
if (ts.isVariableDeclaration(node) && node.initializer) {
|
||||
const init = unwrap(node.initializer)
|
||||
const shape = virtualizerHookShape(init, hooks)
|
||||
if (ts.isIdentifier(node.name)) {
|
||||
if (
|
||||
ts.isCallExpression(init) &&
|
||||
ts.isIdentifier(init.expression) &&
|
||||
runtime.has(init.expression.text)
|
||||
) {
|
||||
caches.add(node.name.text)
|
||||
} else if (shape === 'direct' || isVirtualizer(init)) {
|
||||
bound.add(node.name.text)
|
||||
}
|
||||
} else if (ts.isObjectBindingPattern(node.name)) {
|
||||
for (const element of node.name.elements) {
|
||||
const key = (element.propertyName ?? element.name).getText(sourceFile)
|
||||
if (ts.isIdentifier(element.name) && (key === 'virtualizer' || typed.has(key))) {
|
||||
bound.add(element.name.text)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
if (
|
||||
ts.isIfStatement(node) &&
|
||||
readsCache(node.expression, caches) &&
|
||||
keyedOnVirtualizer(node.expression)
|
||||
) {
|
||||
collect(fn, node.thenStatement)
|
||||
}
|
||||
const next = isFunctionNode(node) ? (reactFunctionName(node) ?? fn) : fn
|
||||
ts.forEachChild(node, (child) => visit(next, child))
|
||||
}
|
||||
visit('(module)', sourceFile)
|
||||
return [...found.values()]
|
||||
}
|
||||
|
||||
+92
@@ -1,9 +1,14 @@
|
||||
import { describe, expect, it } from 'vitest'
|
||||
|
||||
import {
|
||||
findLiveReadWrappers,
|
||||
findMemoizedCalls,
|
||||
findMemoizedHookCalls,
|
||||
findMemoizedStoreReads,
|
||||
findSourceHazards,
|
||||
findVirtualizerMemoFlows,
|
||||
findVirtualizerWrappers,
|
||||
renderLiveReadLines,
|
||||
renderStoreReadLines
|
||||
} from './react-compiler-hazards.mjs'
|
||||
|
||||
@@ -101,3 +106,90 @@ describe('store reads in memo blocks', () => {
|
||||
expect(renderStoreReadLines('a.ts', src, 'useRoute')).toEqual([3])
|
||||
})
|
||||
})
|
||||
|
||||
describe('virtualizer flows into memo blocks', () => {
|
||||
it('follows wrapper hooks and flags cached reads and props, not closures or bound methods', () => {
|
||||
const wrapper = [
|
||||
'export function useRows(n) {',
|
||||
' const virtualizer = useVirtualizer({ count: n })',
|
||||
' return { virtualizer, n }',
|
||||
'}'
|
||||
].join('\n')
|
||||
expect(findVirtualizerWrappers('w.ts', wrapper)).toEqual([
|
||||
{ name: 'useRows', shape: 'property' }
|
||||
])
|
||||
const hooks = new Map([
|
||||
['useVirtualizer', 'direct'],
|
||||
['useList', 'direct']
|
||||
])
|
||||
const compiled = [
|
||||
'import { c as _c } from "react/compiler-runtime";',
|
||||
'export function Pane() {',
|
||||
' const $ = _c(4);',
|
||||
' const list = useList();',
|
||||
' let t0;',
|
||||
' if ($[0] !== list) {',
|
||||
' t0 = <Rows list={list} height={list.getTotalSize()} onPick={() => list.scrollToIndex(0)} rowRef={list.measureElement} />;',
|
||||
' $[0] = list;',
|
||||
' $[1] = t0;',
|
||||
' } else {',
|
||||
' t0 = $[1];',
|
||||
' }',
|
||||
' let t1;',
|
||||
' if ($[2] !== list) {',
|
||||
' t1 = () => list.getVirtualItems();',
|
||||
' $[2] = list;',
|
||||
' $[3] = t1;',
|
||||
' } else {',
|
||||
' t1 = $[3];',
|
||||
' }',
|
||||
' return t0;',
|
||||
'}'
|
||||
].join('\n')
|
||||
expect(
|
||||
findVirtualizerMemoFlows('a.jsx', '', compiled, hooks).map(({ fn, text }) => `${fn}:${text}`)
|
||||
).toEqual(['Pane:list={list}', 'Pane:list.getTotalSize'])
|
||||
})
|
||||
})
|
||||
|
||||
describe('live module-state reads in memo blocks', () => {
|
||||
it('follows plain wrappers and flags a render read the compiler caches, not a useMemo one', () => {
|
||||
const lib = [
|
||||
'export function scopeKey(s) {',
|
||||
' return s ? runtimeKey(s.env) : null',
|
||||
'}',
|
||||
'export const later = (s) => () => runtimeKey(s)',
|
||||
'export function useScope(s) {',
|
||||
' return runtimeKey(s)',
|
||||
'}'
|
||||
].join('\n')
|
||||
expect(findLiveReadWrappers('lib.ts', lib, new Set(['runtimeKey']))).toEqual(['scopeKey'])
|
||||
const compiled = [
|
||||
'import { c as _c } from "react/compiler-runtime";',
|
||||
'export function Card(t0) {',
|
||||
' const $ = _c(2);',
|
||||
' const { settings } = t0;',
|
||||
' let t1;',
|
||||
' if ($[0] !== settings) {',
|
||||
' t1 = scopeKey(settings);',
|
||||
' $[0] = settings;',
|
||||
' $[1] = t1;',
|
||||
' } else {',
|
||||
' t1 = $[1];',
|
||||
' }',
|
||||
' return t1;',
|
||||
'}'
|
||||
].join('\n')
|
||||
const readers = new Set(['runtimeKey', 'scopeKey'])
|
||||
expect(findMemoizedCalls('a.js', compiled, readers)).toEqual([
|
||||
{ fn: 'Card', kind: 'live-read', name: 'scopeKey' }
|
||||
])
|
||||
const src = [
|
||||
'export function Card({ settings }) {',
|
||||
' const kept = useMemo(() => scopeKey(settings), [settings])',
|
||||
' return [kept, scopeKey(settings)]',
|
||||
'}'
|
||||
].join('\n')
|
||||
expect(renderLiveReadLines('a.tsx', src, 'Card', 'scopeKey')).toEqual([3])
|
||||
})
|
||||
})
|
||||
|
||||
@@ -1,66 +0,0 @@
|
||||
import { mkdirSync, mkdtempSync, readdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs'
|
||||
import { tmpdir } from 'node:os'
|
||||
import { join } from 'node:path'
|
||||
import { afterAll, describe, expect, it } from 'vitest'
|
||||
import { copyScriptWithLocalModules } from './script-module-dependencies.mjs'
|
||||
|
||||
const fixtureDir = mkdtempSync(join(tmpdir(), 'script-module-dependencies-'))
|
||||
|
||||
afterAll(() => {
|
||||
rmSync(fixtureDir, { recursive: true, force: true })
|
||||
})
|
||||
|
||||
function sourceTree(files) {
|
||||
const sourceDir = mkdtempSync(join(fixtureDir, 'source-'))
|
||||
for (const [name, contents] of Object.entries(files)) {
|
||||
writeFileSync(join(sourceDir, name), contents)
|
||||
}
|
||||
return sourceDir
|
||||
}
|
||||
|
||||
function copiedNames(files, entryName) {
|
||||
const sourceDir = sourceTree(files)
|
||||
const destinationDir = join(mkdtempSync(join(fixtureDir, 'dest-')), 'scripts')
|
||||
copyScriptWithLocalModules(join(sourceDir, entryName), destinationDir)
|
||||
const names = readdirSync(destinationDir).sort()
|
||||
for (const name of names) {
|
||||
expect(readFileSync(join(destinationDir, name), 'utf8'), name).toBe(files[name])
|
||||
}
|
||||
return names
|
||||
}
|
||||
|
||||
describe('copyScriptWithLocalModules', () => {
|
||||
it('preserves parent paths for modules shared with the runtime', () => {
|
||||
const sourceDir = sourceTree({ 'runtime.ts': 'export const value = 42\n' })
|
||||
mkdirSync(join(sourceDir, 'scripts'))
|
||||
writeFileSync(join(sourceDir, 'scripts', 'entry.mjs'), "export { value } from '../runtime'\n")
|
||||
const destinationRoot = mkdtempSync(join(fixtureDir, 'dest-'))
|
||||
copyScriptWithLocalModules(
|
||||
join(sourceDir, 'scripts', 'entry.mjs'),
|
||||
join(destinationRoot, 'scripts')
|
||||
)
|
||||
expect(readFileSync(join(destinationRoot, 'runtime.ts'), 'utf8')).toBe(
|
||||
'export const value = 42\n'
|
||||
)
|
||||
})
|
||||
|
||||
// Cover require-only CJS gate dependencies so copied fixture fails for target defect, not missing module.
|
||||
|
||||
it('follows a require reached only through an imported module', () => {
|
||||
const names = copiedNames(
|
||||
{
|
||||
'entry.mjs': "import './middle.cjs'\n",
|
||||
'middle.cjs': "require('./leaf.cjs')\n",
|
||||
'leaf.cjs': 'module.exports = {}\n'
|
||||
},
|
||||
'entry.mjs'
|
||||
)
|
||||
expect(names).toContain('leaf.cjs')
|
||||
})
|
||||
|
||||
it('terminates on a cycle rather than recursing forever', () => {
|
||||
expect(
|
||||
copiedNames({ 'a.mjs': "import './b.mjs'\n", 'b.mjs': "import './a.mjs'\n" }, 'a.mjs')
|
||||
).toEqual(['a.mjs', 'b.mjs'])
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,201 @@
|
||||
// Shared-worker files run back to back in one module cache; undo each file's mocks and process state.
|
||||
// A file that leaves timers, listeners or globals behind also drops the module cache, as isolation would.
|
||||
// Plain JS: it rewires Vitest's mocker and the timer globals, which have no public types.
|
||||
import { promisify } from 'node:util'
|
||||
import { afterAll, vi } from 'vitest'
|
||||
|
||||
const VITEST_INTERNAL = /\/vitest\/dist\/|\/@vitest\/|vitest-virtual-/
|
||||
// Registries their owners create on first use and look up again on every access.
|
||||
const LAZY_GLOBAL_REGISTRY = /^(?:Symbol\(orca\.|__zod_global)/
|
||||
const PROCESS_KEYS = ['platform', 'arch', 'execPath', 'argv', 'exitCode']
|
||||
|
||||
function resetNode(node) {
|
||||
node.evaluated = false
|
||||
node.promise = undefined
|
||||
node.exports = undefined
|
||||
}
|
||||
|
||||
// Same reset Vitest's isolation applies, limited to modules that saw the mocked one.
|
||||
function resetImportersOf(modules, id) {
|
||||
const pending = [...(modules.getModuleById(id)?.importers ?? [])]
|
||||
const seen = new Set()
|
||||
while (pending.length > 0) {
|
||||
const importer = pending.pop()
|
||||
if (seen.has(importer) || VITEST_INTERNAL.test(importer)) {
|
||||
continue
|
||||
}
|
||||
seen.add(importer)
|
||||
const node = modules.getModuleById(importer)
|
||||
if (node) {
|
||||
resetNode(node)
|
||||
pending.push(...node.importers)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function resetAllModules(modules) {
|
||||
for (const [id, node] of modules.idToModuleMap) {
|
||||
if (!VITEST_INTERNAL.test(id)) {
|
||||
resetNode(node)
|
||||
node.importers.clear()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function trackTimers(state) {
|
||||
const real = { setTimeout, setInterval, clearTimeout, clearInterval }
|
||||
function trackedSetTimeout(callback, ms, ...args) {
|
||||
if (typeof callback !== 'function') {
|
||||
return real.setTimeout(callback, ms, ...args)
|
||||
}
|
||||
const handle = real.setTimeout(
|
||||
(...callbackArgs) => {
|
||||
state.pendingTimers.delete(handle)
|
||||
callback(...callbackArgs)
|
||||
},
|
||||
ms,
|
||||
...args
|
||||
)
|
||||
state.pendingTimers.add(handle)
|
||||
return handle
|
||||
}
|
||||
trackedSetTimeout[promisify.custom] = real.setTimeout[promisify.custom]
|
||||
globalThis.setTimeout = trackedSetTimeout
|
||||
globalThis.setInterval = (...args) => {
|
||||
const handle = real.setInterval(...args)
|
||||
state.pendingTimers.add(handle)
|
||||
return handle
|
||||
}
|
||||
globalThis.clearTimeout = (handle) => {
|
||||
state.pendingTimers.delete(handle)
|
||||
real.clearTimeout(handle)
|
||||
}
|
||||
globalThis.clearInterval = (handle) => {
|
||||
state.pendingTimers.delete(handle)
|
||||
real.clearInterval(handle)
|
||||
}
|
||||
state.clearTimer = (handle) => {
|
||||
real.clearTimeout(handle)
|
||||
real.clearInterval(handle)
|
||||
}
|
||||
}
|
||||
|
||||
// The mocker lives across files, unlike this module, so it carries the once-per-worker state.
|
||||
function installOnce(mocker) {
|
||||
if (mocker.orcaSharedWorkerState) {
|
||||
return mocker.orcaSharedWorkerState
|
||||
}
|
||||
const mockPath = mocker.mockPath.bind(mocker)
|
||||
// Modules cached by an earlier file hold the real binding; re-run them against this file's mock.
|
||||
mocker.mockPath = (originalId, id, ...rest) => {
|
||||
mockPath(originalId, id, ...rest)
|
||||
resetImportersOf(mocker.evaluatedModules, id)
|
||||
}
|
||||
const reset = mocker.reset.bind(mocker)
|
||||
// And re-run them against the real module before the next file imports them.
|
||||
mocker.reset = () => {
|
||||
for (const registry of mocker.registries.values()) {
|
||||
for (const url of registry.keys()) {
|
||||
resetImportersOf(mocker.evaluatedModules, registry.get(url).id)
|
||||
}
|
||||
}
|
||||
reset()
|
||||
}
|
||||
const state = { pendingTimers: new Set(), clearTimer: () => {} }
|
||||
trackTimers(state)
|
||||
mocker.orcaSharedWorkerState = state
|
||||
return state
|
||||
}
|
||||
|
||||
const mocker = globalThis.__vitest_mocker__
|
||||
const state = mocker ? installOnce(mocker) : undefined
|
||||
state?.pendingTimers.clear()
|
||||
|
||||
const initialGlobals = Object.getOwnPropertyDescriptors(globalThis)
|
||||
const initialProcess = Object.fromEntries(
|
||||
PROCESS_KEYS.map((key) => [key, Object.getOwnPropertyDescriptor(process, key)])
|
||||
)
|
||||
const initialListeners = new Map(
|
||||
process.eventNames().map((event) => [event, new Set(process.listeners(event))])
|
||||
)
|
||||
const initialEnv = { ...process.env }
|
||||
const initialCwd = process.cwd()
|
||||
const evaluatedBefore = new Set(
|
||||
[...(mocker?.evaluatedModules.idToModuleMap ?? [])]
|
||||
.filter(([, node]) => node.evaluated)
|
||||
.map(([id]) => id)
|
||||
)
|
||||
|
||||
/** Puts process state back and reports what this file had left behind. */
|
||||
function restoreProcessState() {
|
||||
const leaks = { globals: [], process: [] }
|
||||
for (const key of Reflect.ownKeys(globalThis)) {
|
||||
if (!(key in initialGlobals) && !LAZY_GLOBAL_REGISTRY.test(String(key))) {
|
||||
leaks.globals.push(String(key))
|
||||
Reflect.deleteProperty(globalThis, key)
|
||||
}
|
||||
}
|
||||
for (const [key, descriptor] of Object.entries(initialGlobals)) {
|
||||
const current = Object.getOwnPropertyDescriptor(globalThis, key)
|
||||
if (!Object.is(current?.value, descriptor.value) || current?.get !== descriptor.get) {
|
||||
leaks.globals.push(key)
|
||||
try {
|
||||
Object.defineProperty(globalThis, key, descriptor)
|
||||
} catch {
|
||||
// Non-configurable globals cannot be put back; the module reset below still applies.
|
||||
}
|
||||
}
|
||||
}
|
||||
for (const key of PROCESS_KEYS) {
|
||||
const descriptor = initialProcess[key]
|
||||
if (descriptor) {
|
||||
Object.defineProperty(process, key, descriptor)
|
||||
} else {
|
||||
Reflect.deleteProperty(process, key)
|
||||
}
|
||||
}
|
||||
for (const event of process.eventNames()) {
|
||||
const before = initialListeners.get(event)
|
||||
for (const listener of process.listeners(event)) {
|
||||
if (!before?.has(listener)) {
|
||||
leaks.process.push(`${String(event)} listener`)
|
||||
process.removeListener(event, listener)
|
||||
}
|
||||
}
|
||||
}
|
||||
for (const handle of state?.pendingTimers ?? []) {
|
||||
leaks.process.push('timer')
|
||||
state.clearTimer(handle)
|
||||
}
|
||||
state?.pendingTimers.clear()
|
||||
for (const key of Object.keys(process.env)) {
|
||||
if (!(key in initialEnv)) {
|
||||
delete process.env[key]
|
||||
}
|
||||
}
|
||||
Object.assign(process.env, initialEnv)
|
||||
if (process.cwd() !== initialCwd) {
|
||||
process.chdir(initialCwd)
|
||||
}
|
||||
return leaks
|
||||
}
|
||||
|
||||
afterAll(() => {
|
||||
// Runs Vitest's end-of-file spy restore now: a spy restored by hand would otherwise be re-applied after this hook.
|
||||
vi.restoreAllMocks()
|
||||
vi.useRealTimers()
|
||||
vi.unstubAllEnvs()
|
||||
vi.unstubAllGlobals()
|
||||
const leaks = restoreProcessState()
|
||||
if (mocker && leaks.process.length > 0) {
|
||||
// Any cached module may own a cleared timer or listener.
|
||||
resetAllModules(mocker.evaluatedModules)
|
||||
} else if (mocker && leaks.globals.length > 0) {
|
||||
// A module this file loaded may have installed the global it now expects.
|
||||
for (const [id, node] of mocker.evaluatedModules.idToModuleMap) {
|
||||
if (node.evaluated && !evaluatedBefore.has(id) && !VITEST_INTERNAL.test(id)) {
|
||||
resetNode(node)
|
||||
}
|
||||
}
|
||||
}
|
||||
})
|
||||
@@ -0,0 +1,94 @@
|
||||
import { readFileSync, statSync } from 'node:fs'
|
||||
import { dirname, join, relative, resolve } from 'node:path'
|
||||
|
||||
// vitest-shared-worker-file-reset.mjs undoes mocks, timers, stubs, env and cwd after each file.
|
||||
// These can't be undone between files, so a file that uses them keeps its own worker.
|
||||
const ISOLATION_REQUIRING_API = new RegExp(
|
||||
[
|
||||
// Opt-out for a file whose state leaks in ways the reset cannot see.
|
||||
String.raw`@orca-isolated-worker\b`,
|
||||
String.raw`\bvi\.(?:doMock|unmock|doUnmock|resetModules)\(`,
|
||||
String.raw`@vitest-environment\s+(?!node\b)`,
|
||||
String.raw`\bglobalThis(?:\.\w+|\[[^\]]+\])\s*=[^=]`,
|
||||
String.raw`\bObject\.defineProperty\(\s*(?:globalThis|process|navigator|window|document)\b`
|
||||
].join('|')
|
||||
)
|
||||
const IMPORT_SPECIFIER = /(?:\bfrom\s*|\bimport\s*\(\s*|\bimport\s+)['"]([^'"]+)['"]/g
|
||||
const SOURCE_EXTENSIONS = ['.ts', '.tsx', '.mts', '.mjs', '.js']
|
||||
|
||||
function isFile(path) {
|
||||
try {
|
||||
return statSync(path).isFile()
|
||||
} catch {
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
function resolveLocal(fromFile, specifier, aliases) {
|
||||
let base = null
|
||||
if (specifier.startsWith('./') || specifier.startsWith('../')) {
|
||||
base = resolve(dirname(fromFile), specifier)
|
||||
} else {
|
||||
const alias = aliases.find(({ find }) => specifier === find || specifier.startsWith(`${find}/`))
|
||||
if (!alias) {
|
||||
return null
|
||||
}
|
||||
base = join(alias.replacement, specifier.slice(alias.find.length))
|
||||
}
|
||||
const stem = base.replace(/\.[cm]?jsx?$/, '')
|
||||
const candidates = [
|
||||
base,
|
||||
...SOURCE_EXTENSIONS.map((extension) => stem + extension),
|
||||
...SOURCE_EXTENSIONS.map((extension) => join(base, `index${extension}`))
|
||||
]
|
||||
return (
|
||||
candidates.find(
|
||||
(candidate) => !/[\\/]node_modules[\\/]/.test(candidate) && isFile(candidate)
|
||||
) ?? null
|
||||
)
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the test files (root-relative, forward slashes) that can share a worker's module cache.
|
||||
* Only the test file and the test-support files it imports are scanned, not production modules.
|
||||
*/
|
||||
export function filesSafeToShareWorker(root, files, aliases = []) {
|
||||
const sources = new Map()
|
||||
const read = (file) => {
|
||||
let source = sources.get(file)
|
||||
if (source === undefined) {
|
||||
source = readFileSync(file, 'utf8')
|
||||
sources.set(file, source)
|
||||
}
|
||||
return source
|
||||
}
|
||||
const isTestSupport = (file) => /\bfrom\s+['"]vitest['"]/.test(read(file))
|
||||
const memo = new Map()
|
||||
const visiting = new Set()
|
||||
const requiresIsolation = (file) => {
|
||||
const known = memo.get(file)
|
||||
if (known !== undefined) {
|
||||
return known
|
||||
}
|
||||
if (visiting.has(file)) {
|
||||
return false
|
||||
}
|
||||
visiting.add(file)
|
||||
const source = read(file)
|
||||
let result = ISOLATION_REQUIRING_API.test(source)
|
||||
for (const match of result ? [] : source.matchAll(IMPORT_SPECIFIER)) {
|
||||
const target = resolveLocal(file, match[1], aliases)
|
||||
if (target && isTestSupport(target) && requiresIsolation(target)) {
|
||||
result = true
|
||||
break
|
||||
}
|
||||
}
|
||||
visiting.delete(file)
|
||||
memo.set(file, result)
|
||||
return result
|
||||
}
|
||||
return files
|
||||
.map((file) => resolve(root, file))
|
||||
.filter((file) => isFile(file) && !requiresIsolation(file))
|
||||
.map((file) => relative(root, file).replaceAll('\\', '/'))
|
||||
}
|
||||
@@ -58,7 +58,6 @@ const NODE_RUNTIME_INCLUDE = [
|
||||
'src/main/acp/session/acp-structured-sign-in.test.ts',
|
||||
'src/main/acp/session/acp-structured-session-adapter.test.ts',
|
||||
'src/main/acp/session/acp-structured-session-adapter-resume.test.ts',
|
||||
'src/main/acp/history/acp-history-scaling.test.ts',
|
||||
'src/main/pi/rpc-turn-races.test.ts',
|
||||
'src/main/acp/session/children/acp-structured-child-session-end.test.ts',
|
||||
'src/main/acp/session/children/acp-structured-child-stop.test.ts',
|
||||
|
||||
@@ -157,7 +157,6 @@ export const WINDOWS_BOUNDARY_TESTS = [
|
||||
'config/scripts/native-build/windows/windows-pe-machine.test.mjs',
|
||||
'config/scripts/native-build/windows/build-windows-cli-launcher.test.mjs',
|
||||
'config/scripts/desktop-distribution/runtime-verification/verify-packaged-windows-agent-hook.test.mjs',
|
||||
'config/scripts/test-fixtures/script-copy-closure/script-module-dependencies.test.mjs',
|
||||
'src/main/windows/windows-registry-addon.test.ts',
|
||||
'src/main/daemon/executable-host/windows/testing/daemon-host-process-package.test.ts',
|
||||
'src/shared/windows-security-addon.win32.test.ts',
|
||||
|
||||
@@ -1,98 +0,0 @@
|
||||
import { beforeAll, describe, expect, it } from 'vitest'
|
||||
import {
|
||||
buildUnitDependencyGraph,
|
||||
collectUnitDependencyGraph,
|
||||
unitConsumers
|
||||
} from '../../ci/unit-selection/dependency-graph/ci-unit-dependency-graph.mjs'
|
||||
import {
|
||||
CROSS_VERSION_WIRE_DIR,
|
||||
discoverUnitFiles
|
||||
} from '../../ci/unit-selection/dependency-graph/ci-unit-files.mjs'
|
||||
|
||||
const harness =
|
||||
'src/renderer/src/runtime/web-session-tabs-sync/testing/web-session-tabs-sync.test-fixture.ts'
|
||||
const structuredSessionHarness =
|
||||
'src/renderer/src/components/native-chat/surfaces/integration/NativeChatStructuredSession.test-harness.tsx'
|
||||
|
||||
const unitHarnesses = [
|
||||
harness,
|
||||
structuredSessionHarness,
|
||||
'src/renderer/src/store/slices/editor/editor-slice-test-harness.ts',
|
||||
'src/renderer/src/store/slices/browser/browser-slice-test-harness.ts',
|
||||
'src/renderer/src/runtime/hosted-terminals/creation/testing/web-runtime-terminal-create.test-fixture.ts',
|
||||
'src/renderer/src/runtime/sync-runtime-graph/testing/sync-runtime-graph-test-harness.ts'
|
||||
]
|
||||
const supportBridges = new Set([
|
||||
// Launch request suites' store rig; it takes the terminal harness's workspace layout.
|
||||
'src/renderer/src/runtime/hosted-terminals/creation/agent-launch/web-runtime-agent-launch-options.test-fixture.ts',
|
||||
'src/renderer/src/runtime/browser/creation/testing/web-runtime-browser-creation-placement-test-rig.ts',
|
||||
'src/renderer/src/components/editor/model-lifetime/retention/editor-model-lifetime-fixture.ts',
|
||||
// Autosave suites' store rig; it takes the editor harness's tab-layout maps.
|
||||
'src/renderer/src/components/editor/autosave/editor-autosave-controller-test-fixture.ts',
|
||||
// Closed-saving-view save suites' rig; it builds on the autosave rig above.
|
||||
'src/renderer/src/components/editor/save/queue/editor-save-closed-view.test-fixture.ts',
|
||||
// Browser suites' store with main drawing their tabs; it takes the browser harness's store.
|
||||
'src/renderer/src/store/slices/browser/browser-slice-drawn-from-main.test-fixture.ts'
|
||||
])
|
||||
|
||||
function productConsumers(file, graph, unitFiles) {
|
||||
return [...unitConsumers([file], graph.reverse)].filter(
|
||||
(consumer) =>
|
||||
consumer !== file &&
|
||||
!unitFiles.has(consumer) &&
|
||||
!(consumer.startsWith(CROSS_VERSION_WIRE_DIR) && consumer.endsWith('.unit.test.ts')) &&
|
||||
!supportBridges.has(consumer)
|
||||
)
|
||||
}
|
||||
|
||||
describe('unit support import ownership', () => {
|
||||
let graph
|
||||
let unitFiles
|
||||
beforeAll(() => {
|
||||
graph = collectUnitDependencyGraph()
|
||||
unitFiles = new Set(discoverUnitFiles())
|
||||
}, 60_000)
|
||||
|
||||
it.each(unitHarnesses)('rejects any product consumer of %s', (unitHarness) => {
|
||||
expect(graph.files.has(unitHarness)).toBe(true)
|
||||
expect(
|
||||
[...unitConsumers([unitHarness], graph.reverse)].some((file) => unitFiles.has(file))
|
||||
).toBe(true)
|
||||
expect(productConsumers(unitHarness, graph, unitFiles)).toEqual([])
|
||||
})
|
||||
|
||||
it.each([
|
||||
"import '@/runtime/web-session-tabs-sync/testing/web-session-tabs-sync.test-fixture'",
|
||||
"export * from '@/runtime/web-session-tabs-sync/testing/web-session-tabs-sync.test-fixture'",
|
||||
"import('@/runtime/web-session-tabs-sync/testing/web-session-tabs-sync.test-fixture')",
|
||||
"import type { Fixture } from '@/runtime/web-session-tabs-sync/testing/web-session-tabs-sync.test-fixture'"
|
||||
])('detects a product importer using %s', (source) => {
|
||||
const importer = 'src/renderer/src/runtime/product.ts'
|
||||
const test = 'src/renderer/src/runtime/ownership.test.ts'
|
||||
const synthetic = buildUnitDependencyGraph(
|
||||
new Map([
|
||||
[harness, 'export const value = 1'],
|
||||
[importer, source],
|
||||
[test, "import './web-session-tabs-sync/testing/web-session-tabs-sync.test-fixture'"]
|
||||
])
|
||||
)
|
||||
expect(productConsumers(harness, synthetic, new Set([test]))).toEqual([importer])
|
||||
})
|
||||
|
||||
it('rejects product consumers reached through an audited support bridge', () => {
|
||||
const bridge =
|
||||
'src/renderer/src/components/editor/model-lifetime/retention/editor-model-lifetime-fixture.ts'
|
||||
const importer = 'src/renderer/src/components/editor/product.ts'
|
||||
const synthetic = buildUnitDependencyGraph(
|
||||
new Map([
|
||||
[harness, 'export const value = 1'],
|
||||
[
|
||||
bridge,
|
||||
"import '@/runtime/web-session-tabs-sync/testing/web-session-tabs-sync.test-fixture'"
|
||||
],
|
||||
[importer, "import './model-lifetime/retention/editor-model-lifetime-fixture'"]
|
||||
])
|
||||
)
|
||||
expect(productConsumers(harness, synthetic, new Set())).toEqual([importer])
|
||||
})
|
||||
})
|
||||
+44
-2
@@ -1,4 +1,4 @@
|
||||
import { readFileSync } from 'node:fs'
|
||||
import { globSync, readFileSync } from 'node:fs'
|
||||
import { createRequire } from 'node:module'
|
||||
import { resolve } from 'node:path'
|
||||
import { normalizePath, transformWithOxc, type Plugin } from 'vite'
|
||||
@@ -9,12 +9,14 @@ import {
|
||||
UNIT_SETUP_FILES
|
||||
} from './scripts/ci/unit-selection/dependency-graph/ci-unit-files.mjs'
|
||||
import TimingSequencer from './scripts/ci/sharding/ci-unit-sequencer.mjs'
|
||||
import { filesSafeToShareWorker } from './scripts/test-runtime/execution-policy/vitest-shared-worker-files.mjs'
|
||||
import RuntimeSequencer from './scripts/test-runtime/execution-policy/vitest-runtime-sequencer.mjs'
|
||||
import { getNodeRuntimeInclude } from './scripts/test-runtime/sqlite-admission/vitest-node-runtime-files.mjs'
|
||||
import { nodeRuntimePool } from './scripts/test-runtime/node-worker/vitest-node-runtime-pool'
|
||||
import { readRunFilters } from './scripts/test-runtime/execution-policy/vitest-run-filters.mjs'
|
||||
import { createWorkspaceSourceResolver } from './scripts/workspace/source-exports/workspace-source-exports.mjs'
|
||||
import { moduleCacheResolutionKey } from './scripts/test-runtime/module-cache/vitest-module-cache-resolution-key'
|
||||
import { vitestReactCompiler } from './build-plugins/vitest-react-compiler'
|
||||
|
||||
const nodeRuntimeInclude = process.versions.bun
|
||||
? getNodeRuntimeInclude({ filters: readRunFilters() })
|
||||
@@ -44,6 +46,7 @@ const transforms = {
|
||||
}
|
||||
} satisfies Plugin,
|
||||
...(moduleCachePath ? [moduleCacheResolutionKey()] : []),
|
||||
...vitestReactCompiler(),
|
||||
{
|
||||
// Unit tests have no asset server; retain real catalog parsing through fetch(data:).
|
||||
name: 'locale-catalog-test-assets',
|
||||
@@ -121,7 +124,46 @@ const bunProject = {
|
||||
sequence: { groupOrder: 1 }
|
||||
}
|
||||
}
|
||||
const projects = [...(process.versions.bun ? [bunProject] : []), nodeProject]
|
||||
// Files whose state the per-file reset can undo share one worker's module cache instead of
|
||||
// re-importing thousands of modules each. ORCA_VITEST_ISOLATE_EVERY_FILE=1 turns it off.
|
||||
const runtimeProject = process.versions.bun ? bunProject : nodeProject
|
||||
const nodeRuntimeFiles = new Set(nodeRuntimeInclude.map((file) => file.replaceAll('\\', '/')))
|
||||
const sharedWorkerFiles =
|
||||
process.env.ORCA_VITEST_ISOLATE_EVERY_FILE === '1'
|
||||
? []
|
||||
: filesSafeToShareWorker(
|
||||
process.cwd(),
|
||||
globSync(UNIT_INCLUDE)
|
||||
.map((file) => file.replaceAll('\\', '/'))
|
||||
.filter((file) => !nodeRuntimeFiles.has(file)),
|
||||
[
|
||||
{ find: '@renderer', replacement: resolve('src/renderer/src') },
|
||||
{ find: '@', replacement: resolve('src/renderer/src') }
|
||||
]
|
||||
)
|
||||
const sharedProjects =
|
||||
sharedWorkerFiles.length > 0
|
||||
? [
|
||||
{
|
||||
...runtimeProject,
|
||||
test: {
|
||||
...runtimeProject.test,
|
||||
name: `${runtimeProject.test.name}-shared`,
|
||||
include: sharedWorkerFiles,
|
||||
isolate: false,
|
||||
setupFiles: [
|
||||
...runtimeProject.test.setupFiles,
|
||||
resolve('config/scripts/test-runtime/environment/vitest-shared-worker-file-reset.mjs')
|
||||
]
|
||||
}
|
||||
}
|
||||
]
|
||||
: []
|
||||
runtimeProject.test.exclude = [
|
||||
...(runtimeProject.test.exclude ?? testOptions.exclude),
|
||||
...sharedWorkerFiles
|
||||
]
|
||||
const projects = [...(process.versions.bun ? [bunProject] : []), nodeProject, ...sharedProjects]
|
||||
|
||||
export default defineConfig({
|
||||
...transforms,
|
||||
|
||||
@@ -15,6 +15,7 @@ import { createViteCacheRetentionPlugin } from './config/build-plugins/vite-cach
|
||||
import { MAIN_BUILD_ENTRY_POINTS } from './config/build-plugins/main-build-entry-points'
|
||||
import { createPlainNodeEntryGuardPlugin } from './config/build-plugins/plain-node-entry-guard'
|
||||
import { createDevServeConfig } from './config/build-plugins/dev-serve-config'
|
||||
import { reactPluginOptions } from './config/build-plugins/react-compiler'
|
||||
import { resolveBuildSourceCommit } from './config/scripts/build-identity/build-source-commit.mjs'
|
||||
|
||||
const BUNDLED_MAIN_DEPENDENCIES = new Set([
|
||||
@@ -284,7 +285,7 @@ export const electronViteConfig: UserConfig = {
|
||||
}
|
||||
},
|
||||
plugins: [
|
||||
react(),
|
||||
react(reactPluginOptions()),
|
||||
tailwindcss(),
|
||||
createPdfjsViewerAssetsPlugin(),
|
||||
createViteCacheRetentionPlugin()
|
||||
|
||||
+3
@@ -3,6 +3,9 @@ package expo.modules.orcamobilewebshell
|
||||
/** Shared page/native bridge contract; framework-free for off-device checks. */
|
||||
internal const val MOBILE_WEB_SHELL_BRIDGE_OBJECT = "orcaBridge"
|
||||
|
||||
/** Tells a page booted ahead of its screen to stop asking for init; the screen that adopts it answers. */
|
||||
internal const val MOBILE_WEB_SHELL_PARKED_FRAME = """{"v":1,"type":"parked"}"""
|
||||
|
||||
/** Enforce the shared UTF-8 JSON byte ceiling natively, before parsing. */
|
||||
internal const val MOBILE_WEB_SHELL_BRIDGE_MAX_MESSAGE_BYTES = 640 * 1024
|
||||
|
||||
|
||||
+413
@@ -0,0 +1,413 @@
|
||||
package expo.modules.orcamobilewebshell
|
||||
|
||||
import android.annotation.SuppressLint
|
||||
import android.content.Context
|
||||
import android.graphics.Bitmap
|
||||
import android.graphics.Color
|
||||
import android.net.Uri
|
||||
import android.os.Message
|
||||
import android.view.View
|
||||
import android.view.ViewGroup
|
||||
import android.webkit.RenderProcessGoneDetail
|
||||
import android.webkit.WebChromeClient
|
||||
import android.webkit.WebResourceError
|
||||
import android.webkit.WebResourceRequest
|
||||
import android.webkit.WebResourceResponse
|
||||
import android.webkit.WebSettings
|
||||
import android.webkit.WebView
|
||||
import android.webkit.WebViewClient
|
||||
import androidx.core.graphics.Insets
|
||||
import androidx.core.view.ViewCompat
|
||||
import androidx.core.view.WindowInsetsCompat
|
||||
import androidx.webkit.JavaScriptReplyProxy
|
||||
import androidx.webkit.ScriptHandler
|
||||
import androidx.webkit.WebMessageCompat
|
||||
import androidx.webkit.WebViewCompat
|
||||
import androidx.webkit.WebViewFeature
|
||||
import expo.modules.kotlin.exception.CodedException
|
||||
import java.io.ByteArrayInputStream
|
||||
|
||||
/** Publish host and manifest map atomically/volatily: main-thread writes race Chromium’s interceptor. */
|
||||
private class MobileWebShellServed(
|
||||
val generation: MobileWebShellGeneration,
|
||||
val originHost: String
|
||||
)
|
||||
|
||||
/** Where a document's reports go: the view showing it, or the spare pool while it is parked. */
|
||||
internal interface MobileWebShellDocumentSink {
|
||||
fun documentLoadState(payload: Map<String, Any>)
|
||||
fun documentBridgeMessage(json: String)
|
||||
fun documentExternalNavigation(url: String)
|
||||
}
|
||||
|
||||
/** One WebView and every fence on it, apart from React. The view hosts it and lays it out. */
|
||||
@SuppressLint("SetJavaScriptEnabled")
|
||||
internal class MobileWebShellDocument(private val context: Context) {
|
||||
var sink: MobileWebShellDocumentSink? = null
|
||||
private var bridgeInstalled = false
|
||||
private val bridgeGate = MobileWebShellBridgeGate()
|
||||
// The page sends ready before native replies; volatile proxy state crosses interceptor/UI threads.
|
||||
@Volatile private var replyProxy: JavaScriptReplyProxy? = null
|
||||
private var applied: MobileWebShellAppliedProps? = null
|
||||
private val loadState = MobileWebShellLoadStateMachine()
|
||||
// Failure state crosses main-thread callbacks and Chromium’s background interceptor.
|
||||
@Volatile private var documentFailed = false
|
||||
@Volatile private var served: MobileWebShellServed? = null
|
||||
private var blocker: ScriptHandler? = null
|
||||
// Read by the interceptor thread when it reports a failed main-frame load.
|
||||
@Volatile var webView: WebView? = createWebView()
|
||||
private set
|
||||
|
||||
/** Still showable: not torn down, and no terminal load failure or renderer loss. */
|
||||
val isUsable: Boolean get() = webView != null && !loadState.isTerminal
|
||||
|
||||
/** Apply unordered props together; identical triples do not retry. Recovery requires a remount. */
|
||||
fun apply(generationDirectory: String, sessionId: String, bridgeEnabled: Boolean) {
|
||||
val next = MobileWebShellAppliedProps(generationDirectory, sessionId, bridgeEnabled)
|
||||
if (applied?.matches(next) == true) return
|
||||
applied = next
|
||||
documentFailed = false
|
||||
loadState.reset()
|
||||
val view = webView
|
||||
if (view == null) {
|
||||
// A dead renderer requires a remount; changed props must still report failure.
|
||||
emit(loadState.rendererStillGone())
|
||||
return
|
||||
}
|
||||
view.stopLoading()
|
||||
emit(loadState.started())
|
||||
|
||||
val origin = mobileWebShellOrigin(sessionId)
|
||||
val host = mobileWebShellOriginHost(sessionId)
|
||||
if (origin == null || host == null) {
|
||||
// The private origin is the isolation primitive; a malformed session id leaves us without one.
|
||||
failPropUpdate(MobileWebShellFailureReason.ISOLATION_UNAVAILABLE)
|
||||
return
|
||||
}
|
||||
val loaded = MobileWebShellGeneration.load(generationDirectory)
|
||||
if (loaded == null) {
|
||||
failPropUpdate(MobileWebShellFailureReason.GENERATION_UNREADABLE)
|
||||
return
|
||||
}
|
||||
blocker?.remove()
|
||||
blocker = installMobileWebShellNetworkApiBlocker(view, origin)
|
||||
if (blocker == null) {
|
||||
failPropUpdate(MobileWebShellFailureReason.ISOLATION_UNAVAILABLE)
|
||||
return
|
||||
}
|
||||
if (!applyBridgeListener(view, origin, bridgeEnabled)) {
|
||||
failPropUpdate(MobileWebShellFailureReason.ISOLATION_UNAVAILABLE)
|
||||
return
|
||||
}
|
||||
served = MobileWebShellServed(loaded, host)
|
||||
view.visibility = View.VISIBLE
|
||||
view.loadUrl("$origin/")
|
||||
}
|
||||
|
||||
/** Retire the old visible generation even when the replacement fails. */
|
||||
private fun failPropUpdate(reason: MobileWebShellFailureReason) {
|
||||
// Remove the old listener: stopLoading leaves its same-origin document alive and able to rearm replies.
|
||||
removeBridgeListener()
|
||||
served = null
|
||||
webView?.visibility = View.INVISIBLE
|
||||
emit(loadState.failed(reason))
|
||||
}
|
||||
|
||||
/** addWebMessageListener injects before scripts and enforces origins; false means unsupported provider. */
|
||||
private fun applyBridgeListener(view: WebView, origin: String, bridgeEnabled: Boolean): Boolean {
|
||||
removeBridgeListener()
|
||||
val outcome = mobileWebShellBridgeInstall(
|
||||
bridgeEnabled,
|
||||
WebViewFeature.isFeatureSupported(WebViewFeature.WEB_MESSAGE_LISTENER)
|
||||
)
|
||||
if (outcome != MobileWebShellBridgeInstall.INSTALL) {
|
||||
return outcome == MobileWebShellBridgeInstall.SKIP
|
||||
}
|
||||
return runCatching {
|
||||
WebViewCompat.addWebMessageListener(
|
||||
view,
|
||||
MOBILE_WEB_SHELL_BRIDGE_OBJECT,
|
||||
setOf(origin),
|
||||
bridgeListener
|
||||
)
|
||||
bridgeInstalled = true
|
||||
}.isSuccess
|
||||
}
|
||||
|
||||
/** The one way the bridge goes away, so no disable path can leave a listener behind. */
|
||||
private fun removeBridgeListener() {
|
||||
val view = webView
|
||||
if (bridgeInstalled && view != null) {
|
||||
WebViewCompat.removeWebMessageListener(view, MOBILE_WEB_SHELL_BRIDGE_OBJECT)
|
||||
}
|
||||
bridgeInstalled = false
|
||||
replyProxy = null
|
||||
}
|
||||
|
||||
/** Chromium calls this on the UI thread, which is also the only thread that may reply. */
|
||||
private val bridgeListener = WebViewCompat.WebMessageListener {
|
||||
_, message, _, isMainFrame, proxy ->
|
||||
val isStringMessage = message.type == WebMessageCompat.TYPE_STRING
|
||||
val json = if (isStringMessage) message.data else null
|
||||
if (
|
||||
acceptsMobileWebShellBridgeFrame(
|
||||
isMainFrame,
|
||||
isStringMessage,
|
||||
loadState.hasCommittedDocument
|
||||
) && json != null &&
|
||||
bridgeGate.accepts(json.toByteArray(Charsets.UTF_8).size)
|
||||
) {
|
||||
replyProxy = proxy
|
||||
sink?.documentBridgeMessage(json)
|
||||
}
|
||||
}
|
||||
|
||||
/** Throw so a host chunking bug rejects rather than leaving its request unsettled. */
|
||||
fun postBridgeMessage(json: String) {
|
||||
val proxy = replyProxy ?: throw MobileWebShellBridgeUnavailableException()
|
||||
val byteCount = json.toByteArray(Charsets.UTF_8).size
|
||||
if (!acceptsMobileWebShellBridgeByteCount(byteCount)) {
|
||||
throw MobileWebShellBridgeMessageTooLargeException(byteCount)
|
||||
}
|
||||
proxy.postMessage(json)
|
||||
}
|
||||
|
||||
/** A frame from the shell itself, to the frame that spoke. */
|
||||
fun postHostFrame(json: String) {
|
||||
replyProxy?.postMessage(json)
|
||||
}
|
||||
|
||||
/** The view's attach and detach: off-window, the page reads hidden, as a buried WKWebView does on iOS. */
|
||||
fun resume() {
|
||||
webView?.onResume()
|
||||
}
|
||||
|
||||
fun pause() {
|
||||
webView?.onPause()
|
||||
}
|
||||
|
||||
/** The view is done with it, or onRenderProcessGone. */
|
||||
fun destroyWebView() {
|
||||
val view = webView ?: return
|
||||
removeBridgeListener()
|
||||
loadState.documentEnded()
|
||||
webView = null
|
||||
blocker?.remove()
|
||||
blocker = null
|
||||
served = null
|
||||
documentFailed = false
|
||||
view.stopLoading()
|
||||
(view.parent as? ViewGroup)?.removeView(view)
|
||||
view.destroy()
|
||||
}
|
||||
|
||||
// Keep explicit settings for the Chromium 83 floor, even where newer WebViews ignore deprecated options.
|
||||
// B4 requires device proofs: no network, persistent state, file/content access, cleartext or navigation escape.
|
||||
@Suppress("DEPRECATION")
|
||||
private fun createWebView(): WebView {
|
||||
val view = MobileWebShellSelectionView(context)
|
||||
view.setBackgroundColor(Color.TRANSPARENT)
|
||||
view.settings.apply {
|
||||
javaScriptEnabled = true
|
||||
domStorageEnabled = false
|
||||
databaseEnabled = false
|
||||
allowFileAccess = false
|
||||
allowFileAccessFromFileURLs = false
|
||||
allowUniversalAccessFromFileURLs = false
|
||||
allowContentAccess = false
|
||||
javaScriptCanOpenWindowsAutomatically = false
|
||||
setSupportMultipleWindows(false)
|
||||
mixedContentMode = WebSettings.MIXED_CONTENT_NEVER_ALLOW
|
||||
cacheMode = WebSettings.LOAD_NO_CACHE
|
||||
blockNetworkLoads = true
|
||||
mediaPlaybackRequiresUserGesture = true
|
||||
setGeolocationEnabled(false)
|
||||
}
|
||||
// clearCache(true) is process-global, including terminals; use per-view LOAD_NO_CACHE and no-store.
|
||||
view.webViewClient = ShellWebViewClient()
|
||||
view.webChromeClient = object : WebChromeClient() {
|
||||
override fun onCreateWindow(
|
||||
view: WebView?,
|
||||
isDialog: Boolean,
|
||||
isUserGesture: Boolean,
|
||||
resultMsg: Message?
|
||||
): Boolean = false
|
||||
}
|
||||
view.setDownloadListener { _, _, _, _, _ -> }
|
||||
// Replace WebView inset handling on P–R/S+; forward zeroed insets for S+ parity.
|
||||
ViewCompat.setOnApplyWindowInsetsListener(view) { target, insets ->
|
||||
ViewCompat.onApplyWindowInsets(target, insetsForShellPage(insets))
|
||||
}
|
||||
return view
|
||||
}
|
||||
|
||||
private fun emit(emission: MobileWebShellLoadEmission?) {
|
||||
if (emission != null) sink?.documentLoadState(emission.toPayload())
|
||||
}
|
||||
|
||||
/** Post hiding past Chromium’s error-document commit; interception may also run off the main thread. */
|
||||
private fun reportDocumentFailure() {
|
||||
replyProxy = null
|
||||
// Drop replies synchronously before Chromium’s error document commits and the posted hide runs.
|
||||
loadState.documentEnded()
|
||||
// Set before posting: intervening onPageFinished must not restore ready or expose the error page.
|
||||
documentFailed = true
|
||||
val epoch = loadState.epoch
|
||||
// The WebView's queue, like the view it sits in: a detached document reports once it attaches.
|
||||
webView?.post {
|
||||
if (!documentFailed) return@post
|
||||
val emission = loadState.failedDuring(
|
||||
epoch,
|
||||
MobileWebShellFailureReason.DOCUMENT_LOAD_FAILED
|
||||
) ?: return@post
|
||||
webView?.visibility = View.INVISIBLE
|
||||
emit(emission)
|
||||
}
|
||||
}
|
||||
|
||||
private fun isDocumentUrl(url: Uri): Boolean {
|
||||
val host = served?.originHost ?: return false
|
||||
return resolveMobileWebShellRequestPath(requestParts(url), host) == "/"
|
||||
}
|
||||
|
||||
private fun requestParts(
|
||||
url: Uri,
|
||||
method: String = "GET",
|
||||
hasRangeHeader: Boolean = false
|
||||
): MobileWebShellRequestParts = MobileWebShellRequestParts(
|
||||
method = method,
|
||||
hasRangeHeader = hasRangeHeader,
|
||||
scheme = url.scheme,
|
||||
host = url.host,
|
||||
port = url.port,
|
||||
userInfo = url.userInfo,
|
||||
query = url.query,
|
||||
fragment = url.fragment,
|
||||
encodedPath = url.encodedPath,
|
||||
urlLength = url.toString().length
|
||||
)
|
||||
|
||||
private fun serveRequest(request: WebResourceRequest): WebResourceResponse? {
|
||||
val current = served ?: return null
|
||||
val parts = requestParts(
|
||||
request.url,
|
||||
method = request.method,
|
||||
hasRangeHeader = request.requestHeaders.keys.any { it.equals("Range", ignoreCase = true) }
|
||||
)
|
||||
val path = resolveMobileWebShellRequestPath(parts, current.originHost) ?: return null
|
||||
val asset = current.generation.entries[path] ?: return null
|
||||
val bytes = runCatching { asset.file.readBytes() }.getOrNull() ?: return null
|
||||
val headers = mobileWebShellResponseHeaders(path, bytes.size)
|
||||
val (mimeType, charset) = splitMobileWebShellContentType(asset.contentType)
|
||||
return WebResourceResponse(mimeType, charset, 200, "OK", headers, ByteArrayInputStream(bytes))
|
||||
}
|
||||
|
||||
private fun refusedResponse(): WebResourceResponse = WebResourceResponse(
|
||||
MOBILE_WEB_SHELL_REFUSAL_MIME_TYPE,
|
||||
MOBILE_WEB_SHELL_REFUSAL_CHARSET,
|
||||
MOBILE_WEB_SHELL_REFUSAL_STATUS,
|
||||
MOBILE_WEB_SHELL_REFUSAL_REASON,
|
||||
MOBILE_WEB_SHELL_REFUSAL_HEADERS,
|
||||
ByteArrayInputStream(mobileWebShellRefusalBody())
|
||||
)
|
||||
|
||||
private inner class ShellWebViewClient : WebViewClient() {
|
||||
/** Never null, so no request can fall through to the network. */
|
||||
override fun shouldInterceptRequest(
|
||||
view: WebView,
|
||||
request: WebResourceRequest
|
||||
): WebResourceResponse {
|
||||
val response = serveRequest(request)
|
||||
if (response != null) return response
|
||||
if (request.isForMainFrame) reportDocumentFailure()
|
||||
return refusedResponse()
|
||||
}
|
||||
|
||||
override fun shouldOverrideUrlLoading(view: WebView, request: WebResourceRequest): Boolean {
|
||||
// hasGesture gates only opener offers: human requests may omit it and subframes can target top without it.
|
||||
val verdict = mobileWebShellNavigationVerdict(
|
||||
url = request.url?.toString(),
|
||||
isForMainFrame = request.isForMainFrame,
|
||||
// Not reported here, unlike WKNavigationAction.sourceFrame on iOS.
|
||||
isFromSubframe = false,
|
||||
isDocumentUrl = !mobileWebShellDropsNavigation(
|
||||
requestParts(request.url),
|
||||
served?.originHost,
|
||||
request.isForMainFrame
|
||||
),
|
||||
// loadUrl bypasses this callback by WebViewClient contract; no callback action is our own load.
|
||||
isShellLoad = false,
|
||||
hasGesture = request.hasGesture(),
|
||||
isDownload = false
|
||||
)
|
||||
if (verdict is MobileWebShellNavigationVerdict.CancelAndOffer) {
|
||||
sink?.documentExternalNavigation(verdict.url)
|
||||
}
|
||||
return verdict !is MobileWebShellNavigationVerdict.Allow
|
||||
}
|
||||
|
||||
override fun onPageStarted(view: WebView, url: String, favicon: Bitmap?) {
|
||||
// Discard the replaced document’s reply proxy; the next page must send ready.
|
||||
replyProxy = null
|
||||
loadState.documentEnded()
|
||||
if (documentFailed || !isDocumentUrl(Uri.parse(url))) return
|
||||
// Arm at commit before page script runs.
|
||||
loadState.committed()
|
||||
emit(loadState.started())
|
||||
}
|
||||
|
||||
// history.replaceState changes the document path before finish; commit state identifies the load.
|
||||
override fun onPageFinished(view: WebView, url: String) {
|
||||
if (documentFailed || !loadState.hasCommittedDocument) return
|
||||
view.visibility = View.VISIBLE
|
||||
// Remove history so the page cannot return to a replaced document.
|
||||
view.clearHistory()
|
||||
emit(loadState.finished())
|
||||
}
|
||||
|
||||
override fun onReceivedError(
|
||||
view: WebView,
|
||||
request: WebResourceRequest,
|
||||
error: WebResourceError
|
||||
) {
|
||||
if (request.isForMainFrame) reportDocumentFailure()
|
||||
}
|
||||
|
||||
override fun onReceivedHttpError(
|
||||
view: WebView,
|
||||
request: WebResourceRequest,
|
||||
errorResponse: WebResourceResponse
|
||||
) {
|
||||
if (request.isForMainFrame) reportDocumentFailure()
|
||||
}
|
||||
|
||||
/** Return true to avoid killing the app; destroy the dead WebView and leave retry policy to the caller. */
|
||||
override fun onRenderProcessGone(view: WebView, detail: RenderProcessGoneDetail): Boolean {
|
||||
// Android ends every WebView's renderer together; off-screen or low-memory losses are the OS's doing, not the page's.
|
||||
val host = view.parent as? View ?: view
|
||||
val background = !host.isShown || host.windowVisibility != View.VISIBLE
|
||||
destroyWebView()
|
||||
emit(loadState.rendererGone(background, detail.didCrash()))
|
||||
return true
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
internal class MobileWebShellBridgeUnavailableException :
|
||||
CodedException("The mobile web shell bridge is not installed on this view")
|
||||
|
||||
internal class MobileWebShellBridgeMessageTooLargeException(byteCount: Int) : CodedException(
|
||||
"A bridge message of $byteCount bytes exceeds the " +
|
||||
"$MOBILE_WEB_SHELL_BRIDGE_MAX_MESSAGE_BYTES byte cap"
|
||||
)
|
||||
|
||||
/** The shell already pads bars/keyboard; zero (never consume) insets to prevent WebView M144+ bar and M139+ IME double-padding. */
|
||||
private fun insetsForShellPage(insets: WindowInsetsCompat): WindowInsetsCompat =
|
||||
WindowInsetsCompat.Builder(insets)
|
||||
.setInsets(SHELL_OWNED_INSET_TYPES, Insets.NONE)
|
||||
.build()
|
||||
|
||||
private val SHELL_OWNED_INSET_TYPES =
|
||||
WindowInsetsCompat.Type.systemBars() or
|
||||
WindowInsetsCompat.Type.displayCutout() or
|
||||
WindowInsetsCompat.Type.ime()
|
||||
+1
@@ -26,6 +26,7 @@ internal data class MobileWebShellLoadEmission(
|
||||
/** Failure is terminal and duplicate reports are dropped: late error-document/rule-list callbacks must never restore ready. Cross-thread readers require volatile state. */
|
||||
internal class MobileWebShellLoadStateMachine {
|
||||
private var terminal = false
|
||||
val isTerminal: Boolean get() = terminal
|
||||
private var last: MobileWebShellLoadEmission? = null
|
||||
private var rendererLoss: Pair<Boolean, Boolean>? = null
|
||||
|
||||
|
||||
+169
@@ -0,0 +1,169 @@
|
||||
package expo.modules.orcamobilewebshell
|
||||
|
||||
import android.app.Activity
|
||||
import android.app.ActivityManager
|
||||
import android.content.Context
|
||||
import android.os.Handler
|
||||
import android.os.Looper
|
||||
import android.view.MotionEvent
|
||||
import android.view.View
|
||||
import android.view.ViewGroup
|
||||
import android.widget.FrameLayout
|
||||
import java.util.Collections
|
||||
import java.util.WeakHashMap
|
||||
|
||||
/** More than 3 GiB can only come from a phone with 4 GB or more; those report about 3.5 to 3.9 GiB. */
|
||||
private const val MINIMUM_TOTAL_MEMORY_BYTES = 3L shl 30
|
||||
|
||||
/** A claim is adopted on the claiming screen's first commit; this only bounds a screen that never mounts. */
|
||||
private const val CLAIM_EXPIRY_MS = 10_000L
|
||||
|
||||
/** Holds a parked WebView under the app's content: invisible, untouchable and out of accessibility. */
|
||||
private class MobileWebShellParking(context: Context) : FrameLayout(context) {
|
||||
init {
|
||||
alpha = 0f
|
||||
isFocusable = false
|
||||
descendantFocusability = ViewGroup.FOCUS_BLOCK_DESCENDANTS
|
||||
importantForAccessibility = View.IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS
|
||||
}
|
||||
|
||||
override fun dispatchTouchEvent(event: MotionEvent): Boolean = false
|
||||
}
|
||||
|
||||
/**
|
||||
* A booted document waiting for a screen. It keeps what the page reported, and the page's ready, for
|
||||
* the view that adopts it: a parked page stops asking for init, so its ready is answered from here.
|
||||
*/
|
||||
internal class MobileWebShellSpare(
|
||||
activity: Activity,
|
||||
val directory: String,
|
||||
val sessionId: String
|
||||
) : MobileWebShellDocumentSink {
|
||||
val document = MobileWebShellDocument(activity)
|
||||
val parking: ViewGroup = MobileWebShellParking(activity)
|
||||
private val loadStates = mutableListOf<Map<String, Any>>()
|
||||
private var ready: String? = null
|
||||
|
||||
init {
|
||||
document.sink = this
|
||||
}
|
||||
|
||||
override fun documentLoadState(payload: Map<String, Any>) {
|
||||
loadStates += payload
|
||||
if (payload["state"] == "failed") MobileWebShellSparePool.discard(this)
|
||||
}
|
||||
|
||||
/** Before init a page only sends ready, from its first document or one it reloaded. */
|
||||
override fun documentBridgeMessage(json: String) {
|
||||
ready = json
|
||||
document.postHostFrame(MOBILE_WEB_SHELL_PARKED_FRAME)
|
||||
}
|
||||
|
||||
// A parked page has no screen to have been tapped on.
|
||||
override fun documentExternalNavigation(url: String) = Unit
|
||||
|
||||
/** The adopting view sees what a fresh document would have reported, ready last. */
|
||||
fun handOver(sink: MobileWebShellDocumentSink) {
|
||||
document.sink = sink
|
||||
loadStates.forEach(sink::documentLoadState)
|
||||
ready?.let(sink::documentBridgeMessage)
|
||||
}
|
||||
|
||||
fun destroy() {
|
||||
document.destroyWebView()
|
||||
(parking.parent as? ViewGroup)?.removeView(parking)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* At most one document booted ahead of its screen, only while no page document is shown. Main thread only.
|
||||
* Parked attached under the content, not detached: a detached WebView took 0.3–1.9 s to paint after 30 s, vs 0.2 s.
|
||||
*/
|
||||
internal object MobileWebShellSparePool {
|
||||
private val main = Handler(Looper.getMainLooper())
|
||||
private var parked: MobileWebShellSpare? = null
|
||||
private var claimed: MobileWebShellSpare? = null
|
||||
private val shown: MutableSet<MobileWebShellDocument> =
|
||||
Collections.newSetFromMap(WeakHashMap())
|
||||
|
||||
/** Whether a spare for [directory] is parked after the call; never on a small phone or beside a page. */
|
||||
fun prepare(activity: Activity, directory: String, sessionId: String): Boolean {
|
||||
if (!inForeground() || cannotAffordSpare(activity) || shown.any { it.webView != null }) return false
|
||||
val current = parked
|
||||
if (current != null && current.directory == directory && current.document.isUsable) return true
|
||||
val decor = activity.window?.decorView as? ViewGroup ?: return false
|
||||
// A claim no view adopted was abandoned; it must not outlive the spare that replaces it.
|
||||
discardAll()
|
||||
val spare = MobileWebShellSpare(activity, directory, sessionId)
|
||||
val webView = spare.document.webView ?: return false
|
||||
spare.parking.addView(webView, FrameLayout.LayoutParams(MATCH, MATCH))
|
||||
decor.addView(spare.parking, 0, FrameLayout.LayoutParams(MATCH, MATCH))
|
||||
parked = spare
|
||||
spare.document.apply(directory, sessionId, bridgeEnabled = true)
|
||||
// A load that failed at once has already discarded it.
|
||||
return parked === spare
|
||||
}
|
||||
|
||||
/** The parked spare's session id for a screen opening [directory], handed out once. */
|
||||
fun claim(directory: String): String? {
|
||||
val spare = parked ?: return null
|
||||
if (spare.directory != directory || !spare.document.isUsable) return null
|
||||
parked = null
|
||||
claimed = spare
|
||||
main.postDelayed({ if (claimed === spare) discard(spare) }, CLAIM_EXPIRY_MS)
|
||||
return spare.sessionId
|
||||
}
|
||||
|
||||
/** The claimed spare when [sessionId] names it, else a fresh document, which leaves no room for a spare. */
|
||||
fun document(
|
||||
context: Context,
|
||||
sessionId: String,
|
||||
sink: MobileWebShellDocumentSink
|
||||
): MobileWebShellDocument {
|
||||
val spare = claimed
|
||||
val document = if (spare != null && spare.sessionId == sessionId && spare.document.isUsable) {
|
||||
claimed = null
|
||||
spare.document.webView?.let { spare.parking.removeView(it) }
|
||||
(spare.parking.parent as? ViewGroup)?.removeView(spare.parking)
|
||||
spare.handOver(sink)
|
||||
spare.document
|
||||
} else {
|
||||
discardAll()
|
||||
MobileWebShellDocument(context).also { it.sink = sink }
|
||||
}
|
||||
shown += document
|
||||
return document
|
||||
}
|
||||
|
||||
/** Memory pressure, the app leaving the foreground, files going away, or Home without a claim. */
|
||||
fun discardAll() {
|
||||
listOfNotNull(parked, claimed).forEach(MobileWebShellSpare::destroy)
|
||||
parked = null
|
||||
claimed = null
|
||||
}
|
||||
|
||||
fun discard(spare: MobileWebShellSpare) {
|
||||
when {
|
||||
parked === spare -> parked = null
|
||||
claimed === spare -> claimed = null
|
||||
else -> return
|
||||
}
|
||||
spare.destroy()
|
||||
}
|
||||
|
||||
/** React Native keeps its activity after it stops, so ask the process's own importance. */
|
||||
private fun inForeground(): Boolean {
|
||||
val state = ActivityManager.RunningAppProcessInfo()
|
||||
ActivityManager.getMyMemoryState(state)
|
||||
return state.importance <= ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND
|
||||
}
|
||||
|
||||
private fun cannotAffordSpare(activity: Activity): Boolean {
|
||||
val manager = activity.getSystemService(ActivityManager::class.java) ?: return true
|
||||
val memory = ActivityManager.MemoryInfo().also(manager::getMemoryInfo)
|
||||
// Android 14 stopped sending RUNNING_LOW trims to foreground apps, so check pressure before booting.
|
||||
return manager.isLowRamDevice || memory.totalMem <= MINIMUM_TOTAL_MEMORY_BYTES || memory.lowMemory
|
||||
}
|
||||
}
|
||||
|
||||
private const val MATCH = ViewGroup.LayoutParams.MATCH_PARENT
|
||||
+22
-370
@@ -2,44 +2,16 @@ package expo.modules.orcamobilewebshell
|
||||
|
||||
import android.annotation.SuppressLint
|
||||
import android.content.Context
|
||||
import android.graphics.Bitmap
|
||||
import android.graphics.Color
|
||||
import android.net.Uri
|
||||
import android.os.Message
|
||||
import android.view.View
|
||||
import android.webkit.RenderProcessGoneDetail
|
||||
import android.webkit.WebChromeClient
|
||||
import android.webkit.WebResourceError
|
||||
import android.webkit.WebResourceRequest
|
||||
import android.webkit.WebResourceResponse
|
||||
import android.webkit.WebSettings
|
||||
import android.webkit.WebView
|
||||
import android.webkit.WebViewClient
|
||||
import androidx.core.graphics.Insets
|
||||
import androidx.core.view.ViewCompat
|
||||
import androidx.core.view.WindowInsetsCompat
|
||||
import androidx.webkit.JavaScriptReplyProxy
|
||||
import androidx.webkit.ScriptHandler
|
||||
import androidx.webkit.WebMessageCompat
|
||||
import androidx.webkit.WebViewCompat
|
||||
import androidx.webkit.WebViewFeature
|
||||
import expo.modules.kotlin.AppContext
|
||||
import expo.modules.kotlin.exception.CodedException
|
||||
import expo.modules.kotlin.viewevent.EventDispatcher
|
||||
import expo.modules.kotlin.views.ExpoView
|
||||
import java.io.ByteArrayInputStream
|
||||
|
||||
/** Publish host and manifest map atomically/volatily: main-thread writes race Chromium’s interceptor. */
|
||||
private class MobileWebShellServed(
|
||||
val generation: MobileWebShellGeneration,
|
||||
val originHost: String
|
||||
)
|
||||
|
||||
@SuppressLint("ViewConstructor", "SetJavaScriptEnabled")
|
||||
/** React Native's handle on one document: it lays the WebView out and forwards what it reports. */
|
||||
@SuppressLint("ViewConstructor")
|
||||
internal class OrcaMobileWebShellView(
|
||||
context: Context,
|
||||
appContext: AppContext
|
||||
) : ExpoView(context, appContext) {
|
||||
) : ExpoView(context, appContext), MobileWebShellDocumentSink {
|
||||
private val onLoadState by EventDispatcher<Map<String, Any>>()
|
||||
private val onBridgeMessage by EventDispatcher<Map<String, Any>>()
|
||||
private val onExternalNavigation by EventDispatcher<Map<String, Any>>()
|
||||
@@ -47,23 +19,8 @@ internal class OrcaMobileWebShellView(
|
||||
private var generationDirectory = ""
|
||||
private var sessionId = ""
|
||||
private var bridgeEnabled = false
|
||||
private var bridgeInstalled = false
|
||||
private val bridgeGate = MobileWebShellBridgeGate()
|
||||
// The page sends ready before native replies; volatile proxy state crosses interceptor/UI threads.
|
||||
@Volatile private var replyProxy: JavaScriptReplyProxy? = null
|
||||
private var applied: MobileWebShellAppliedProps? = null
|
||||
private val loadState = MobileWebShellLoadStateMachine()
|
||||
// Failure state crosses main-thread callbacks and Chromium’s background interceptor.
|
||||
@Volatile private var documentFailed = false
|
||||
@Volatile private var served: MobileWebShellServed? = null
|
||||
private var blocker: ScriptHandler? = null
|
||||
private var webView: WebView? = createWebView()
|
||||
|
||||
init {
|
||||
addView(webView, LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT))
|
||||
// Why: Chromium reports an unpaused, never-attached WebView as visible, and a screen pushed under another never attaches.
|
||||
webView?.onPause()
|
||||
}
|
||||
/** Taken on the first prop commit, not in init: the session id says whether a spare was booted for it. */
|
||||
private var document: MobileWebShellDocument? = null
|
||||
|
||||
fun setGenerationDirectory(value: String) {
|
||||
generationDirectory = value
|
||||
@@ -77,348 +34,43 @@ internal class OrcaMobileWebShellView(
|
||||
bridgeEnabled = value
|
||||
}
|
||||
|
||||
/** Apply unordered props together; identical triples do not retry. Recovery requires a remount. */
|
||||
fun propsDidUpdate() {
|
||||
val next = MobileWebShellAppliedProps(generationDirectory, sessionId, bridgeEnabled)
|
||||
if (applied?.matches(next) == true) return
|
||||
applied = next
|
||||
documentFailed = false
|
||||
loadState.reset()
|
||||
val view = webView
|
||||
if (view == null) {
|
||||
// A dead renderer requires a remount; changed props must still report failure.
|
||||
emit(loadState.rendererStillGone())
|
||||
return
|
||||
}
|
||||
view.stopLoading()
|
||||
emit(loadState.started())
|
||||
|
||||
val origin = mobileWebShellOrigin(sessionId)
|
||||
val host = mobileWebShellOriginHost(sessionId)
|
||||
if (origin == null || host == null) {
|
||||
// The private origin is the isolation primitive; a malformed session id leaves us without one.
|
||||
failPropUpdate(MobileWebShellFailureReason.ISOLATION_UNAVAILABLE)
|
||||
return
|
||||
}
|
||||
val loaded = MobileWebShellGeneration.load(generationDirectory)
|
||||
if (loaded == null) {
|
||||
failPropUpdate(MobileWebShellFailureReason.GENERATION_UNREADABLE)
|
||||
return
|
||||
}
|
||||
blocker?.remove()
|
||||
blocker = installMobileWebShellNetworkApiBlocker(view, origin)
|
||||
if (blocker == null) {
|
||||
failPropUpdate(MobileWebShellFailureReason.ISOLATION_UNAVAILABLE)
|
||||
return
|
||||
}
|
||||
if (!applyBridgeListener(view, origin)) {
|
||||
failPropUpdate(MobileWebShellFailureReason.ISOLATION_UNAVAILABLE)
|
||||
return
|
||||
}
|
||||
served = MobileWebShellServed(loaded, host)
|
||||
view.visibility = View.VISIBLE
|
||||
view.loadUrl("$origin/")
|
||||
val current = document ?: hostDocument().also { document = it }
|
||||
current.apply(generationDirectory, sessionId, bridgeEnabled)
|
||||
}
|
||||
|
||||
/** Retire the old visible generation even when the replacement fails. */
|
||||
private fun failPropUpdate(reason: MobileWebShellFailureReason) {
|
||||
// Remove the old listener: stopLoading leaves its same-origin document alive and able to rearm replies.
|
||||
removeBridgeListener()
|
||||
served = null
|
||||
webView?.visibility = View.INVISIBLE
|
||||
emit(loadState.failed(reason))
|
||||
private fun hostDocument(): MobileWebShellDocument {
|
||||
val document = MobileWebShellSparePool.document(context, sessionId, this)
|
||||
addView(document.webView, LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT))
|
||||
// Why: Chromium reports an unpaused, never-attached WebView as visible, and a screen pushed under another never attaches.
|
||||
if (!isAttachedToWindow) document.pause()
|
||||
return document
|
||||
}
|
||||
|
||||
/** addWebMessageListener injects before scripts and enforces origins; false means unsupported provider. */
|
||||
private fun applyBridgeListener(view: WebView, origin: String): Boolean {
|
||||
removeBridgeListener()
|
||||
val outcome = mobileWebShellBridgeInstall(
|
||||
bridgeEnabled,
|
||||
WebViewFeature.isFeatureSupported(WebViewFeature.WEB_MESSAGE_LISTENER)
|
||||
)
|
||||
if (outcome != MobileWebShellBridgeInstall.INSTALL) {
|
||||
return outcome == MobileWebShellBridgeInstall.SKIP
|
||||
}
|
||||
return runCatching {
|
||||
WebViewCompat.addWebMessageListener(
|
||||
view,
|
||||
MOBILE_WEB_SHELL_BRIDGE_OBJECT,
|
||||
setOf(origin),
|
||||
bridgeListener
|
||||
)
|
||||
bridgeInstalled = true
|
||||
}.isSuccess
|
||||
}
|
||||
|
||||
/** The one way the bridge goes away, so no disable path can leave a listener behind. */
|
||||
private fun removeBridgeListener() {
|
||||
val view = webView
|
||||
if (bridgeInstalled && view != null) {
|
||||
WebViewCompat.removeWebMessageListener(view, MOBILE_WEB_SHELL_BRIDGE_OBJECT)
|
||||
}
|
||||
bridgeInstalled = false
|
||||
replyProxy = null
|
||||
}
|
||||
|
||||
/** Chromium calls this on the UI thread, which is also the only thread that may reply. */
|
||||
private val bridgeListener = WebViewCompat.WebMessageListener {
|
||||
_, message, _, isMainFrame, proxy ->
|
||||
val isStringMessage = message.type == WebMessageCompat.TYPE_STRING
|
||||
val json = if (isStringMessage) message.data else null
|
||||
if (
|
||||
acceptsMobileWebShellBridgeFrame(
|
||||
isMainFrame,
|
||||
isStringMessage,
|
||||
loadState.hasCommittedDocument
|
||||
) && json != null &&
|
||||
bridgeGate.accepts(json.toByteArray(Charsets.UTF_8).size)
|
||||
) {
|
||||
replyProxy = proxy
|
||||
onBridgeMessage(mapOf("json" to json))
|
||||
}
|
||||
}
|
||||
|
||||
/** Throw so a host chunking bug rejects rather than leaving its request unsettled. */
|
||||
fun postBridgeMessage(json: String) {
|
||||
val proxy = replyProxy ?: throw MobileWebShellBridgeUnavailableException()
|
||||
val byteCount = json.toByteArray(Charsets.UTF_8).size
|
||||
if (!acceptsMobileWebShellBridgeByteCount(byteCount)) {
|
||||
throw MobileWebShellBridgeMessageTooLargeException(byteCount)
|
||||
}
|
||||
proxy.postMessage(json)
|
||||
val current = document ?: throw MobileWebShellBridgeUnavailableException()
|
||||
current.postBridgeMessage(json)
|
||||
}
|
||||
|
||||
override fun onAttachedToWindow() {
|
||||
super.onAttachedToWindow()
|
||||
webView?.onResume()
|
||||
document?.resume()
|
||||
}
|
||||
|
||||
// Stay paused whenever off-window so the page reads hidden, as a buried WKWebView does on iOS.
|
||||
override fun onDetachedFromWindow() {
|
||||
webView?.onPause()
|
||||
document?.pause()
|
||||
super.onDetachedFromWindow()
|
||||
}
|
||||
|
||||
/** Expo calls this once React Native is done with the view, and onRenderProcessGone calls it. */
|
||||
/** Expo calls this once React Native is done with the view. */
|
||||
fun destroyWebView() {
|
||||
val view = webView ?: return
|
||||
removeBridgeListener()
|
||||
loadState.documentEnded()
|
||||
webView = null
|
||||
blocker?.remove()
|
||||
blocker = null
|
||||
served = null
|
||||
documentFailed = false
|
||||
view.stopLoading()
|
||||
removeView(view)
|
||||
view.destroy()
|
||||
document?.destroyWebView()
|
||||
}
|
||||
|
||||
// Keep explicit settings for the Chromium 83 floor, even where newer WebViews ignore deprecated options.
|
||||
// B4 requires device proofs: no network, persistent state, file/content access, cleartext or navigation escape.
|
||||
@Suppress("DEPRECATION")
|
||||
private fun createWebView(): WebView {
|
||||
val view = MobileWebShellSelectionView(context)
|
||||
view.setBackgroundColor(Color.TRANSPARENT)
|
||||
view.settings.apply {
|
||||
javaScriptEnabled = true
|
||||
domStorageEnabled = false
|
||||
databaseEnabled = false
|
||||
allowFileAccess = false
|
||||
allowFileAccessFromFileURLs = false
|
||||
allowUniversalAccessFromFileURLs = false
|
||||
allowContentAccess = false
|
||||
javaScriptCanOpenWindowsAutomatically = false
|
||||
setSupportMultipleWindows(false)
|
||||
mixedContentMode = WebSettings.MIXED_CONTENT_NEVER_ALLOW
|
||||
cacheMode = WebSettings.LOAD_NO_CACHE
|
||||
blockNetworkLoads = true
|
||||
mediaPlaybackRequiresUserGesture = true
|
||||
setGeolocationEnabled(false)
|
||||
}
|
||||
// clearCache(true) is process-global, including terminals; use per-view LOAD_NO_CACHE and no-store.
|
||||
view.webViewClient = ShellWebViewClient()
|
||||
view.webChromeClient = object : WebChromeClient() {
|
||||
override fun onCreateWindow(
|
||||
view: WebView?,
|
||||
isDialog: Boolean,
|
||||
isUserGesture: Boolean,
|
||||
resultMsg: Message?
|
||||
): Boolean = false
|
||||
}
|
||||
view.setDownloadListener { _, _, _, _, _ -> }
|
||||
// Replace WebView inset handling on P–R/S+; forward zeroed insets for S+ parity.
|
||||
ViewCompat.setOnApplyWindowInsetsListener(view) { target, insets ->
|
||||
ViewCompat.onApplyWindowInsets(target, insetsForShellPage(insets))
|
||||
}
|
||||
return view
|
||||
}
|
||||
override fun documentLoadState(payload: Map<String, Any>) = onLoadState(payload)
|
||||
|
||||
private fun emit(emission: MobileWebShellLoadEmission?) {
|
||||
if (emission != null) onLoadState(emission.toPayload())
|
||||
}
|
||||
override fun documentBridgeMessage(json: String) = onBridgeMessage(mapOf("json" to json))
|
||||
|
||||
/** Post hiding past Chromium’s error-document commit; interception may also run off the main thread. */
|
||||
private fun reportDocumentFailure() {
|
||||
replyProxy = null
|
||||
// Drop replies synchronously before Chromium’s error document commits and the posted hide runs.
|
||||
loadState.documentEnded()
|
||||
// Set before posting: intervening onPageFinished must not restore ready or expose the error page.
|
||||
documentFailed = true
|
||||
val epoch = loadState.epoch
|
||||
post {
|
||||
if (!documentFailed) return@post
|
||||
val emission = loadState.failedDuring(
|
||||
epoch,
|
||||
MobileWebShellFailureReason.DOCUMENT_LOAD_FAILED
|
||||
) ?: return@post
|
||||
webView?.visibility = View.INVISIBLE
|
||||
emit(emission)
|
||||
}
|
||||
}
|
||||
|
||||
private fun isDocumentUrl(url: Uri): Boolean {
|
||||
val host = served?.originHost ?: return false
|
||||
return resolveMobileWebShellRequestPath(requestParts(url), host) == "/"
|
||||
}
|
||||
|
||||
private fun requestParts(
|
||||
url: Uri,
|
||||
method: String = "GET",
|
||||
hasRangeHeader: Boolean = false
|
||||
): MobileWebShellRequestParts = MobileWebShellRequestParts(
|
||||
method = method,
|
||||
hasRangeHeader = hasRangeHeader,
|
||||
scheme = url.scheme,
|
||||
host = url.host,
|
||||
port = url.port,
|
||||
userInfo = url.userInfo,
|
||||
query = url.query,
|
||||
fragment = url.fragment,
|
||||
encodedPath = url.encodedPath,
|
||||
urlLength = url.toString().length
|
||||
)
|
||||
|
||||
private fun serveRequest(request: WebResourceRequest): WebResourceResponse? {
|
||||
val current = served ?: return null
|
||||
val parts = requestParts(
|
||||
request.url,
|
||||
method = request.method,
|
||||
hasRangeHeader = request.requestHeaders.keys.any { it.equals("Range", ignoreCase = true) }
|
||||
)
|
||||
val path = resolveMobileWebShellRequestPath(parts, current.originHost) ?: return null
|
||||
val asset = current.generation.entries[path] ?: return null
|
||||
val bytes = runCatching { asset.file.readBytes() }.getOrNull() ?: return null
|
||||
val headers = mobileWebShellResponseHeaders(path, bytes.size)
|
||||
val (mimeType, charset) = splitMobileWebShellContentType(asset.contentType)
|
||||
return WebResourceResponse(mimeType, charset, 200, "OK", headers, ByteArrayInputStream(bytes))
|
||||
}
|
||||
|
||||
private fun refusedResponse(): WebResourceResponse = WebResourceResponse(
|
||||
MOBILE_WEB_SHELL_REFUSAL_MIME_TYPE,
|
||||
MOBILE_WEB_SHELL_REFUSAL_CHARSET,
|
||||
MOBILE_WEB_SHELL_REFUSAL_STATUS,
|
||||
MOBILE_WEB_SHELL_REFUSAL_REASON,
|
||||
MOBILE_WEB_SHELL_REFUSAL_HEADERS,
|
||||
ByteArrayInputStream(mobileWebShellRefusalBody())
|
||||
)
|
||||
|
||||
private inner class ShellWebViewClient : WebViewClient() {
|
||||
/** Never null, so no request can fall through to the network. */
|
||||
override fun shouldInterceptRequest(
|
||||
view: WebView,
|
||||
request: WebResourceRequest
|
||||
): WebResourceResponse {
|
||||
val response = serveRequest(request)
|
||||
if (response != null) return response
|
||||
if (request.isForMainFrame) reportDocumentFailure()
|
||||
return refusedResponse()
|
||||
}
|
||||
|
||||
override fun shouldOverrideUrlLoading(view: WebView, request: WebResourceRequest): Boolean {
|
||||
// hasGesture gates only opener offers: human requests may omit it and subframes can target top without it.
|
||||
val verdict = mobileWebShellNavigationVerdict(
|
||||
url = request.url?.toString(),
|
||||
isForMainFrame = request.isForMainFrame,
|
||||
// Not reported here, unlike WKNavigationAction.sourceFrame on iOS.
|
||||
isFromSubframe = false,
|
||||
isDocumentUrl = !mobileWebShellDropsNavigation(
|
||||
requestParts(request.url),
|
||||
served?.originHost,
|
||||
request.isForMainFrame
|
||||
),
|
||||
// loadUrl bypasses this callback by WebViewClient contract; no callback action is our own load.
|
||||
isShellLoad = false,
|
||||
hasGesture = request.hasGesture(),
|
||||
isDownload = false
|
||||
)
|
||||
if (verdict is MobileWebShellNavigationVerdict.CancelAndOffer) {
|
||||
onExternalNavigation(mapOf("url" to verdict.url))
|
||||
}
|
||||
return verdict !is MobileWebShellNavigationVerdict.Allow
|
||||
}
|
||||
|
||||
override fun onPageStarted(view: WebView, url: String, favicon: Bitmap?) {
|
||||
// Discard the replaced document’s reply proxy; the next page must send ready.
|
||||
replyProxy = null
|
||||
loadState.documentEnded()
|
||||
if (documentFailed || !isDocumentUrl(Uri.parse(url))) return
|
||||
// Arm at commit before page script runs.
|
||||
loadState.committed()
|
||||
emit(loadState.started())
|
||||
}
|
||||
|
||||
// history.replaceState changes the document path before finish; commit state identifies the load.
|
||||
override fun onPageFinished(view: WebView, url: String) {
|
||||
if (documentFailed || !loadState.hasCommittedDocument) return
|
||||
view.visibility = View.VISIBLE
|
||||
// Remove history so the page cannot return to a replaced document.
|
||||
view.clearHistory()
|
||||
emit(loadState.finished())
|
||||
}
|
||||
|
||||
override fun onReceivedError(
|
||||
view: WebView,
|
||||
request: WebResourceRequest,
|
||||
error: WebResourceError
|
||||
) {
|
||||
if (request.isForMainFrame) reportDocumentFailure()
|
||||
}
|
||||
|
||||
override fun onReceivedHttpError(
|
||||
view: WebView,
|
||||
request: WebResourceRequest,
|
||||
errorResponse: WebResourceResponse
|
||||
) {
|
||||
if (request.isForMainFrame) reportDocumentFailure()
|
||||
}
|
||||
|
||||
/** Return true to avoid killing the app; destroy the dead WebView and leave retry policy to the caller. */
|
||||
override fun onRenderProcessGone(view: WebView, detail: RenderProcessGoneDetail): Boolean {
|
||||
// Android ends every WebView's renderer together; off-screen or low-memory losses are the OS's doing, not the page's.
|
||||
val background = !isShown || windowVisibility != View.VISIBLE
|
||||
destroyWebView()
|
||||
emit(loadState.rendererGone(background, detail.didCrash()))
|
||||
return true
|
||||
}
|
||||
}
|
||||
override fun documentExternalNavigation(url: String) = onExternalNavigation(mapOf("url" to url))
|
||||
}
|
||||
|
||||
internal class MobileWebShellBridgeUnavailableException :
|
||||
CodedException("The mobile web shell bridge is not installed on this view")
|
||||
|
||||
internal class MobileWebShellBridgeMessageTooLargeException(byteCount: Int) : CodedException(
|
||||
"A bridge message of $byteCount bytes exceeds the " +
|
||||
"$MOBILE_WEB_SHELL_BRIDGE_MAX_MESSAGE_BYTES byte cap"
|
||||
)
|
||||
|
||||
/** The shell already pads bars/keyboard; zero (never consume) insets to prevent WebView M144+ bar and M139+ IME double-padding. */
|
||||
private fun insetsForShellPage(insets: WindowInsetsCompat): WindowInsetsCompat =
|
||||
WindowInsetsCompat.Builder(insets)
|
||||
.setInsets(SHELL_OWNED_INSET_TYPES, Insets.NONE)
|
||||
.build()
|
||||
|
||||
private val SHELL_OWNED_INSET_TYPES =
|
||||
WindowInsetsCompat.Type.systemBars() or
|
||||
WindowInsetsCompat.Type.displayCutout() or
|
||||
WindowInsetsCompat.Type.ime()
|
||||
|
||||
+58
@@ -1,17 +1,75 @@
|
||||
package expo.modules.orcamobilewebshell
|
||||
|
||||
import android.content.ActivityNotFoundException
|
||||
import android.content.ComponentCallbacks2
|
||||
import android.content.Context
|
||||
import android.content.Intent
|
||||
import android.content.res.Configuration
|
||||
import android.net.Uri
|
||||
import android.os.Handler
|
||||
import android.os.Looper
|
||||
import expo.modules.kotlin.exception.CodedException
|
||||
import expo.modules.kotlin.exception.Exceptions
|
||||
import expo.modules.kotlin.functions.Queues
|
||||
import expo.modules.kotlin.modules.Module
|
||||
import expo.modules.kotlin.modules.ModuleDefinition
|
||||
|
||||
class OrcaMobileWebShellModule : Module() {
|
||||
private val main = Handler(Looper.getMainLooper())
|
||||
// Kept so teardown unregisters from the same context after React has let go of it.
|
||||
private var callbacksContext: Context? = null
|
||||
|
||||
// A spare is the first thing to give back: nothing is shown by it. UI_HIDDEN, above RUNNING_LOW, is
|
||||
// the app leaving the foreground; an activity pause is not, since a notification tap or deep link
|
||||
// pauses it on the way to the screen that would claim the spare.
|
||||
private val memoryCallbacks = object : ComponentCallbacks2 {
|
||||
override fun onTrimMemory(level: Int) {
|
||||
if (level >= ComponentCallbacks2.TRIM_MEMORY_RUNNING_LOW) discardSpare()
|
||||
}
|
||||
|
||||
override fun onConfigurationChanged(newConfig: Configuration) = Unit
|
||||
|
||||
@Deprecated("Deprecated in Java")
|
||||
override fun onLowMemory() = discardSpare()
|
||||
}
|
||||
|
||||
// Callbacks and OnDestroy can run off the main thread, and the pool's WebViews must not.
|
||||
private fun discardSpare() {
|
||||
main.post { MobileWebShellSparePool.discardAll() }
|
||||
}
|
||||
|
||||
override fun definition() = ModuleDefinition {
|
||||
Name("OrcaMobileWebShell")
|
||||
|
||||
OnCreate {
|
||||
callbacksContext = appContext.reactContext?.applicationContext?.also {
|
||||
it.registerComponentCallbacks(memoryCallbacks)
|
||||
}
|
||||
}
|
||||
|
||||
OnDestroy {
|
||||
callbacksContext?.unregisterComponentCallbacks(memoryCallbacks)
|
||||
callbacksContext = null
|
||||
discardSpare()
|
||||
}
|
||||
|
||||
OnActivityDestroys {
|
||||
discardSpare()
|
||||
}
|
||||
|
||||
AsyncFunction("prepareSpareDocument") { directory: String, sessionId: String ->
|
||||
val activity = appContext.currentActivity ?: return@AsyncFunction false
|
||||
MobileWebShellSparePool.prepare(activity, directory, sessionId)
|
||||
}.runOnQueue(Queues.MAIN)
|
||||
|
||||
AsyncFunction("claimSpareDocument") { directory: String ->
|
||||
MobileWebShellSparePool.claim(directory)
|
||||
}.runOnQueue(Queues.MAIN)
|
||||
|
||||
AsyncFunction("discardSpareDocument") {
|
||||
MobileWebShellSparePool.discardAll()
|
||||
}.runOnQueue(Queues.MAIN)
|
||||
|
||||
// Takes a FileProvider content:// URI; the grant lets the chosen viewer read Orca's cache file.
|
||||
AsyncFunction("presentPdf") { uri: String ->
|
||||
val activity = appContext.currentActivity ?: throw Exceptions.MissingActivity()
|
||||
|
||||
@@ -5,6 +5,9 @@ enum MobileWebShellBridge {
|
||||
/// Use the same injected global/handler name on Android and iOS.
|
||||
static let handlerName = "orcaBridge"
|
||||
|
||||
/// Tells a page booted ahead of its screen to stop asking for init; the screen that adopts it answers.
|
||||
static let parkedFrame = #"{"v":1,"type":"parked"}"#
|
||||
|
||||
/// Enforce the shared UTF-8 JSON byte ceiling natively, before parsing.
|
||||
static let maxMessageByteCount = 640 * 1024
|
||||
|
||||
|
||||
@@ -0,0 +1,606 @@
|
||||
import ExpoModulesCore
|
||||
import WebKit
|
||||
|
||||
private let networkBlockIdentifier = "dev.orca.mobile-web-shell.network-block-v1"
|
||||
|
||||
/// Block http(s)/ws(s) beneath CSP; compilation failure is terminal and must load nothing.
|
||||
private let networkBlockRules = """
|
||||
[
|
||||
{ "trigger": { "url-filter": "^https?://" }, "action": { "type": "block" } },
|
||||
{ "trigger": { "url-filter": "^wss?://" }, "action": { "type": "block" } }
|
||||
]
|
||||
"""
|
||||
|
||||
/// Compiled once per launch and shared by every view, so later mounts load without waiting; main thread only.
|
||||
private enum NetworkBlockRuleList {
|
||||
private static var compiled: WKContentRuleList?
|
||||
|
||||
/// Synchronous once compiled in this process; nil means isolation is unavailable.
|
||||
static func load(_ completion: @escaping (WKContentRuleList?) -> Void) {
|
||||
if let compiled {
|
||||
completion(compiled)
|
||||
return
|
||||
}
|
||||
// Optional chaining would skip completion when the store is absent, leaving loading forever; fail closed instead.
|
||||
guard let store = WKContentRuleListStore.default() else {
|
||||
completion(nil)
|
||||
return
|
||||
}
|
||||
store.compileContentRuleList(
|
||||
forIdentifier: networkBlockIdentifier,
|
||||
encodedContentRuleList: networkBlockRules
|
||||
) { ruleList, _ in
|
||||
DispatchQueue.main.async {
|
||||
if let ruleList {
|
||||
compiled = ruleList
|
||||
}
|
||||
completion(ruleList)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// CSP fences fetch/XHR; document-start script blocks unobservable WebSocket and service-worker APIs.
|
||||
/// Match Android; both non-configurable and non-writable prevent page replacement.
|
||||
private let networkApiBlocker = """
|
||||
(function(){
|
||||
var deny=function(){throw new TypeError('Network access is disabled')};
|
||||
try{Object.defineProperty(globalThis,'WebSocket',{value:deny,configurable:false,writable:false})}catch(_){}
|
||||
try{Object.defineProperty(Navigator.prototype,'serviceWorker',{get:function(){return undefined},configurable:false})}catch(_){}
|
||||
try{Object.defineProperty(navigator,'serviceWorker',{value:undefined,configurable:false,writable:false})}catch(_){}
|
||||
})();
|
||||
"""
|
||||
|
||||
/// Inject the same orcaBridge surface as Android before scripts, alongside the network blocker.
|
||||
/// Capture the sink so deleting window.webkit cannot break it; freeze properties against replacement.
|
||||
private let bridgeInstaller = """
|
||||
(function(){
|
||||
var sink=window.webkit.messageHandlers.orcaBridge;
|
||||
var handler=null;
|
||||
var bridge={};
|
||||
Object.defineProperty(bridge,'postMessage',{value:function(json){
|
||||
if(typeof json!=='string'){throw new TypeError('orcaBridge.postMessage expects a string')}
|
||||
sink.postMessage(json)},configurable:false,writable:false,enumerable:true});
|
||||
Object.defineProperty(bridge,'onmessage',{get:function(){return handler},
|
||||
set:function(value){handler=typeof value==='function'?value:null},configurable:false,enumerable:true});
|
||||
Object.defineProperty(bridge,'__deliver',{value:function(json){if(handler){handler({data:json})}},
|
||||
configurable:false,writable:false,enumerable:false});
|
||||
Object.defineProperty(globalThis,'orcaBridge',{value:bridge,configurable:false,writable:false,enumerable:true});
|
||||
})();
|
||||
"""
|
||||
|
||||
/// Bind payload as JS value m, never script text. A missing installer must throw to reject undelivered posts.
|
||||
private let bridgeDeliver = """
|
||||
globalThis.orcaBridge.__deliver(m)
|
||||
"""
|
||||
|
||||
private final class MobileWebShellSchemeHandler: NSObject, WKURLSchemeHandler {
|
||||
/// Read up-to-10-MiB assets off WebKit’s main-thread scheme callbacks.
|
||||
private let readQueue = DispatchQueue(label: "dev.orca.mobile-web-shell.read")
|
||||
/// Main-thread live-task set prevents stopped-task delivery’s uncatchable Objective-C exception.
|
||||
private var liveTasks: Set<ObjectIdentifier> = []
|
||||
|
||||
var sessionId: String?
|
||||
var generation: MobileWebShellGeneration?
|
||||
|
||||
func webView(_ webView: WKWebView, start urlSchemeTask: WKURLSchemeTask) {
|
||||
let key = ObjectIdentifier(urlSchemeTask)
|
||||
liveTasks.insert(key)
|
||||
guard
|
||||
let sessionId,
|
||||
let generation,
|
||||
let url = urlSchemeTask.request.url,
|
||||
let parts = MobileWebShellRequestParts(request: urlSchemeTask.request),
|
||||
let path = MobileWebShellOrigin.resolveRequestPath(parts, sessionId: sessionId),
|
||||
let asset = generation.entries[path]
|
||||
else {
|
||||
fail(urlSchemeTask, key)
|
||||
return
|
||||
}
|
||||
readQueue.async { [weak self] in
|
||||
let data = try? Data(contentsOf: asset.file)
|
||||
DispatchQueue.main.async {
|
||||
guard let self, self.liveTasks.contains(key) else { return }
|
||||
guard
|
||||
let data,
|
||||
let response = Self.makeResponse(
|
||||
url: url,
|
||||
asset: asset,
|
||||
byteCount: data.count,
|
||||
path: path
|
||||
)
|
||||
else {
|
||||
self.fail(urlSchemeTask, key)
|
||||
return
|
||||
}
|
||||
self.liveTasks.remove(key)
|
||||
urlSchemeTask.didReceive(response)
|
||||
urlSchemeTask.didReceive(data)
|
||||
urlSchemeTask.didFinish()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func webView(_ webView: WKWebView, stop urlSchemeTask: WKURLSchemeTask) {
|
||||
liveTasks.remove(ObjectIdentifier(urlSchemeTask))
|
||||
}
|
||||
|
||||
private func fail(_ urlSchemeTask: WKURLSchemeTask, _ key: ObjectIdentifier) {
|
||||
guard liveTasks.remove(key) != nil else { return }
|
||||
urlSchemeTask.didFailWithError(URLError(.resourceUnavailable))
|
||||
}
|
||||
|
||||
private static func makeResponse(
|
||||
url: URL,
|
||||
asset: MobileWebShellAsset,
|
||||
byteCount: Int,
|
||||
path: String
|
||||
) -> HTTPURLResponse? {
|
||||
HTTPURLResponse(
|
||||
url: url,
|
||||
statusCode: 200,
|
||||
httpVersion: "HTTP/1.1",
|
||||
headerFields: MobileWebShellResponseHeaders.forPath(
|
||||
path,
|
||||
contentType: asset.contentType,
|
||||
byteCount: byteCount
|
||||
)
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
/// WKUserContentController retains handlers; a weak document reference prevents a React-unmount leak.
|
||||
private final class MobileWebShellBridgeReceiver: NSObject, WKScriptMessageHandler {
|
||||
weak var document: MobileWebShellDocument?
|
||||
|
||||
func userContentController(
|
||||
_ controller: WKUserContentController,
|
||||
didReceive message: WKScriptMessage
|
||||
) {
|
||||
document?.receiveBridgeMessage(message)
|
||||
}
|
||||
}
|
||||
|
||||
/// The RN host sees this, never the page: it is the difference between a request that failed and
|
||||
/// one that never settles.
|
||||
internal final class MobileWebShellBridgeDeliveryFailedException: GenericException<String>,
|
||||
@unchecked Sendable {
|
||||
override var reason: String {
|
||||
"The mobile web shell bridge could not deliver a message: \(param)"
|
||||
}
|
||||
}
|
||||
|
||||
internal final class MobileWebShellBridgeUnavailableException: Exception, @unchecked Sendable {
|
||||
override var reason: String {
|
||||
"The mobile web shell bridge is not installed on this view"
|
||||
}
|
||||
}
|
||||
|
||||
/// Throw so a host chunking bug rejects rather than leaving its request unsettled.
|
||||
internal final class MobileWebShellBridgeMessageTooLargeException: GenericException<Int>,
|
||||
@unchecked Sendable {
|
||||
override var reason: String {
|
||||
"A bridge message of \(param) bytes exceeds the \(MobileWebShellBridge.maxMessageByteCount) byte cap"
|
||||
}
|
||||
}
|
||||
|
||||
/// Where a document's reports go: the view showing it, or the spare pool while it is parked.
|
||||
protocol MobileWebShellDocumentSink: AnyObject {
|
||||
func documentLoadState(_ payload: [String: Any])
|
||||
func documentBridgeMessage(_ json: String)
|
||||
func documentExternalNavigation(_ url: String)
|
||||
}
|
||||
|
||||
/// One WKWebView and every fence on it, apart from React. The view hosts it and lays it out.
|
||||
final class MobileWebShellDocument: NSObject, WKNavigationDelegate, WKUIDelegate {
|
||||
weak var sink: MobileWebShellDocumentSink?
|
||||
let webView: WKWebView
|
||||
|
||||
private let schemeHandler = MobileWebShellSchemeHandler()
|
||||
private let bridgeReceiver = MobileWebShellBridgeReceiver()
|
||||
private let bridgeGate = MobileWebShellBridgeGate()
|
||||
private var bridgeInstalled = false
|
||||
private var bridgeTarget = MobileWebShellBridgeTarget<WKFrameInfo>()
|
||||
private var applied: MobileWebShellAppliedProps?
|
||||
private var appliedSessionId: String? { applied?.sessionId }
|
||||
private var pendingDocumentUrl: URL?
|
||||
private var isolationReady = false
|
||||
private var isolationFailed = false
|
||||
private var destroyed = false
|
||||
private let loadState = MobileWebShellLoadStateMachine()
|
||||
private var keyboardPreparationPending = false
|
||||
private var windowObservers: [NSObjectProtocol] = []
|
||||
|
||||
override init() {
|
||||
let configuration = WKWebViewConfiguration()
|
||||
configuration.allowsInlineMediaPlayback = true
|
||||
configuration.mediaTypesRequiringUserActionForPlayback = .all
|
||||
// WebKit cannot disable DOM storage/databases; isolate with a non-persistent store, per-session origin and unmount destruction.
|
||||
configuration.websiteDataStore = .nonPersistent()
|
||||
configuration.preferences.javaScriptCanOpenWindowsAutomatically = false
|
||||
// Disabling text interaction suppresses text after keydown; page user-select handles long-press selection.
|
||||
configuration.setURLSchemeHandler(schemeHandler, forURLScheme: MobileWebShellOrigin.scheme)
|
||||
configuration.userContentController.addUserScript(Self.makeBlockerScript())
|
||||
webView = WKWebView(frame: .zero, configuration: configuration)
|
||||
super.init()
|
||||
bridgeReceiver.document = self
|
||||
webView.navigationDelegate = self
|
||||
webView.uiDelegate = self
|
||||
webView.allowsBackForwardNavigationGestures = false
|
||||
// WKWebView’s opaque white default flashes during dark-page boot; transparency exposes the shell’s themed frame.
|
||||
webView.isOpaque = false
|
||||
webView.backgroundColor = .clear
|
||||
webView.scrollView.backgroundColor = .clear
|
||||
webView.scrollView.contentInsetAdjustmentBehavior = .never
|
||||
hideKeyboardAccessoryBar(of: webView)
|
||||
ignoreKeyboardNotifications(in: webView)
|
||||
for name in [
|
||||
UIWindow.didBecomeKeyNotification, UIScene.didActivateNotification,
|
||||
UIApplication.didBecomeActiveNotification,
|
||||
UIResponder.keyboardDidHideNotification, UITextField.textDidEndEditingNotification,
|
||||
UITextView.textDidEndEditingNotification
|
||||
] {
|
||||
windowObservers.append(NotificationCenter.default.addObserver(
|
||||
forName: name, object: nil, queue: .main
|
||||
) { [weak self] _ in
|
||||
self?.loadWhenIsolated()
|
||||
})
|
||||
}
|
||||
installNetworkBlock(into: configuration.userContentController)
|
||||
}
|
||||
|
||||
deinit {
|
||||
for observer in windowObservers {
|
||||
NotificationCenter.default.removeObserver(observer)
|
||||
}
|
||||
}
|
||||
|
||||
/// Still showable: not torn down, and no terminal load failure or content-process loss.
|
||||
var isUsable: Bool { !destroyed && !loadState.isTerminal }
|
||||
|
||||
/// The spare pool's teardown; the content process goes with the last reference.
|
||||
func destroy() {
|
||||
destroyed = true
|
||||
sink = nil
|
||||
clearBridgeTarget()
|
||||
pendingDocumentUrl = nil
|
||||
webView.stopLoading()
|
||||
webView.removeFromSuperview()
|
||||
}
|
||||
|
||||
/// Apply unordered props together; identical triples do not retry (remount required).
|
||||
/// Include bridgeEnabled: document-start scripts require a reload to change.
|
||||
func apply(generationDirectory: String, sessionId: String, bridgeEnabled: Bool) {
|
||||
let next = MobileWebShellAppliedProps(
|
||||
generationDirectory: generationDirectory,
|
||||
sessionId: sessionId,
|
||||
bridgeEnabled: bridgeEnabled
|
||||
)
|
||||
guard applied?.matches(next) != true else { return }
|
||||
applied = next
|
||||
clearBridgeTarget()
|
||||
loadState.reset()
|
||||
pendingDocumentUrl = nil
|
||||
webView.stopLoading()
|
||||
webView.isHidden = false
|
||||
emit(loadState.started())
|
||||
guard
|
||||
MobileWebShellOrigin.isValidSessionId(sessionId),
|
||||
let documentUrl = MobileWebShellOrigin.documentUrl(sessionId: sessionId)
|
||||
else {
|
||||
// The private origin is the isolation primitive; a malformed session id leaves us without one.
|
||||
failPropUpdate(.isolationUnavailable)
|
||||
return
|
||||
}
|
||||
guard
|
||||
let generation = try? MobileWebShellGeneration.load(directoryPath: generationDirectory)
|
||||
else {
|
||||
failPropUpdate(.generationUnreadable)
|
||||
return
|
||||
}
|
||||
schemeHandler.sessionId = sessionId
|
||||
schemeHandler.generation = generation
|
||||
applyBridgeInstallation(bridgeEnabled)
|
||||
if isolationFailed {
|
||||
failPropUpdate(.isolationUnavailable)
|
||||
return
|
||||
}
|
||||
pendingDocumentUrl = documentUrl
|
||||
loadWhenIsolated()
|
||||
}
|
||||
|
||||
/// Retire the old visible generation even when the replacement fails.
|
||||
private func failPropUpdate(_ reason: MobileWebShellFailureReason) {
|
||||
clearBridgeTarget()
|
||||
schemeHandler.sessionId = nil
|
||||
schemeHandler.generation = nil
|
||||
pendingDocumentUrl = nil
|
||||
webView.stopLoading()
|
||||
webView.isHidden = true
|
||||
emit(loadState.failed(reason))
|
||||
}
|
||||
|
||||
/// removeAllUserScripts is WebKit’s only removal API, so disabling the bridge must reinstall the blocker.
|
||||
private static func makeBlockerScript() -> WKUserScript {
|
||||
WKUserScript(
|
||||
source: networkApiBlocker,
|
||||
injectionTime: .atDocumentStart,
|
||||
forMainFrameOnly: false
|
||||
)
|
||||
}
|
||||
|
||||
/// Nothing here runs while the prop stays false, which is what keeps Phase B byte-identical.
|
||||
private func applyBridgeInstallation(_ bridgeEnabled: Bool) {
|
||||
guard bridgeEnabled != bridgeInstalled else { return }
|
||||
clearBridgeTarget()
|
||||
let controller = webView.configuration.userContentController
|
||||
if bridgeEnabled {
|
||||
controller.add(bridgeReceiver, name: MobileWebShellBridge.handlerName)
|
||||
controller.addUserScript(
|
||||
WKUserScript(
|
||||
source: bridgeInstaller,
|
||||
injectionTime: .atDocumentStart,
|
||||
// Main-frame injection is convenience; accepts must still refuse subframes that reach the handler.
|
||||
forMainFrameOnly: true
|
||||
)
|
||||
)
|
||||
} else {
|
||||
controller.removeScriptMessageHandler(forName: MobileWebShellBridge.handlerName)
|
||||
controller.removeAllUserScripts()
|
||||
controller.addUserScript(Self.makeBlockerScript())
|
||||
}
|
||||
bridgeInstalled = bridgeEnabled
|
||||
}
|
||||
|
||||
/// Use the loaded session, not latest props; the replaced same-origin document survives until commit.
|
||||
fileprivate func receiveBridgeMessage(_ message: WKScriptMessage) {
|
||||
guard bridgeInstalled, let json = message.body as? String else { return }
|
||||
let origin = message.frameInfo.securityOrigin
|
||||
let source = MobileWebShellBridgeSource(
|
||||
isOurWebView: message.webView === webView,
|
||||
isMainFrame: message.frameInfo.isMainFrame,
|
||||
hasCommittedDocument: loadState.hasCommittedDocument,
|
||||
originProtocol: origin.`protocol`,
|
||||
originHost: origin.host
|
||||
)
|
||||
guard
|
||||
MobileWebShellBridge.accepts(source, sessionId: appliedSessionId ?? ""),
|
||||
bridgeGate.accepts(byteCount: json.utf8.count)
|
||||
else { return }
|
||||
bridgeTarget.arm(frame: message.frameInfo, originHost: origin.host)
|
||||
sink?.documentBridgeMessage(json)
|
||||
}
|
||||
|
||||
/// Anything that ends the document the page spoke from ends the only target native has.
|
||||
private func clearBridgeTarget() {
|
||||
bridgeTarget.clear()
|
||||
}
|
||||
|
||||
/// Reject posts without a live committed frame that spoke; resolve only after page execution so host requests cannot hang.
|
||||
func postBridgeMessage(_ json: String, promise: Promise) throws {
|
||||
guard
|
||||
MobileWebShellBridge.canPost(
|
||||
toFrameOriginHost: bridgeTarget.originHost,
|
||||
sessionId: appliedSessionId ?? "",
|
||||
hasCommittedDocument: loadState.hasCommittedDocument
|
||||
),
|
||||
let frame = bridgeTarget.frame
|
||||
else {
|
||||
throw MobileWebShellBridgeUnavailableException()
|
||||
}
|
||||
let byteCount = json.utf8.count
|
||||
guard MobileWebShellBridge.acceptsByteCount(byteCount) else {
|
||||
throw MobileWebShellBridgeMessageTooLargeException(byteCount)
|
||||
}
|
||||
// Use the two in: labels plus completionHandler to select the callback overload and reply to the frame that spoke.
|
||||
webView.callAsyncJavaScript(
|
||||
bridgeDeliver,
|
||||
arguments: ["m": json],
|
||||
in: frame,
|
||||
in: .page
|
||||
) { result in
|
||||
switch result {
|
||||
case .success:
|
||||
promise.resolve()
|
||||
case .failure(let error):
|
||||
promise.reject(MobileWebShellBridgeDeliveryFailedException(error.localizedDescription))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A frame from the shell itself, to the frame that spoke; nothing waits on its delivery.
|
||||
func postHostFrame(_ json: String) {
|
||||
guard let frame = bridgeTarget.frame else { return }
|
||||
webView.callAsyncJavaScript(bridgeDeliver, arguments: ["m": json], in: frame, in: .page) { _ in }
|
||||
}
|
||||
|
||||
private func installNetworkBlock(into controller: WKUserContentController) {
|
||||
NetworkBlockRuleList.load { [weak self] ruleList in
|
||||
guard let self else { return }
|
||||
guard let ruleList else {
|
||||
self.isolationFailed = true
|
||||
self.pendingDocumentUrl = nil
|
||||
// Rule compilation can finish after refusal; the state machine prevents a second terminal reason.
|
||||
if self.appliedSessionId != nil {
|
||||
self.failPropUpdate(.isolationUnavailable)
|
||||
}
|
||||
return
|
||||
}
|
||||
controller.add(ruleList)
|
||||
self.isolationReady = true
|
||||
self.loadWhenIsolated()
|
||||
}
|
||||
}
|
||||
|
||||
/// Load only in a foreground-active key window; the view calls this again when it moves to one.
|
||||
func loadWhenIsolated() {
|
||||
guard isolationReady, pendingDocumentUrl != nil, !keyboardPreparationPending,
|
||||
let window = webView.window, window.isKeyWindow,
|
||||
window.windowScene?.activationState == .foregroundActive else { return }
|
||||
keyboardPreparationPending = true
|
||||
DispatchQueue.main.async { [weak self, weak window] in
|
||||
guard let self else { return }
|
||||
guard let window, self.webView.window === window, window.isKeyWindow,
|
||||
window.windowScene?.activationState == .foregroundActive else {
|
||||
self.keyboardPreparationPending = false
|
||||
self.loadWhenIsolated()
|
||||
return
|
||||
}
|
||||
let delay: TimeInterval
|
||||
switch MobileWebShellKeyboardWarmup.prepare(in: window) {
|
||||
case .ready(let remainingDelay):
|
||||
delay = remainingDelay
|
||||
case .waitingForTextInput:
|
||||
DispatchQueue.main.asyncAfter(deadline: .now() + 0.25) { [weak self] in
|
||||
guard let self else { return }
|
||||
self.keyboardPreparationPending = false
|
||||
self.loadWhenIsolated()
|
||||
}
|
||||
return
|
||||
case .failed:
|
||||
self.keyboardPreparationPending = false
|
||||
self.failPropUpdate(.documentLoadFailed)
|
||||
return
|
||||
}
|
||||
DispatchQueue.main.asyncAfter(deadline: .now() + delay) { [weak self, weak window] in
|
||||
guard let self else { return }
|
||||
self.keyboardPreparationPending = false
|
||||
guard let window, self.webView.window === window, window.isKeyWindow,
|
||||
window.windowScene?.activationState == .foregroundActive else {
|
||||
self.loadWhenIsolated()
|
||||
return
|
||||
}
|
||||
guard self.isolationReady, let url = self.pendingDocumentUrl else { return }
|
||||
self.pendingDocumentUrl = nil
|
||||
self.loadState.shellLoadStarted()
|
||||
self.webView.load(URLRequest(url: url, cachePolicy: .reloadIgnoringLocalCacheData))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private func emit(_ emission: MobileWebShellLoadEmission?) {
|
||||
guard let emission else { return }
|
||||
sink?.documentLoadState(emission.payload)
|
||||
}
|
||||
|
||||
private func reportDocumentFailure() {
|
||||
clearBridgeTarget()
|
||||
emit(loadState.failed(.documentLoadFailed))
|
||||
}
|
||||
|
||||
/// A cancelled navigation is our own doing, not the document's; see MobileWebShellNavigationError.
|
||||
private func reportNavigationFailure(_ error: Error) {
|
||||
let error = error as NSError
|
||||
guard !MobileWebShellNavigationError.isIgnorable(domain: error.domain, code: error.code) else {
|
||||
return
|
||||
}
|
||||
reportDocumentFailure()
|
||||
}
|
||||
|
||||
private func isDocumentUrl(_ url: URL?) -> Bool {
|
||||
guard let url, let parts = MobileWebShellRequestParts(url: url) else { return false }
|
||||
return MobileWebShellOrigin.resolveRequestPath(parts, sessionId: appliedSessionId ?? "") == "/"
|
||||
}
|
||||
|
||||
func webView(
|
||||
_ webView: WKWebView,
|
||||
decidePolicyFor navigationAction: WKNavigationAction,
|
||||
decisionHandler: @escaping (WKNavigationActionPolicy) -> Void
|
||||
) {
|
||||
var isDownload = false
|
||||
if #available(iOS 14.5, *) {
|
||||
isDownload = navigationAction.shouldPerformDownload
|
||||
}
|
||||
let isMainFrame = navigationAction.targetFrame?.isMainFrame == true
|
||||
// linkActivated gates only opener offers; gesture-free subframe top navigation must never authorize a load.
|
||||
let verdict = MobileWebShellNavigationPolicy.verdict(
|
||||
url: navigationAction.request.url?.absoluteString,
|
||||
isMainFrame: isMainFrame,
|
||||
isDocumentUrl: isDocumentUrl(navigationAction.request.url),
|
||||
isShellLoad: loadState.isShellLoad,
|
||||
hasGesture: navigationAction.navigationType == .linkActivated,
|
||||
isDownload: isDownload
|
||||
)
|
||||
if case let .cancelAndOffer(url) = verdict {
|
||||
sink?.documentExternalNavigation(url)
|
||||
}
|
||||
if verdict == .allow && isMainFrame {
|
||||
// Spend before handing back the decision so another main-frame action cannot reuse the allowance.
|
||||
loadState.shellLoadConsumed()
|
||||
}
|
||||
decisionHandler(verdict == .allow ? .allow : .cancel)
|
||||
}
|
||||
|
||||
func webView(
|
||||
_ webView: WKWebView,
|
||||
decidePolicyFor navigationResponse: WKNavigationResponse,
|
||||
decisionHandler: @escaping (WKNavigationResponsePolicy) -> Void
|
||||
) {
|
||||
// Only srcdoc subframes pass the action policy; refusing one must not fail the shell document.
|
||||
guard navigationResponse.isForMainFrame else {
|
||||
let url = navigationResponse.response.url?.absoluteString
|
||||
decisionHandler(url == MobileWebShellNavigationPolicy.inlineDocumentUrl ? .allow : .cancel)
|
||||
return
|
||||
}
|
||||
let allowed = navigationResponse.canShowMIMEType &&
|
||||
isDocumentUrl(navigationResponse.response.url)
|
||||
if !allowed {
|
||||
reportDocumentFailure()
|
||||
}
|
||||
decisionHandler(allowed ? .allow : .cancel)
|
||||
}
|
||||
|
||||
func webView(_ webView: WKWebView, didStartProvisionalNavigation navigation: WKNavigation!) {
|
||||
// Clear replies and acceptance when the document is replaced; its successor must commit and send ready.
|
||||
clearBridgeTarget()
|
||||
loadState.documentEnded()
|
||||
guard appliedSessionId != nil else { return }
|
||||
emit(loadState.started())
|
||||
}
|
||||
|
||||
/// Arm at commit, before document-start messages and didFinish.
|
||||
func webView(_ webView: WKWebView, didCommit navigation: WKNavigation!) {
|
||||
guard isDocumentUrl(webView.url) else { return }
|
||||
// Commit rearms acceptance, so clear the replaced frame here as well as at provisional start.
|
||||
clearBridgeTarget()
|
||||
loadState.committed()
|
||||
}
|
||||
|
||||
/// history.replaceState changes the path before finish; finished() uses commit state instead of URL equality.
|
||||
func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
|
||||
MobileWebShellWarmUp.release()
|
||||
emit(loadState.finished())
|
||||
}
|
||||
|
||||
func webView(
|
||||
_ webView: WKWebView,
|
||||
didFailProvisionalNavigation navigation: WKNavigation!,
|
||||
withError error: Error
|
||||
) {
|
||||
MobileWebShellWarmUp.release()
|
||||
reportNavigationFailure(error)
|
||||
}
|
||||
|
||||
func webView(_ webView: WKWebView, didFail navigation: WKNavigation!, withError error: Error) {
|
||||
MobileWebShellWarmUp.release()
|
||||
reportNavigationFailure(error)
|
||||
}
|
||||
|
||||
/// Report renderer death; memory pressure/provider updates look alike, so the caller owns retry policy.
|
||||
func webViewWebContentProcessDidTerminate(_ webView: WKWebView) {
|
||||
MobileWebShellWarmUp.release()
|
||||
clearBridgeTarget()
|
||||
// Jetsam takes WebContent while Orca is backgrounded; the report can arrive as the app resumes, before it is active.
|
||||
let background = webView.window == nil || UIApplication.shared.applicationState != .active
|
||||
emit(loadState.failed(.renderProcessGone, background: background))
|
||||
}
|
||||
|
||||
func webView(
|
||||
_ webView: WKWebView,
|
||||
createWebViewWith configuration: WKWebViewConfiguration,
|
||||
for navigationAction: WKNavigationAction,
|
||||
windowFeatures: WKWindowFeatures
|
||||
) -> WKWebView? {
|
||||
nil
|
||||
}
|
||||
}
|
||||
@@ -28,7 +28,7 @@ struct MobileWebShellLoadEmission: Equatable {
|
||||
|
||||
/// Failure is terminal and duplicate reports are dropped: late error-document/rule-list callbacks must never restore ready.
|
||||
final class MobileWebShellLoadStateMachine {
|
||||
private var isTerminal = false
|
||||
private(set) var isTerminal = false
|
||||
private var last: MobileWebShellLoadEmission?
|
||||
|
||||
/// Accept messages only after the current props’ document commits; the replaced same-origin document can still speak before then.
|
||||
|
||||
@@ -0,0 +1,150 @@
|
||||
import UIKit
|
||||
import WebKit
|
||||
|
||||
/// More than 3 GiB can only come from a phone with 4 GB or more; those report about 3.5 to 3.9 GiB.
|
||||
private let minimumPhysicalMemory: UInt64 = 3 << 30
|
||||
|
||||
/// A claim is adopted on the claiming screen's first commit; this only bounds a screen that never mounts.
|
||||
private let claimExpirySeconds: TimeInterval = 10
|
||||
|
||||
/// A booted document waiting for a screen. It keeps what the page reported, and the page's ready, for
|
||||
/// the view that adopts it: a parked page stops asking for init, so its ready is answered from here.
|
||||
final class MobileWebShellSpare: MobileWebShellDocumentSink {
|
||||
let document = MobileWebShellDocument()
|
||||
let directory: String
|
||||
let sessionId: String
|
||||
private var loadStates: [[String: Any]] = []
|
||||
private var ready: String?
|
||||
|
||||
init(directory: String, sessionId: String) {
|
||||
self.directory = directory
|
||||
self.sessionId = sessionId
|
||||
document.sink = self
|
||||
}
|
||||
|
||||
func documentLoadState(_ payload: [String: Any]) {
|
||||
loadStates.append(payload)
|
||||
if payload["state"] as? String == "failed" {
|
||||
MobileWebShellSparePool.shared.discard(self)
|
||||
}
|
||||
}
|
||||
|
||||
/// Before init a page only sends ready, from its first document or one it reloaded.
|
||||
func documentBridgeMessage(_ json: String) {
|
||||
ready = json
|
||||
document.postHostFrame(MobileWebShellBridge.parkedFrame)
|
||||
}
|
||||
|
||||
/// A parked page has no screen to have been tapped on.
|
||||
func documentExternalNavigation(_ url: String) {}
|
||||
|
||||
/// The adopting view sees what a fresh document would have reported, ready last.
|
||||
func handOver(to sink: MobileWebShellDocumentSink) {
|
||||
document.sink = sink
|
||||
loadStates.forEach(sink.documentLoadState)
|
||||
if let ready {
|
||||
sink.documentBridgeMessage(ready)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// At most one document booted ahead of its screen, only while no page document is shown. Main thread only.
|
||||
/// Parked in the key window at alpha 0: WebKit suspends an off-window view (0.5–1.3 s to paint after 30 s, vs 0.1 s).
|
||||
final class MobileWebShellSparePool {
|
||||
static let shared = MobileWebShellSparePool()
|
||||
|
||||
private var parked: MobileWebShellSpare?
|
||||
private var claimed: MobileWebShellSpare?
|
||||
private let shown = NSHashTable<MobileWebShellDocument>.weakObjects()
|
||||
|
||||
/// Whether a spare for `directory` is parked after the call; never on a small phone, inactive app or shown page.
|
||||
func prepare(directory: String, sessionId: String) -> Bool {
|
||||
guard
|
||||
ProcessInfo.processInfo.physicalMemory > minimumPhysicalMemory,
|
||||
UIApplication.shared.applicationState == .active,
|
||||
shown.allObjects.isEmpty,
|
||||
let window = keyWindow()
|
||||
else { return false }
|
||||
if let parked, parked.directory == directory, parked.document.isUsable {
|
||||
return true
|
||||
}
|
||||
// A claim no view adopted was abandoned; it must not outlive the spare that replaces it.
|
||||
discardAll()
|
||||
let spare = MobileWebShellSpare(directory: directory, sessionId: sessionId)
|
||||
let webView = spare.document.webView
|
||||
webView.alpha = 0
|
||||
webView.isUserInteractionEnabled = false
|
||||
webView.accessibilityElementsHidden = true
|
||||
webView.frame = window.bounds
|
||||
webView.autoresizingMask = [.flexibleWidth, .flexibleHeight]
|
||||
window.insertSubview(webView, at: 0)
|
||||
parked = spare
|
||||
spare.document.apply(generationDirectory: directory, sessionId: sessionId, bridgeEnabled: true)
|
||||
// A load that failed at once has already discarded it.
|
||||
return parked === spare
|
||||
}
|
||||
|
||||
/// The parked spare's session id for a screen opening `directory`, handed out once.
|
||||
func claim(directory: String) -> String? {
|
||||
guard let spare = parked, spare.directory == directory, spare.document.isUsable else {
|
||||
return nil
|
||||
}
|
||||
parked = nil
|
||||
claimed = spare
|
||||
DispatchQueue.main.asyncAfter(deadline: .now() + claimExpirySeconds) { [weak self, weak spare] in
|
||||
if let self, let spare, self.claimed === spare {
|
||||
self.discard(spare)
|
||||
}
|
||||
}
|
||||
return spare.sessionId
|
||||
}
|
||||
|
||||
/// The claimed spare when `sessionId` names it, else a fresh document, which leaves no room for a spare.
|
||||
func document(for sessionId: String, sink: MobileWebShellDocumentSink) -> MobileWebShellDocument {
|
||||
let document: MobileWebShellDocument
|
||||
if let spare = claimed, spare.sessionId == sessionId, spare.document.isUsable {
|
||||
claimed = nil
|
||||
document = spare.document
|
||||
let webView = document.webView
|
||||
webView.removeFromSuperview()
|
||||
webView.alpha = 1
|
||||
webView.isUserInteractionEnabled = true
|
||||
webView.accessibilityElementsHidden = false
|
||||
webView.autoresizingMask = []
|
||||
spare.handOver(to: sink)
|
||||
} else {
|
||||
discardAll()
|
||||
document = MobileWebShellDocument()
|
||||
document.sink = sink
|
||||
}
|
||||
shown.add(document)
|
||||
return document
|
||||
}
|
||||
|
||||
/// Memory pressure, the app leaving the foreground, files going away, or Home without a claim.
|
||||
func discardAll() {
|
||||
for spare in [parked, claimed].compactMap({ $0 }) {
|
||||
spare.document.destroy()
|
||||
}
|
||||
parked = nil
|
||||
claimed = nil
|
||||
}
|
||||
|
||||
fileprivate func discard(_ spare: MobileWebShellSpare) {
|
||||
if parked === spare {
|
||||
parked = nil
|
||||
} else if claimed === spare {
|
||||
claimed = nil
|
||||
} else {
|
||||
return
|
||||
}
|
||||
spare.document.destroy()
|
||||
}
|
||||
|
||||
private func keyWindow() -> UIWindow? {
|
||||
UIApplication.shared.connectedScenes
|
||||
.compactMap { $0 as? UIWindowScene }
|
||||
.flatMap(\.windows)
|
||||
.first(where: \.isKeyWindow)
|
||||
}
|
||||
}
|
||||
@@ -1,190 +1,8 @@
|
||||
import ExpoModulesCore
|
||||
import WebKit
|
||||
|
||||
private let networkBlockIdentifier = "dev.orca.mobile-web-shell.network-block-v1"
|
||||
|
||||
/// Block http(s)/ws(s) beneath CSP; compilation failure is terminal and must load nothing.
|
||||
private let networkBlockRules = """
|
||||
[
|
||||
{ "trigger": { "url-filter": "^https?://" }, "action": { "type": "block" } },
|
||||
{ "trigger": { "url-filter": "^wss?://" }, "action": { "type": "block" } }
|
||||
]
|
||||
"""
|
||||
|
||||
/// Compiled once per launch and shared by every view, so later mounts load without waiting; main thread only.
|
||||
private enum NetworkBlockRuleList {
|
||||
private static var compiled: WKContentRuleList?
|
||||
|
||||
/// Synchronous once compiled in this process; nil means isolation is unavailable.
|
||||
static func load(_ completion: @escaping (WKContentRuleList?) -> Void) {
|
||||
if let compiled {
|
||||
completion(compiled)
|
||||
return
|
||||
}
|
||||
// Optional chaining would skip completion when the store is absent, leaving loading forever; fail closed instead.
|
||||
guard let store = WKContentRuleListStore.default() else {
|
||||
completion(nil)
|
||||
return
|
||||
}
|
||||
store.compileContentRuleList(
|
||||
forIdentifier: networkBlockIdentifier,
|
||||
encodedContentRuleList: networkBlockRules
|
||||
) { ruleList, _ in
|
||||
DispatchQueue.main.async {
|
||||
if let ruleList {
|
||||
compiled = ruleList
|
||||
}
|
||||
completion(ruleList)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// CSP fences fetch/XHR; document-start script blocks unobservable WebSocket and service-worker APIs.
|
||||
/// Match Android; both non-configurable and non-writable prevent page replacement.
|
||||
private let networkApiBlocker = """
|
||||
(function(){
|
||||
var deny=function(){throw new TypeError('Network access is disabled')};
|
||||
try{Object.defineProperty(globalThis,'WebSocket',{value:deny,configurable:false,writable:false})}catch(_){}
|
||||
try{Object.defineProperty(Navigator.prototype,'serviceWorker',{get:function(){return undefined},configurable:false})}catch(_){}
|
||||
try{Object.defineProperty(navigator,'serviceWorker',{value:undefined,configurable:false,writable:false})}catch(_){}
|
||||
})();
|
||||
"""
|
||||
|
||||
/// Inject the same orcaBridge surface as Android before scripts, alongside the network blocker.
|
||||
/// Capture the sink so deleting window.webkit cannot break it; freeze properties against replacement.
|
||||
private let bridgeInstaller = """
|
||||
(function(){
|
||||
var sink=window.webkit.messageHandlers.orcaBridge;
|
||||
var handler=null;
|
||||
var bridge={};
|
||||
Object.defineProperty(bridge,'postMessage',{value:function(json){
|
||||
if(typeof json!=='string'){throw new TypeError('orcaBridge.postMessage expects a string')}
|
||||
sink.postMessage(json)},configurable:false,writable:false,enumerable:true});
|
||||
Object.defineProperty(bridge,'onmessage',{get:function(){return handler},
|
||||
set:function(value){handler=typeof value==='function'?value:null},configurable:false,enumerable:true});
|
||||
Object.defineProperty(bridge,'__deliver',{value:function(json){if(handler){handler({data:json})}},
|
||||
configurable:false,writable:false,enumerable:false});
|
||||
Object.defineProperty(globalThis,'orcaBridge',{value:bridge,configurable:false,writable:false,enumerable:true});
|
||||
})();
|
||||
"""
|
||||
|
||||
/// Bind payload as JS value m, never script text. A missing installer must throw to reject undelivered posts.
|
||||
private let bridgeDeliver = """
|
||||
globalThis.orcaBridge.__deliver(m)
|
||||
"""
|
||||
|
||||
private final class MobileWebShellSchemeHandler: NSObject, WKURLSchemeHandler {
|
||||
/// Read up-to-10-MiB assets off WebKit’s main-thread scheme callbacks.
|
||||
private let readQueue = DispatchQueue(label: "dev.orca.mobile-web-shell.read")
|
||||
/// Main-thread live-task set prevents stopped-task delivery’s uncatchable Objective-C exception.
|
||||
private var liveTasks: Set<ObjectIdentifier> = []
|
||||
|
||||
var sessionId: String?
|
||||
var generation: MobileWebShellGeneration?
|
||||
|
||||
func webView(_ webView: WKWebView, start urlSchemeTask: WKURLSchemeTask) {
|
||||
let key = ObjectIdentifier(urlSchemeTask)
|
||||
liveTasks.insert(key)
|
||||
guard
|
||||
let sessionId,
|
||||
let generation,
|
||||
let url = urlSchemeTask.request.url,
|
||||
let parts = MobileWebShellRequestParts(request: urlSchemeTask.request),
|
||||
let path = MobileWebShellOrigin.resolveRequestPath(parts, sessionId: sessionId),
|
||||
let asset = generation.entries[path]
|
||||
else {
|
||||
fail(urlSchemeTask, key)
|
||||
return
|
||||
}
|
||||
readQueue.async { [weak self] in
|
||||
let data = try? Data(contentsOf: asset.file)
|
||||
DispatchQueue.main.async {
|
||||
guard let self, self.liveTasks.contains(key) else { return }
|
||||
guard
|
||||
let data,
|
||||
let response = Self.makeResponse(
|
||||
url: url,
|
||||
asset: asset,
|
||||
byteCount: data.count,
|
||||
path: path
|
||||
)
|
||||
else {
|
||||
self.fail(urlSchemeTask, key)
|
||||
return
|
||||
}
|
||||
self.liveTasks.remove(key)
|
||||
urlSchemeTask.didReceive(response)
|
||||
urlSchemeTask.didReceive(data)
|
||||
urlSchemeTask.didFinish()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func webView(_ webView: WKWebView, stop urlSchemeTask: WKURLSchemeTask) {
|
||||
liveTasks.remove(ObjectIdentifier(urlSchemeTask))
|
||||
}
|
||||
|
||||
private func fail(_ urlSchemeTask: WKURLSchemeTask, _ key: ObjectIdentifier) {
|
||||
guard liveTasks.remove(key) != nil else { return }
|
||||
urlSchemeTask.didFailWithError(URLError(.resourceUnavailable))
|
||||
}
|
||||
|
||||
private static func makeResponse(
|
||||
url: URL,
|
||||
asset: MobileWebShellAsset,
|
||||
byteCount: Int,
|
||||
path: String
|
||||
) -> HTTPURLResponse? {
|
||||
HTTPURLResponse(
|
||||
url: url,
|
||||
statusCode: 200,
|
||||
httpVersion: "HTTP/1.1",
|
||||
headerFields: MobileWebShellResponseHeaders.forPath(
|
||||
path,
|
||||
contentType: asset.contentType,
|
||||
byteCount: byteCount
|
||||
)
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
/// WKUserContentController retains handlers; a weak view reference prevents a React-unmount leak.
|
||||
private final class MobileWebShellBridgeReceiver: NSObject, WKScriptMessageHandler {
|
||||
weak var view: OrcaMobileWebShellView?
|
||||
|
||||
func userContentController(
|
||||
_ controller: WKUserContentController,
|
||||
didReceive message: WKScriptMessage
|
||||
) {
|
||||
view?.receiveBridgeMessage(message)
|
||||
}
|
||||
}
|
||||
|
||||
/// The RN host sees this, never the page: it is the difference between a request that failed and
|
||||
/// one that never settles.
|
||||
internal final class MobileWebShellBridgeDeliveryFailedException: GenericException<String>,
|
||||
@unchecked Sendable {
|
||||
override var reason: String {
|
||||
"The mobile web shell bridge could not deliver a message: \(param)"
|
||||
}
|
||||
}
|
||||
|
||||
internal final class MobileWebShellBridgeUnavailableException: Exception, @unchecked Sendable {
|
||||
override var reason: String {
|
||||
"The mobile web shell bridge is not installed on this view"
|
||||
}
|
||||
}
|
||||
|
||||
/// Throw so a host chunking bug rejects rather than leaving its request unsettled.
|
||||
internal final class MobileWebShellBridgeMessageTooLargeException: GenericException<Int>,
|
||||
@unchecked Sendable {
|
||||
override var reason: String {
|
||||
"A bridge message of \(param) bytes exceeds the \(MobileWebShellBridge.maxMessageByteCount) byte cap"
|
||||
}
|
||||
}
|
||||
|
||||
final class OrcaMobileWebShellView: ExpoView, WKNavigationDelegate, WKUIDelegate,
|
||||
/// React Native's handle on one document: it lays the WebView out and owns the back-edge swipe.
|
||||
final class OrcaMobileWebShellView: ExpoView, MobileWebShellDocumentSink,
|
||||
UIGestureRecognizerDelegate {
|
||||
let onLoadState = EventDispatcher()
|
||||
let onBridgeMessage = EventDispatcher()
|
||||
@@ -193,58 +11,28 @@ final class OrcaMobileWebShellView: ExpoView, WKNavigationDelegate, WKUIDelegate
|
||||
|
||||
// The page's own Back: the stack's swipe is off while the page claims Back, and a strip overlay would eat taps.
|
||||
private let backEdgePan = UIPanGestureRecognizer()
|
||||
private let schemeHandler = MobileWebShellSchemeHandler()
|
||||
private let bridgeReceiver = MobileWebShellBridgeReceiver()
|
||||
private let bridgeGate = MobileWebShellBridgeGate()
|
||||
private var bridgeEnabled = false
|
||||
private var bridgeInstalled = false
|
||||
private var bridgeTarget = MobileWebShellBridgeTarget<WKFrameInfo>()
|
||||
private var webView: WKWebView!
|
||||
/// Taken on the first prop commit, not in init: the session id says whether a spare was booted for it.
|
||||
private var document: MobileWebShellDocument?
|
||||
private var generationDirectory = ""
|
||||
private var sessionId = ""
|
||||
private var applied: MobileWebShellAppliedProps?
|
||||
private var appliedSessionId: String? { applied?.sessionId }
|
||||
private var pendingDocumentUrl: URL?
|
||||
private var isolationReady = false
|
||||
private var isolationFailed = false
|
||||
private let loadState = MobileWebShellLoadStateMachine()
|
||||
private var keyboardPreparationPending = false
|
||||
private var windowObservers: [NSObjectProtocol] = []
|
||||
private var bridgeEnabled = false
|
||||
|
||||
override func didMoveToWindow() {
|
||||
super.didMoveToWindow()
|
||||
loadWhenIsolated()
|
||||
}
|
||||
|
||||
deinit {
|
||||
for observer in windowObservers {
|
||||
NotificationCenter.default.removeObserver(observer)
|
||||
}
|
||||
document?.loadWhenIsolated()
|
||||
}
|
||||
|
||||
required init(appContext: AppContext? = nil) {
|
||||
super.init(appContext: appContext)
|
||||
let configuration = WKWebViewConfiguration()
|
||||
configuration.allowsInlineMediaPlayback = true
|
||||
configuration.mediaTypesRequiringUserActionForPlayback = .all
|
||||
// WebKit cannot disable DOM storage/databases; isolate with a non-persistent store, per-session origin and unmount destruction.
|
||||
configuration.websiteDataStore = .nonPersistent()
|
||||
configuration.preferences.javaScriptCanOpenWindowsAutomatically = false
|
||||
// Disabling text interaction suppresses text after keydown; page user-select handles long-press selection.
|
||||
configuration.setURLSchemeHandler(schemeHandler, forURLScheme: MobileWebShellOrigin.scheme)
|
||||
configuration.userContentController.addUserScript(Self.makeBlockerScript())
|
||||
bridgeReceiver.view = self
|
||||
webView = WKWebView(frame: bounds, configuration: configuration)
|
||||
webView.navigationDelegate = self
|
||||
webView.uiDelegate = self
|
||||
webView.allowsBackForwardNavigationGestures = false
|
||||
// WKWebView’s opaque white default flashes during dark-page boot; transparency exposes the shell’s themed frame.
|
||||
webView.isOpaque = false
|
||||
webView.backgroundColor = .clear
|
||||
webView.scrollView.backgroundColor = .clear
|
||||
webView.scrollView.contentInsetAdjustmentBehavior = .never
|
||||
hideKeyboardAccessoryBar(of: webView)
|
||||
ignoreKeyboardNotifications(in: webView)
|
||||
backEdgePan.isEnabled = false
|
||||
backEdgePan.addTarget(self, action: #selector(handleBackEdgePan(_:)))
|
||||
backEdgePan.delegate = self
|
||||
addGestureRecognizer(backEdgePan)
|
||||
}
|
||||
|
||||
private func hostDocument() -> MobileWebShellDocument {
|
||||
let document = MobileWebShellSparePool.shared.document(for: sessionId, sink: self)
|
||||
let webView = document.webView
|
||||
webView.translatesAutoresizingMaskIntoConstraints = false
|
||||
addSubview(webView)
|
||||
NSLayoutConstraint.activate([
|
||||
@@ -253,24 +41,8 @@ final class OrcaMobileWebShellView: ExpoView, WKNavigationDelegate, WKUIDelegate
|
||||
webView.leadingAnchor.constraint(equalTo: leadingAnchor),
|
||||
webView.trailingAnchor.constraint(equalTo: trailingAnchor)
|
||||
])
|
||||
for name in [
|
||||
UIWindow.didBecomeKeyNotification, UIScene.didActivateNotification,
|
||||
UIApplication.didBecomeActiveNotification,
|
||||
UIResponder.keyboardDidHideNotification, UITextField.textDidEndEditingNotification,
|
||||
UITextView.textDidEndEditingNotification
|
||||
] {
|
||||
windowObservers.append(NotificationCenter.default.addObserver(
|
||||
forName: name, object: nil, queue: .main
|
||||
) { [weak self] _ in
|
||||
self?.loadWhenIsolated()
|
||||
})
|
||||
}
|
||||
installNetworkBlock(into: configuration.userContentController)
|
||||
backEdgePan.isEnabled = false
|
||||
backEdgePan.addTarget(self, action: #selector(handleBackEdgePan(_:)))
|
||||
backEdgePan.delegate = self
|
||||
addGestureRecognizer(backEdgePan)
|
||||
webView.scrollView.panGestureRecognizer.require(toFail: backEdgePan)
|
||||
return document
|
||||
}
|
||||
|
||||
func setBackEdgeSwipe(_ value: Bool) {
|
||||
@@ -310,332 +82,30 @@ final class OrcaMobileWebShellView: ExpoView, WKNavigationDelegate, WKUIDelegate
|
||||
bridgeEnabled = value
|
||||
}
|
||||
|
||||
/// Apply unordered props together; identical triples do not retry (remount required).
|
||||
/// Include bridgeEnabled: document-start scripts require a reload to change.
|
||||
func propsDidUpdate() {
|
||||
let next = MobileWebShellAppliedProps(
|
||||
let document = self.document ?? hostDocument()
|
||||
self.document = document
|
||||
document.apply(
|
||||
generationDirectory: generationDirectory,
|
||||
sessionId: sessionId,
|
||||
bridgeEnabled: bridgeEnabled
|
||||
)
|
||||
guard applied?.matches(next) != true else { return }
|
||||
applied = next
|
||||
clearBridgeTarget()
|
||||
loadState.reset()
|
||||
pendingDocumentUrl = nil
|
||||
webView.stopLoading()
|
||||
webView.isHidden = false
|
||||
emit(loadState.started())
|
||||
guard
|
||||
MobileWebShellOrigin.isValidSessionId(sessionId),
|
||||
let documentUrl = MobileWebShellOrigin.documentUrl(sessionId: sessionId)
|
||||
else {
|
||||
// The private origin is the isolation primitive; a malformed session id leaves us without one.
|
||||
failPropUpdate(.isolationUnavailable)
|
||||
return
|
||||
}
|
||||
guard
|
||||
let generation = try? MobileWebShellGeneration.load(directoryPath: generationDirectory)
|
||||
else {
|
||||
failPropUpdate(.generationUnreadable)
|
||||
return
|
||||
}
|
||||
schemeHandler.sessionId = sessionId
|
||||
schemeHandler.generation = generation
|
||||
applyBridgeInstallation()
|
||||
if isolationFailed {
|
||||
failPropUpdate(.isolationUnavailable)
|
||||
return
|
||||
}
|
||||
pendingDocumentUrl = documentUrl
|
||||
loadWhenIsolated()
|
||||
}
|
||||
|
||||
/// Retire the old visible generation even when the replacement fails.
|
||||
private func failPropUpdate(_ reason: MobileWebShellFailureReason) {
|
||||
clearBridgeTarget()
|
||||
schemeHandler.sessionId = nil
|
||||
schemeHandler.generation = nil
|
||||
pendingDocumentUrl = nil
|
||||
webView.stopLoading()
|
||||
webView.isHidden = true
|
||||
emit(loadState.failed(reason))
|
||||
func postBridgeMessage(_ json: String, promise: Promise) throws {
|
||||
guard let document else { throw MobileWebShellBridgeUnavailableException() }
|
||||
try document.postBridgeMessage(json, promise: promise)
|
||||
}
|
||||
|
||||
/// removeAllUserScripts is WebKit’s only removal API, so disabling the bridge must reinstall the blocker.
|
||||
private static func makeBlockerScript() -> WKUserScript {
|
||||
WKUserScript(
|
||||
source: networkApiBlocker,
|
||||
injectionTime: .atDocumentStart,
|
||||
forMainFrameOnly: false
|
||||
)
|
||||
func documentLoadState(_ payload: [String: Any]) {
|
||||
onLoadState(payload)
|
||||
}
|
||||
|
||||
/// Nothing here runs while the prop stays false, which is what keeps Phase B byte-identical.
|
||||
private func applyBridgeInstallation() {
|
||||
guard bridgeEnabled != bridgeInstalled else { return }
|
||||
clearBridgeTarget()
|
||||
let controller = webView.configuration.userContentController
|
||||
if bridgeEnabled {
|
||||
controller.add(bridgeReceiver, name: MobileWebShellBridge.handlerName)
|
||||
controller.addUserScript(
|
||||
WKUserScript(
|
||||
source: bridgeInstaller,
|
||||
injectionTime: .atDocumentStart,
|
||||
// Main-frame injection is convenience; accepts must still refuse subframes that reach the handler.
|
||||
forMainFrameOnly: true
|
||||
)
|
||||
)
|
||||
} else {
|
||||
controller.removeScriptMessageHandler(forName: MobileWebShellBridge.handlerName)
|
||||
controller.removeAllUserScripts()
|
||||
controller.addUserScript(Self.makeBlockerScript())
|
||||
}
|
||||
bridgeInstalled = bridgeEnabled
|
||||
}
|
||||
|
||||
/// Use the loaded session, not latest props; the replaced same-origin document survives until commit.
|
||||
fileprivate func receiveBridgeMessage(_ message: WKScriptMessage) {
|
||||
guard bridgeInstalled, let json = message.body as? String else { return }
|
||||
let origin = message.frameInfo.securityOrigin
|
||||
let source = MobileWebShellBridgeSource(
|
||||
isOurWebView: message.webView === webView,
|
||||
isMainFrame: message.frameInfo.isMainFrame,
|
||||
hasCommittedDocument: loadState.hasCommittedDocument,
|
||||
originProtocol: origin.`protocol`,
|
||||
originHost: origin.host
|
||||
)
|
||||
guard
|
||||
MobileWebShellBridge.accepts(source, sessionId: appliedSessionId ?? ""),
|
||||
bridgeGate.accepts(byteCount: json.utf8.count)
|
||||
else { return }
|
||||
bridgeTarget.arm(frame: message.frameInfo, originHost: origin.host)
|
||||
func documentBridgeMessage(_ json: String) {
|
||||
onBridgeMessage(["json": json])
|
||||
}
|
||||
|
||||
/// Anything that ends the document the page spoke from ends the only target native has.
|
||||
private func clearBridgeTarget() {
|
||||
bridgeTarget.clear()
|
||||
}
|
||||
|
||||
/// Reject posts without a live committed frame that spoke; resolve only after page execution so host requests cannot hang.
|
||||
func postBridgeMessage(_ json: String, promise: Promise) throws {
|
||||
guard
|
||||
MobileWebShellBridge.canPost(
|
||||
toFrameOriginHost: bridgeTarget.originHost,
|
||||
sessionId: appliedSessionId ?? "",
|
||||
hasCommittedDocument: loadState.hasCommittedDocument
|
||||
),
|
||||
let frame = bridgeTarget.frame
|
||||
else {
|
||||
throw MobileWebShellBridgeUnavailableException()
|
||||
}
|
||||
let byteCount = json.utf8.count
|
||||
guard MobileWebShellBridge.acceptsByteCount(byteCount) else {
|
||||
throw MobileWebShellBridgeMessageTooLargeException(byteCount)
|
||||
}
|
||||
// Use the two in: labels plus completionHandler to select the callback overload and reply to the frame that spoke.
|
||||
webView.callAsyncJavaScript(
|
||||
bridgeDeliver,
|
||||
arguments: ["m": json],
|
||||
in: frame,
|
||||
in: .page
|
||||
) { result in
|
||||
switch result {
|
||||
case .success:
|
||||
promise.resolve()
|
||||
case .failure(let error):
|
||||
promise.reject(MobileWebShellBridgeDeliveryFailedException(error.localizedDescription))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private func installNetworkBlock(into controller: WKUserContentController) {
|
||||
NetworkBlockRuleList.load { [weak self] ruleList in
|
||||
guard let self else { return }
|
||||
guard let ruleList else {
|
||||
self.isolationFailed = true
|
||||
self.pendingDocumentUrl = nil
|
||||
// Rule compilation can finish after refusal; the state machine prevents a second terminal reason.
|
||||
if self.appliedSessionId != nil {
|
||||
self.failPropUpdate(.isolationUnavailable)
|
||||
}
|
||||
return
|
||||
}
|
||||
controller.add(ruleList)
|
||||
self.isolationReady = true
|
||||
self.loadWhenIsolated()
|
||||
}
|
||||
}
|
||||
|
||||
private func loadWhenIsolated() {
|
||||
guard isolationReady, pendingDocumentUrl != nil, !keyboardPreparationPending,
|
||||
let window, window.isKeyWindow,
|
||||
window.windowScene?.activationState == .foregroundActive else { return }
|
||||
keyboardPreparationPending = true
|
||||
DispatchQueue.main.async { [weak self, weak window] in
|
||||
guard let self else { return }
|
||||
guard let window, self.window === window, window.isKeyWindow,
|
||||
window.windowScene?.activationState == .foregroundActive else {
|
||||
self.keyboardPreparationPending = false
|
||||
self.loadWhenIsolated()
|
||||
return
|
||||
}
|
||||
let delay: TimeInterval
|
||||
switch MobileWebShellKeyboardWarmup.prepare(in: window) {
|
||||
case .ready(let remainingDelay):
|
||||
delay = remainingDelay
|
||||
case .waitingForTextInput:
|
||||
DispatchQueue.main.asyncAfter(deadline: .now() + 0.25) { [weak self] in
|
||||
guard let self else { return }
|
||||
self.keyboardPreparationPending = false
|
||||
self.loadWhenIsolated()
|
||||
}
|
||||
return
|
||||
case .failed:
|
||||
self.keyboardPreparationPending = false
|
||||
self.failPropUpdate(.documentLoadFailed)
|
||||
return
|
||||
}
|
||||
DispatchQueue.main.asyncAfter(deadline: .now() + delay) { [weak self, weak window] in
|
||||
guard let self else { return }
|
||||
self.keyboardPreparationPending = false
|
||||
guard let window, self.window === window, window.isKeyWindow,
|
||||
window.windowScene?.activationState == .foregroundActive else {
|
||||
self.loadWhenIsolated()
|
||||
return
|
||||
}
|
||||
guard self.isolationReady, let url = self.pendingDocumentUrl else { return }
|
||||
self.pendingDocumentUrl = nil
|
||||
self.loadState.shellLoadStarted()
|
||||
self.webView.load(URLRequest(url: url, cachePolicy: .reloadIgnoringLocalCacheData))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private func emit(_ emission: MobileWebShellLoadEmission?) {
|
||||
guard let emission else { return }
|
||||
onLoadState(emission.payload)
|
||||
}
|
||||
|
||||
private func reportDocumentFailure() {
|
||||
clearBridgeTarget()
|
||||
emit(loadState.failed(.documentLoadFailed))
|
||||
}
|
||||
|
||||
/// A cancelled navigation is our own doing, not the document's; see MobileWebShellNavigationError.
|
||||
private func reportNavigationFailure(_ error: Error) {
|
||||
let error = error as NSError
|
||||
guard !MobileWebShellNavigationError.isIgnorable(domain: error.domain, code: error.code) else {
|
||||
return
|
||||
}
|
||||
reportDocumentFailure()
|
||||
}
|
||||
|
||||
private func isDocumentUrl(_ url: URL?) -> Bool {
|
||||
guard let url, let parts = MobileWebShellRequestParts(url: url) else { return false }
|
||||
return MobileWebShellOrigin.resolveRequestPath(parts, sessionId: sessionId) == "/"
|
||||
}
|
||||
|
||||
func webView(
|
||||
_ webView: WKWebView,
|
||||
decidePolicyFor navigationAction: WKNavigationAction,
|
||||
decisionHandler: @escaping (WKNavigationActionPolicy) -> Void
|
||||
) {
|
||||
var isDownload = false
|
||||
if #available(iOS 14.5, *) {
|
||||
isDownload = navigationAction.shouldPerformDownload
|
||||
}
|
||||
let isMainFrame = navigationAction.targetFrame?.isMainFrame == true
|
||||
// linkActivated gates only opener offers; gesture-free subframe top navigation must never authorize a load.
|
||||
let verdict = MobileWebShellNavigationPolicy.verdict(
|
||||
url: navigationAction.request.url?.absoluteString,
|
||||
isMainFrame: isMainFrame,
|
||||
isDocumentUrl: isDocumentUrl(navigationAction.request.url),
|
||||
isShellLoad: loadState.isShellLoad,
|
||||
hasGesture: navigationAction.navigationType == .linkActivated,
|
||||
isDownload: isDownload
|
||||
)
|
||||
if case let .cancelAndOffer(url) = verdict {
|
||||
onExternalNavigation(["url": url])
|
||||
}
|
||||
if verdict == .allow && isMainFrame {
|
||||
// Spend before handing back the decision so another main-frame action cannot reuse the allowance.
|
||||
loadState.shellLoadConsumed()
|
||||
}
|
||||
decisionHandler(verdict == .allow ? .allow : .cancel)
|
||||
}
|
||||
|
||||
func webView(
|
||||
_ webView: WKWebView,
|
||||
decidePolicyFor navigationResponse: WKNavigationResponse,
|
||||
decisionHandler: @escaping (WKNavigationResponsePolicy) -> Void
|
||||
) {
|
||||
// Only srcdoc subframes pass the action policy; refusing one must not fail the shell document.
|
||||
guard navigationResponse.isForMainFrame else {
|
||||
let url = navigationResponse.response.url?.absoluteString
|
||||
decisionHandler(url == MobileWebShellNavigationPolicy.inlineDocumentUrl ? .allow : .cancel)
|
||||
return
|
||||
}
|
||||
let allowed = navigationResponse.canShowMIMEType &&
|
||||
isDocumentUrl(navigationResponse.response.url)
|
||||
if !allowed {
|
||||
reportDocumentFailure()
|
||||
}
|
||||
decisionHandler(allowed ? .allow : .cancel)
|
||||
}
|
||||
|
||||
func webView(_ webView: WKWebView, didStartProvisionalNavigation navigation: WKNavigation!) {
|
||||
// Clear replies and acceptance when the document is replaced; its successor must commit and send ready.
|
||||
clearBridgeTarget()
|
||||
loadState.documentEnded()
|
||||
guard appliedSessionId != nil else { return }
|
||||
emit(loadState.started())
|
||||
}
|
||||
|
||||
/// Arm at commit, before document-start messages and didFinish.
|
||||
func webView(_ webView: WKWebView, didCommit navigation: WKNavigation!) {
|
||||
guard isDocumentUrl(webView.url) else { return }
|
||||
// Commit rearms acceptance, so clear the replaced frame here as well as at provisional start.
|
||||
clearBridgeTarget()
|
||||
loadState.committed()
|
||||
}
|
||||
|
||||
/// history.replaceState changes the path before finish; finished() uses commit state instead of URL equality.
|
||||
func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
|
||||
MobileWebShellWarmUp.release()
|
||||
emit(loadState.finished())
|
||||
}
|
||||
|
||||
func webView(
|
||||
_ webView: WKWebView,
|
||||
didFailProvisionalNavigation navigation: WKNavigation!,
|
||||
withError error: Error
|
||||
) {
|
||||
MobileWebShellWarmUp.release()
|
||||
reportNavigationFailure(error)
|
||||
}
|
||||
|
||||
func webView(_ webView: WKWebView, didFail navigation: WKNavigation!, withError error: Error) {
|
||||
MobileWebShellWarmUp.release()
|
||||
reportNavigationFailure(error)
|
||||
}
|
||||
|
||||
/// Report renderer death; memory pressure/provider updates look alike, so the caller owns retry policy.
|
||||
func webViewWebContentProcessDidTerminate(_ webView: WKWebView) {
|
||||
MobileWebShellWarmUp.release()
|
||||
clearBridgeTarget()
|
||||
// Jetsam takes WebContent while Orca is backgrounded; the report can arrive as the app resumes, before it is active.
|
||||
let background = window == nil || UIApplication.shared.applicationState != .active
|
||||
emit(loadState.failed(.renderProcessGone, background: background))
|
||||
}
|
||||
|
||||
func webView(
|
||||
_ webView: WKWebView,
|
||||
createWebViewWith configuration: WKWebViewConfiguration,
|
||||
for navigationAction: WKNavigationAction,
|
||||
windowFeatures: WKWindowFeatures
|
||||
) -> WKWebView? {
|
||||
nil
|
||||
func documentExternalNavigation(_ url: String) {
|
||||
onExternalNavigation(["url": url])
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,12 +1,53 @@
|
||||
import ExpoModulesCore
|
||||
import QuickLook
|
||||
import UIKit
|
||||
|
||||
public class OrcaMobileWebShellModule: Module {
|
||||
private var pdfPreview: MobileWebShellPdfPreview?
|
||||
private var memoryWarningObserver: NSObjectProtocol?
|
||||
|
||||
public func definition() -> ModuleDefinition {
|
||||
Name("OrcaMobileWebShell")
|
||||
|
||||
// A spare is the first thing to give back: nothing is shown by it.
|
||||
OnCreate {
|
||||
memoryWarningObserver = NotificationCenter.default.addObserver(
|
||||
forName: UIApplication.didReceiveMemoryWarningNotification,
|
||||
object: nil,
|
||||
queue: .main
|
||||
) { _ in
|
||||
MobileWebShellSparePool.shared.discardAll()
|
||||
}
|
||||
}
|
||||
|
||||
OnDestroy {
|
||||
if let memoryWarningObserver {
|
||||
NotificationCenter.default.removeObserver(memoryWarningObserver)
|
||||
}
|
||||
DispatchQueue.main.async {
|
||||
MobileWebShellSparePool.shared.discardAll()
|
||||
}
|
||||
}
|
||||
|
||||
// Home boots the next one after its next foreground idle.
|
||||
OnAppEntersBackground {
|
||||
DispatchQueue.main.async {
|
||||
MobileWebShellSparePool.shared.discardAll()
|
||||
}
|
||||
}
|
||||
|
||||
AsyncFunction("prepareSpareDocument") { (directory: String, sessionId: String) -> Bool in
|
||||
MobileWebShellSparePool.shared.prepare(directory: directory, sessionId: sessionId)
|
||||
}.runOnQueue(.main)
|
||||
|
||||
AsyncFunction("claimSpareDocument") { (directory: String) -> String? in
|
||||
MobileWebShellSparePool.shared.claim(directory: directory)
|
||||
}.runOnQueue(.main)
|
||||
|
||||
AsyncFunction("discardSpareDocument") {
|
||||
MobileWebShellSparePool.shared.discardAll()
|
||||
}.runOnQueue(.main)
|
||||
|
||||
// Home calls this once it has a paired host, so a user with nothing to open pays nothing.
|
||||
Function("warmUp") {
|
||||
// A second's delay keeps the warm-up off the launch's first frames.
|
||||
|
||||
@@ -0,0 +1,27 @@
|
||||
import { requireOptionalNativeModule } from 'expo-modules-core'
|
||||
|
||||
type SpareDocumentModule = {
|
||||
prepareSpareDocument?: (directory: string, sessionId: string) => Promise<boolean>
|
||||
claimSpareDocument?: (directory: string) => Promise<string | null>
|
||||
discardSpareDocument?: () => Promise<void>
|
||||
}
|
||||
|
||||
// A binary built before the spare existed has the module without these functions.
|
||||
const spareModule = (): SpareDocumentModule | null =>
|
||||
requireOptionalNativeModule<SpareDocumentModule>('OrcaMobileWebShell')
|
||||
|
||||
// Boot a page from `directory` under `sessionId` and park it, invisible, until a screen claims it.
|
||||
// False when native declined: a phone under 4 GB, the app not active, or a page document shown.
|
||||
export async function prepareSpareDocument(directory: string, sessionId: string): Promise<boolean> {
|
||||
return (await spareModule()?.prepareSpareDocument?.(directory, sessionId)) ?? false
|
||||
}
|
||||
|
||||
// The parked spare's session id when it was booted from `directory`, handed out once. The view
|
||||
// mounted under that id adopts the booted page.
|
||||
export async function claimSpareDocument(directory: string): Promise<string | null> {
|
||||
return (await spareModule()?.claimSpareDocument?.(directory)) ?? null
|
||||
}
|
||||
|
||||
export async function discardSpareDocument(): Promise<void> {
|
||||
await spareModule()?.discardSpareDocument?.()
|
||||
}
|
||||
@@ -35,17 +35,6 @@
|
||||
"ordinal": 9,
|
||||
"json": "{\"id\":\"frame-3\",\"deviceToken\":\"recording-device\",\"method\":\"ssh.listTargetSummaries\"}"
|
||||
},
|
||||
"18c2b8e092d7": {
|
||||
"name": "streams-registered-at-teardown",
|
||||
"ordinal": 26,
|
||||
"value": [
|
||||
{
|
||||
"cancelled": true,
|
||||
"method": "runtime.clientEvents.subscribe",
|
||||
"payload": "runtime.clientEvents.subscribe#1"
|
||||
}
|
||||
]
|
||||
},
|
||||
"20200b8feac4": {
|
||||
"name": "host.platform#1",
|
||||
"ordinal": 6,
|
||||
@@ -106,6 +95,17 @@
|
||||
"startedAt": 0
|
||||
}
|
||||
},
|
||||
"44eb39507b75": {
|
||||
"name": "streams-registered-at-teardown",
|
||||
"ordinal": 23,
|
||||
"value": [
|
||||
{
|
||||
"cancelled": true,
|
||||
"method": "runtime.clientEvents.subscribe",
|
||||
"payload": "runtime.clientEvents.subscribe#1"
|
||||
}
|
||||
]
|
||||
},
|
||||
"564f54c8d902": {
|
||||
"name": "host.platform#1",
|
||||
"ordinal": 6,
|
||||
@@ -137,11 +137,6 @@
|
||||
"ordinal": 13,
|
||||
"value": [["ssh:ssh-1", "SSH"]]
|
||||
},
|
||||
"59ab92fbdbc0": {
|
||||
"name": "hostPlatform",
|
||||
"ordinal": 25,
|
||||
"value": "linux"
|
||||
},
|
||||
"6770aa1912e4": {
|
||||
"name": "repo.list#2",
|
||||
"ordinal": 15,
|
||||
@@ -411,11 +406,6 @@
|
||||
"status": "pending",
|
||||
"startedAt": 0
|
||||
},
|
||||
"9c290301a4bc": {
|
||||
"name": "hostHealthById",
|
||||
"ordinal": 23,
|
||||
"value": []
|
||||
},
|
||||
"b2746491ac07": {
|
||||
"name": "repo.list#1",
|
||||
"ordinal": 2,
|
||||
@@ -642,11 +632,6 @@
|
||||
"name": "hostPlatform",
|
||||
"ordinal": 14,
|
||||
"value": "linux"
|
||||
},
|
||||
"fb797b9761e1": {
|
||||
"name": "hostLabelById",
|
||||
"ordinal": 24,
|
||||
"value": [["ssh:ssh-1", "SSH"]]
|
||||
}
|
||||
},
|
||||
"recording": {
|
||||
@@ -795,10 +780,7 @@
|
||||
"8cfdd18c5fe6",
|
||||
"84c1dde54c62",
|
||||
"56ab81cb67dc",
|
||||
"f9193cae5824",
|
||||
"9c290301a4bc",
|
||||
"fb797b9761e1",
|
||||
"59ab92fbdbc0"
|
||||
"f9193cae5824"
|
||||
]
|
||||
}
|
||||
},
|
||||
@@ -838,10 +820,7 @@
|
||||
"84c1dde54c62",
|
||||
"56ab81cb67dc",
|
||||
"f9193cae5824",
|
||||
"9c290301a4bc",
|
||||
"fb797b9761e1",
|
||||
"59ab92fbdbc0",
|
||||
"18c2b8e092d7"
|
||||
"44eb39507b75"
|
||||
]
|
||||
}
|
||||
}
|
||||
|
||||
@@ -84,15 +84,6 @@ describe('app update checker', () => {
|
||||
expect(h.checker.getSnapshot().checking).toBe(false)
|
||||
})
|
||||
|
||||
it('joins a manual check to one already in flight', async () => {
|
||||
const h = harness({ stored: { lastCheckedAt: T0 }, replies: [{ kind: 'current' }] })
|
||||
h.checker.start()
|
||||
await vi.advanceTimersByTimeAsync(0)
|
||||
const [first, second] = [h.checker.checkNow(), h.checker.checkNow()]
|
||||
await expect(Promise.all([first, second])).resolves.toEqual(['up-to-date', 'up-to-date'])
|
||||
expect(checks(h)).toBe(1)
|
||||
})
|
||||
|
||||
it('keeps the 1 h retry for a manual check that fails while the store is still loading', async () => {
|
||||
let finishLoad: () => void = () => {}
|
||||
const h = harness({
|
||||
@@ -112,15 +103,6 @@ describe('app update checker', () => {
|
||||
expect(checks(h)).toBe(2)
|
||||
})
|
||||
|
||||
it('applies one load and runs one check across a StrictMode-style double start', async () => {
|
||||
const h = harness({})
|
||||
h.checker.start()()
|
||||
h.checker.start()
|
||||
await vi.advanceTimersByTimeAsync(0)
|
||||
expect(h.deps.loadPreferences).toHaveBeenCalledTimes(1)
|
||||
expect(checks(h)).toBe(1)
|
||||
})
|
||||
|
||||
function deferredReply() {
|
||||
let answer: (result: AppUpdateCheckResult) => void = () => {}
|
||||
const reply = new Promise<AppUpdateCheckResult>((resolve) => {
|
||||
|
||||
@@ -1,116 +0,0 @@
|
||||
import { describe, expect, it, vi } from 'vitest'
|
||||
import { BRIDGE_MAX_MESSAGE_BYTES } from '../mobile-web-shell/bridge/bridge-caps'
|
||||
import { buildMobileBrowserScreencastRequest } from './browser-screencast-request'
|
||||
import {
|
||||
base64Characters,
|
||||
binaryEventEnvelopeBytes,
|
||||
budgetedMobileViewDeviceScaleFactor,
|
||||
buildMobileBrowserScreencastRequest as buildOnWeb,
|
||||
WORST_CASE_JPEG_BYTES_PER_PIXEL
|
||||
} from './browser-screencast-request.web'
|
||||
|
||||
/** A phone's measured browser area, in CSS pixels. */
|
||||
const PHONE = { width: 390, height: 712 }
|
||||
|
||||
/** What the shell would have to post for a frame of this area at the worst case JPEG has. */
|
||||
function frameMessageBytes(areaPixels: number): number {
|
||||
const imageBytes = Math.ceil(areaPixels * WORST_CASE_JPEG_BYTES_PER_PIXEL)
|
||||
return base64Characters(imageBytes) + binaryEventEnvelopeBytes()
|
||||
}
|
||||
|
||||
function mobileFrameArea(
|
||||
layout: { width: number; height: number },
|
||||
request: { deviceScaleFactor?: number } | null
|
||||
): number {
|
||||
const scale = request?.deviceScaleFactor
|
||||
if (scale === undefined) {
|
||||
throw new Error('the request carried no device scale factor')
|
||||
}
|
||||
return Math.round(layout.width) * Math.round(layout.height) * scale * scale
|
||||
}
|
||||
|
||||
describe('the mobile-view area budget', () => {
|
||||
// Native density at same phone size exceeds bridge cap; without web budget shell drops frame.
|
||||
it('is needed: the native request overflows the frame cap on a phone', () => {
|
||||
const native = buildMobileBrowserScreencastRequest(PHONE, 2, 'mobile')
|
||||
|
||||
expect(native?.deviceScaleFactor).toBe(2)
|
||||
expect(frameMessageBytes(mobileFrameArea(PHONE, native))).toBeGreaterThan(
|
||||
BRIDGE_MAX_MESSAGE_BYTES
|
||||
)
|
||||
})
|
||||
|
||||
it('keeps the worst case frame inside one bridge message', () => {
|
||||
const budgeted = buildOnWeb(PHONE, 2, 'mobile')
|
||||
|
||||
expect(frameMessageBytes(mobileFrameArea(PHONE, budgeted))).toBeLessThanOrEqual(
|
||||
BRIDGE_MAX_MESSAGE_BYTES
|
||||
)
|
||||
})
|
||||
|
||||
it('uses the largest hundredth of density whose frame fits the cap', () => {
|
||||
const scale = budgetedMobileViewDeviceScaleFactor(PHONE)
|
||||
expect(
|
||||
frameMessageBytes(mobileFrameArea(PHONE, { deviceScaleFactor: scale + 0.01 }))
|
||||
).toBeGreaterThan(BRIDGE_MAX_MESSAGE_BYTES)
|
||||
})
|
||||
|
||||
it('leaves web mode byte-identical to the native request', () => {
|
||||
expect(buildOnWeb(PHONE, 2, 'web')).toEqual(
|
||||
buildMobileBrowserScreencastRequest(PHONE, 2, 'web')
|
||||
)
|
||||
expect(buildOnWeb(PHONE, 2)).toEqual(buildMobileBrowserScreencastRequest(PHONE, 2))
|
||||
})
|
||||
|
||||
it('never asks for more density than native, on a viewport the budget does not bind', () => {
|
||||
expect(budgetedMobileViewDeviceScaleFactor({ width: 200, height: 200 })).toBe(2)
|
||||
})
|
||||
|
||||
it('stops at one device pixel per CSS pixel on a viewport no scale would fit', () => {
|
||||
// Never request fewer device pixels than CSS pixels; shell drops frames still too large at density 1.
|
||||
expect(budgetedMobileViewDeviceScaleFactor({ width: 2000, height: 1400 })).toBe(1)
|
||||
})
|
||||
|
||||
it('answers the native factor when there is no layout to budget against', () => {
|
||||
expect(budgetedMobileViewDeviceScaleFactor(null)).toBe(2)
|
||||
expect(buildOnWeb(null, 2, 'mobile')).toBeNull()
|
||||
expect(buildOnWeb({ width: 0, height: 712 }, 2, 'mobile')).toBeNull()
|
||||
})
|
||||
})
|
||||
|
||||
it('counts base64 padding for an image that does not fill its last group', () => {
|
||||
expect(base64Characters(3001)).toBe(4004)
|
||||
})
|
||||
|
||||
describe('web-mode request work', () => {
|
||||
for (const mode of [undefined, 'web'] as const) {
|
||||
it(`skips discarded mobile density work in ${mode ?? 'default'} view`, () => {
|
||||
const layouts = [
|
||||
{ width: 360, height: 640 },
|
||||
{ width: 390, height: 712 },
|
||||
{ width: 402, height: 593 },
|
||||
{ width: 319.49, height: 239.51 },
|
||||
{ width: 1200, height: 1200 },
|
||||
{ width: 2000, height: 1400 }
|
||||
]
|
||||
const expected = layouts.map((layout) => buildMobileBrowserScreencastRequest(layout, 2, mode))
|
||||
const stringify = vi.spyOn(JSON, 'stringify')
|
||||
const sqrt = vi.spyOn(Math, 'sqrt')
|
||||
let actual: ReturnType<typeof buildOnWeb>[] = []
|
||||
let envelopeCalls = 0
|
||||
let sqrtCalls = 0
|
||||
try {
|
||||
actual = layouts.map((layout) => buildOnWeb(layout, 2, mode))
|
||||
envelopeCalls = stringify.mock.calls.length
|
||||
sqrtCalls = sqrt.mock.calls.length
|
||||
} finally {
|
||||
stringify.mockRestore()
|
||||
sqrt.mockRestore()
|
||||
}
|
||||
|
||||
expect(actual).toEqual(expected)
|
||||
expect(envelopeCalls).toBe(0)
|
||||
expect(sqrtCalls).toBe(0)
|
||||
})
|
||||
}
|
||||
})
|
||||
@@ -1,12 +0,0 @@
|
||||
import { describe, expect, it } from 'vitest'
|
||||
|
||||
import { normalizeBrowserUrl } from './browser-url'
|
||||
|
||||
describe('normalizeBrowserUrl', () => {
|
||||
it('keeps localhost-style addresses as http URLs', () => {
|
||||
expect(normalizeBrowserUrl('localhost:3000')).toBe('http://localhost:3000/')
|
||||
expect(normalizeBrowserUrl('127.0.0.1:6769/web-index.html')).toBe(
|
||||
'http://127.0.0.1:6769/web-index.html'
|
||||
)
|
||||
})
|
||||
})
|
||||
@@ -1,55 +0,0 @@
|
||||
import { beforeEach, describe, expect, it } from 'vitest'
|
||||
import {
|
||||
clearMobileBrowserViewModeState,
|
||||
getInitialMobileBrowserViewMode,
|
||||
saveMobileBrowserViewMode
|
||||
} from './mobile-browser-view-mode-state'
|
||||
|
||||
describe('mobile browser view mode state', () => {
|
||||
beforeEach(() => {
|
||||
clearMobileBrowserViewModeState()
|
||||
})
|
||||
|
||||
it('defaults each browser page to web view', () => {
|
||||
expect(getInitialMobileBrowserViewMode('worktree-1', 'page-1')).toBe('web')
|
||||
expect(getInitialMobileBrowserViewMode('worktree-1', null)).toBe('web')
|
||||
})
|
||||
|
||||
it('defaults local HTML reports to mobile view', () => {
|
||||
expect(
|
||||
getInitialMobileBrowserViewMode(
|
||||
'folder:workspace-1',
|
||||
'page-1',
|
||||
'file:///Users/me/report%20one.HTML?generated=1'
|
||||
)
|
||||
).toBe('mobile')
|
||||
expect(
|
||||
getInitialMobileBrowserViewMode('worktree-1', 'page-2', 'file:///C:/Users/me/report.htm')
|
||||
).toBe('mobile')
|
||||
})
|
||||
|
||||
it('keeps remote HTML URLs and non-HTML files in web view', () => {
|
||||
expect(
|
||||
getInitialMobileBrowserViewMode('worktree-1', 'page-1', 'https://example.com/report.html')
|
||||
).toBe('web')
|
||||
expect(getInitialMobileBrowserViewMode('worktree-1', 'page-2', 'file:///repo/notes.txt')).toBe(
|
||||
'web'
|
||||
)
|
||||
})
|
||||
|
||||
it('restores the last mode for the same browser page after remount', () => {
|
||||
saveMobileBrowserViewMode('worktree-1', 'page-1', 'mobile')
|
||||
|
||||
expect(getInitialMobileBrowserViewMode('worktree-1', 'page-1')).toBe('mobile')
|
||||
expect(getInitialMobileBrowserViewMode('worktree-1', 'page-2')).toBe('web')
|
||||
expect(getInitialMobileBrowserViewMode('worktree-2', 'page-1')).toBe('web')
|
||||
})
|
||||
|
||||
it('preserves an explicit web choice for a local HTML report', () => {
|
||||
saveMobileBrowserViewMode('worktree-1', 'page-1', 'web')
|
||||
|
||||
expect(
|
||||
getInitialMobileBrowserViewMode('worktree-1', 'page-1', 'file:///repo/report.html')
|
||||
).toBe('web')
|
||||
})
|
||||
})
|
||||
@@ -25,17 +25,6 @@ describe('drag completion and cancellation', () => {
|
||||
await act(async () => fixture.root.unmount())
|
||||
})
|
||||
|
||||
it('commits the moved order once on a successful drop', async () => {
|
||||
const fixture = await mounted()
|
||||
await act(async () => {
|
||||
fixture.gesture.start!({ absoluteY: 100, translationY: 0 }, true)
|
||||
fixture.gesture.update!({ absoluteY: 180, translationY: 80 }, true)
|
||||
fixture.gesture.finalize!({ absoluteY: 180, translationY: 80 }, true)
|
||||
})
|
||||
expect(fixture.onReorder.mock.calls).toEqual([[['b', 'a']]])
|
||||
await act(async () => fixture.root.unmount())
|
||||
})
|
||||
|
||||
it('does not write after a failed activation or an unchanged drop', async () => {
|
||||
const fixture = await mounted()
|
||||
await act(async () => {
|
||||
@@ -286,56 +275,3 @@ it('keeps measured rows still on hold, restores cancellation, and drops by moved
|
||||
expect(move).toHaveBeenCalledExactlyOnceWith({ movedId: 'a', afterId: 'c' })
|
||||
await act(async () => root!.unmount())
|
||||
})
|
||||
|
||||
it.each([100, 1000])(
|
||||
'bounds accessibility work for %i rows while excluded slots stay fixed',
|
||||
async (count) => {
|
||||
const ids = Array.from({ length: count }, (_, at) =>
|
||||
at === 1 ? 'fixed' : at === 2 ? 'busy' : `row-${at}`
|
||||
)
|
||||
let keyReads = 0
|
||||
let membership = 0
|
||||
const onMove = vi.fn()
|
||||
const onReorder = vi.fn()
|
||||
function Harness({ items = ids }: { items?: string[] }) {
|
||||
return createElement(DragReorderList<string>, {
|
||||
items,
|
||||
itemKey: (id) => {
|
||||
keyReads++
|
||||
return id
|
||||
},
|
||||
canMove: (id) => {
|
||||
membership++
|
||||
return id !== 'fixed' && id !== 'busy'
|
||||
},
|
||||
rowHeight: 56,
|
||||
renderRow: (id, handle) => createElement('Text', null, id, handle),
|
||||
onMove,
|
||||
onReorder,
|
||||
scrollRef: useAnimatedRef<Animated.ScrollView>(),
|
||||
scrollOffsetY: useSharedValue(0),
|
||||
scrollContentHeight: useSharedValue(count * 56)
|
||||
})
|
||||
}
|
||||
let root: ReturnType<typeof create>
|
||||
await act(async () => {
|
||||
root = create(createElement(Harness))
|
||||
})
|
||||
const first = root!.root.findAll(
|
||||
(node) => node.type === Animated.View && node.props.onAccessibilityAction
|
||||
)[0]!
|
||||
const accessibilityAction = first.props.onAccessibilityAction
|
||||
keyReads = membership = 0
|
||||
await act(async () => accessibilityAction({ nativeEvent: { actionName: 'moveUp' } }))
|
||||
expect(onMove).not.toHaveBeenCalled()
|
||||
await act(async () => accessibilityAction({ nativeEvent: { actionName: 'moveDown' } }))
|
||||
expect(keyReads).toBeLessThanOrEqual(3 * count)
|
||||
expect(membership).toBeLessThanOrEqual(3 * count)
|
||||
expect(onReorder.mock.calls[0]![0].slice(0, 4)).toEqual(['row-3', 'fixed', 'busy', 'row-0'])
|
||||
expect(onMove).toHaveBeenCalledExactlyOnceWith({ movedId: 'row-0', beforeId: 'row-4' })
|
||||
await act(async () => root!.update(createElement(Harness, { items: ids.slice(1) })))
|
||||
await act(async () => accessibilityAction({ nativeEvent: { actionName: 'moveDown' } }))
|
||||
expect(onMove).toHaveBeenCalledOnce()
|
||||
await act(async () => root!.unmount())
|
||||
}
|
||||
)
|
||||
|
||||
@@ -1,65 +0,0 @@
|
||||
import { createElement, type ReactNode } from 'react'
|
||||
import { act, create, type ReactTestRenderer } from 'react-test-renderer'
|
||||
import { afterEach, describe, expect, it, vi } from 'vitest'
|
||||
|
||||
vi.mock('react-native', async () => {
|
||||
const React = await import('react')
|
||||
return {
|
||||
Pressable: ({ children, ...props }: { children?: ReactNode }) =>
|
||||
React.createElement('Pressable', props, children),
|
||||
Text: ({ children, ...props }: { children?: ReactNode }) =>
|
||||
React.createElement('Text', props, children),
|
||||
View: ({ children, ...props }: { children?: ReactNode }) =>
|
||||
React.createElement('View', props, children),
|
||||
StyleSheet: { create: (styles: unknown) => styles }
|
||||
}
|
||||
})
|
||||
vi.mock('lucide-react-native', () => ({ X: 'X' }))
|
||||
|
||||
import { HostRouteNoticeBanner } from './HostRouteNoticeBanner'
|
||||
|
||||
// Announce inserted banner because list reader may be below it; failure interrupts, bounced-route context stays polite so urgency retains meaning.
|
||||
describe('the host route notice banner announces itself', () => {
|
||||
let renderer: ReactTestRenderer | null = null
|
||||
|
||||
afterEach(() => {
|
||||
act(() => renderer?.unmount())
|
||||
renderer = null
|
||||
})
|
||||
|
||||
function banner(tone?: 'notice' | 'failure') {
|
||||
act(() => {
|
||||
renderer = create(
|
||||
createElement(HostRouteNoticeBanner, {
|
||||
message: 'Nothing happened',
|
||||
tone,
|
||||
onDismiss: () => {}
|
||||
})
|
||||
)
|
||||
})
|
||||
if (renderer === null) {
|
||||
throw new Error('the banner did not render')
|
||||
}
|
||||
// Match host name to avoid ElementType cast for arbitrary RN strings; first match is banner root carrying tested props.
|
||||
return renderer.root.findAll((node) => String(node.type) === 'View')[0]
|
||||
}
|
||||
|
||||
it('interrupts for a failure, which is an action that did not happen', () => {
|
||||
const root = banner('failure')
|
||||
expect(root.props.accessibilityRole).toBe('alert')
|
||||
expect(root.props.accessibilityLiveRegion).toBe('assertive')
|
||||
})
|
||||
|
||||
it('waits its turn for a notice, which is context rather than a refusal', () => {
|
||||
const root = banner('notice')
|
||||
expect(root.props.accessibilityLiveRegion).toBe('polite')
|
||||
// No alert role: nothing here failed, and an alert is what the tone above is for.
|
||||
expect(root.props.accessibilityRole).toBeUndefined()
|
||||
})
|
||||
|
||||
it('treats the default tone as the notice one, which is what the route caller passes', () => {
|
||||
const root = banner(undefined)
|
||||
expect(root.props.accessibilityLiveRegion).toBe('polite')
|
||||
expect(root.props.accessibilityRole).toBeUndefined()
|
||||
})
|
||||
})
|
||||
@@ -1,22 +1,6 @@
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import { isMobileMermaidLanguage } from './mobile-mermaid-language'
|
||||
import { normalizeMobileMarkdownPreviewHtml } from './mobile-markdown-preview-html'
|
||||
|
||||
describe('isMobileMermaidLanguage', () => {
|
||||
it('matches mermaid case-insensitively after trim', () => {
|
||||
expect(isMobileMermaidLanguage('mermaid')).toBe(true)
|
||||
expect(isMobileMermaidLanguage('Mermaid')).toBe(true)
|
||||
expect(isMobileMermaidLanguage(' MERMAID ')).toBe(true)
|
||||
})
|
||||
|
||||
it('rejects non-mermaid languages and missing language', () => {
|
||||
expect(isMobileMermaidLanguage(undefined)).toBe(false)
|
||||
expect(isMobileMermaidLanguage('')).toBe(false)
|
||||
expect(isMobileMermaidLanguage('ts')).toBe(false)
|
||||
expect(isMobileMermaidLanguage('mermaidx')).toBe(false)
|
||||
})
|
||||
})
|
||||
|
||||
describe('normalizeMobileMarkdownPreviewHtml', () => {
|
||||
it('normalizes common README HTML into readable Markdown preview text', () => {
|
||||
const normalized = normalizeMobileMarkdownPreviewHtml(`
|
||||
|
||||
@@ -1,45 +0,0 @@
|
||||
import { Folder } from 'lucide-react-native'
|
||||
import { createElement } from 'react'
|
||||
import { Image } from 'react-native'
|
||||
import { act, create, type ReactTestRenderer } from 'react-test-renderer'
|
||||
import { afterEach, describe, expect, it, vi } from 'vitest'
|
||||
import { MobileRepoIcon } from './MobileRepoIcon'
|
||||
|
||||
vi.mock('react-native', () => ({
|
||||
Image: 'Image',
|
||||
StyleSheet: { create: <T,>(styles: T) => styles },
|
||||
Text: 'Text',
|
||||
View: 'View'
|
||||
}))
|
||||
// Each icon renders as an element named after it.
|
||||
vi.mock(
|
||||
'lucide-react-native',
|
||||
() => new Proxy({}, { has: () => true, get: (_, name) => String(name) })
|
||||
)
|
||||
vi.mock('../theme/use-mobile-color-scheme', () => ({ useMobileColorScheme: () => 'dark' }))
|
||||
|
||||
let renderer: ReactTestRenderer | null = null
|
||||
afterEach(() => {
|
||||
act(() => renderer?.unmount())
|
||||
renderer = null
|
||||
})
|
||||
|
||||
function imageIcon(src: string) {
|
||||
return createElement(MobileRepoIcon, { repoIcon: { type: 'image', src, label: 'owner/repo' } })
|
||||
}
|
||||
|
||||
describe('MobileRepoIcon', () => {
|
||||
it('shows the folder after an image fails, and tries a changed image again', () => {
|
||||
act(() => {
|
||||
renderer = create(imageIcon('https://github.com/owner.png?size=64'))
|
||||
})
|
||||
act(() => renderer!.root.findByType(Image).props.onError())
|
||||
expect(renderer!.root.findAllByType(Image)).toHaveLength(0)
|
||||
expect(renderer!.root.findAllByType(Folder)).toHaveLength(1)
|
||||
|
||||
act(() => renderer!.update(imageIcon('data:image/png;base64,AAAA')))
|
||||
expect(renderer!.root.findByType(Image).props.source).toEqual({
|
||||
uri: 'data:image/png;base64,AAAA'
|
||||
})
|
||||
})
|
||||
})
|
||||
@@ -1,68 +0,0 @@
|
||||
import { createElement } from 'react'
|
||||
import { act, create, type ReactTestRenderer } from 'react-test-renderer'
|
||||
import { afterEach, describe, expect, it, vi } from 'vitest'
|
||||
|
||||
vi.mock('react-native', () => ({
|
||||
Pressable: 'Pressable',
|
||||
ScrollView: 'ScrollView',
|
||||
StyleSheet: { create: (styles: unknown) => styles, hairlineWidth: 1 },
|
||||
View: 'View'
|
||||
}))
|
||||
|
||||
vi.mock('lucide-react-native', () => ({
|
||||
Bold: 'Bold',
|
||||
Code2: 'Code2',
|
||||
FileCode2: 'FileCode2',
|
||||
Heading1: 'Heading1',
|
||||
Heading2: 'Heading2',
|
||||
Heading3: 'Heading3',
|
||||
ImageIcon: 'ImageIcon',
|
||||
Italic: 'Italic',
|
||||
Link: 'Link',
|
||||
List: 'List',
|
||||
ListOrdered: 'ListOrdered',
|
||||
ListTodo: 'ListTodo',
|
||||
Pilcrow: 'Pilcrow',
|
||||
Quote: 'Quote',
|
||||
Strikethrough: 'Strikethrough'
|
||||
}))
|
||||
|
||||
import { MobileRichMarkdownToolbar } from './MobileRichMarkdownToolbar'
|
||||
import type { MobileRichMarkdownCommand } from './mobile-rich-markdown-editor-contract'
|
||||
|
||||
let renderer: ReactTestRenderer | null = null
|
||||
|
||||
afterEach(() => {
|
||||
act(() => renderer?.unmount())
|
||||
renderer = null
|
||||
})
|
||||
|
||||
function render(editable: boolean, onCommand: (command: MobileRichMarkdownCommand) => void) {
|
||||
act(() => {
|
||||
renderer = create(createElement(MobileRichMarkdownToolbar, { editable, onCommand }))
|
||||
})
|
||||
return renderer!.root.findAll((node) => String(node.type) === 'Pressable')
|
||||
}
|
||||
|
||||
describe('the rich Markdown toolbar', () => {
|
||||
it('routes named controls to their editor commands', () => {
|
||||
const onCommand = vi.fn()
|
||||
const buttons = render(true, onCommand)
|
||||
for (const [label, command] of [
|
||||
['Bold', 'bold'],
|
||||
['Link', 'link'],
|
||||
['Inline code', 'inlineCode']
|
||||
] as const) {
|
||||
onCommand.mockClear()
|
||||
const button = buttons.find((candidate) => candidate.props.accessibilityLabel === label)
|
||||
expect(button).toBeDefined()
|
||||
act(() => button!.props.onPress())
|
||||
expect(onCommand.mock.calls).toEqual([[command]])
|
||||
}
|
||||
})
|
||||
|
||||
it('disables every button against a document that cannot be edited', () => {
|
||||
const buttons = render(false, vi.fn())
|
||||
expect(buttons.filter((button) => button.props.disabled !== true)).toEqual([])
|
||||
})
|
||||
})
|
||||
@@ -72,34 +72,6 @@ describe('ProtocolBlockScreen', () => {
|
||||
renderer = null
|
||||
})
|
||||
|
||||
// Why: the protocol wall shipped before the bundle one; its copy is what users already see.
|
||||
it('keeps the existing protocol wall rendering unchanged', () => {
|
||||
const mobile = render({
|
||||
kind: 'blocked',
|
||||
reason: 'mobile-too-old',
|
||||
desktopVersion: 5,
|
||||
requiredMobileVersion: 99
|
||||
})
|
||||
expect(mobile).toContain('Update Orca Mobile')
|
||||
expect(mobile).toContain(
|
||||
'This desktop needs a newer Orca Mobile app. Update Orca Mobile from the App Store, then try this host again.'
|
||||
)
|
||||
expect(mobile).toContain('Open App Store')
|
||||
act(() => renderer?.unmount())
|
||||
|
||||
const desktop = render({
|
||||
kind: 'blocked',
|
||||
reason: 'desktop-too-old',
|
||||
desktopVersion: 0,
|
||||
requiredDesktopVersion: 2
|
||||
})
|
||||
expect(desktop).toContain('Update Orca on your computer')
|
||||
expect(desktop).toContain(
|
||||
'This paired desktop app is too old for your current Orca Mobile app. Update Orca on your computer, then try this host again.'
|
||||
)
|
||||
expect(desktop).toContain('Open GitHub Releases')
|
||||
})
|
||||
|
||||
it('tells a host without a bundle, or without this screen, the desktop is too old', () => {
|
||||
for (const reason of ['bundle-unavailable', 'page-route-unlisted'] as const) {
|
||||
const output = render({ kind: 'blocked', reason })
|
||||
@@ -112,12 +84,6 @@ describe('ProtocolBlockScreen', () => {
|
||||
}
|
||||
})
|
||||
|
||||
it('sends a screen that needs a grant this app lacks to the mobile update', () => {
|
||||
const output = render({ kind: 'blocked', reason: 'page-route-grant-missing' })
|
||||
expect(output).toContain('Update Orca Mobile')
|
||||
expect(output).toContain("This desktop's mobile workspace needs a newer Orca Mobile app.")
|
||||
})
|
||||
|
||||
it('sends an unknown manifest schema to the mobile update', () => {
|
||||
const output = render({
|
||||
kind: 'blocked',
|
||||
@@ -169,44 +135,13 @@ describe('ProtocolBlockScreen', () => {
|
||||
expect(primaryActionUrl()).toBe(RELEASES_URL)
|
||||
})
|
||||
|
||||
it('sends a desktop whose page is older than this shell to the desktop update', () => {
|
||||
const output = render({
|
||||
kind: 'blocked',
|
||||
reason: 'bundle-incompatible',
|
||||
side: 'desktop',
|
||||
pageVersion: 0,
|
||||
requiredPageVersion: 1
|
||||
})
|
||||
expect(output).toContain('Update Orca on your computer')
|
||||
expect(output).toContain('This paired desktop app is too old for your current Orca Mobile app')
|
||||
expect(primaryActionUrl()).toBe(RELEASES_URL)
|
||||
})
|
||||
|
||||
it('routes an Android bundle wall to GitHub Releases, not a store that has no listing', () => {
|
||||
nativeTestState.platform.OS = 'android'
|
||||
const output = render({
|
||||
kind: 'blocked',
|
||||
reason: 'bundle-shell-too-old',
|
||||
schemaVersion: 2
|
||||
})
|
||||
expect(output).toContain('Update Orca Mobile from GitHub Releases')
|
||||
expect(primaryActionUrl()).toBe(RELEASES_URL)
|
||||
})
|
||||
|
||||
it('keeps the update walls on two buttons and the full recovery note', () => {
|
||||
const output = render({ kind: 'blocked', reason: 'bundle-unavailable' })
|
||||
expect(output).toContain('Already updated? Go back to Hosts and refresh the connection.')
|
||||
// The presence precondition for the absence asserted on the refresh wall above.
|
||||
expect(pressableCount()).toBe(2)
|
||||
})
|
||||
|
||||
describe('with the newest release known', () => {
|
||||
const release = {
|
||||
version: '0.0.52',
|
||||
url: 'https://github.com/stablyai/orca/releases/tag/mobile-v0.0.52'
|
||||
}
|
||||
|
||||
it.each(['ios', 'android'] as const)('opens that exact release on %s', (os) => {
|
||||
it.each(['android'] as const)('opens that exact release on %s', (os) => {
|
||||
nativeTestState.platform.OS = os
|
||||
const output = render(
|
||||
{ kind: 'blocked', reason: 'bundle-shell-too-old', schemaVersion: 2 },
|
||||
|
||||
@@ -6,9 +6,11 @@ import {
|
||||
} from '../drafts/use-document-edit-draft'
|
||||
import { useClipboardWriter } from '../platform/clipboard'
|
||||
import { triggerError, triggerSuccess } from '../platform/haptics'
|
||||
import { useKeyboardOcclusion } from '../platform/keyboard-occlusion'
|
||||
import { spacing } from '../theme/mobile-theme'
|
||||
import { useSafeAreaInsets } from 'react-native-safe-area-context'
|
||||
import type { MobileFilePreviewSource } from './mobile-file-preview-request'
|
||||
import { resolveMarkdownFloatingActionsBottom } from './session-documents/markdown-floating-actions-layout'
|
||||
|
||||
/** Only terminal artifacts are editable in the file preview. */
|
||||
export function filePreviewEditDraftKey(
|
||||
@@ -43,10 +45,15 @@ function OfferBar(props: {
|
||||
}) {
|
||||
const clipboard = useClipboardWriter()
|
||||
const insets = useSafeAreaInsets()
|
||||
const keyboardHeight = useKeyboardOcclusion()
|
||||
return (
|
||||
<DocumentEditDraftOfferBar
|
||||
{...props}
|
||||
bottom={insets.bottom + spacing.lg}
|
||||
bottom={resolveMarkdownFloatingActionsBottom({
|
||||
keyboardLift: keyboardHeight,
|
||||
restingBottom: insets.bottom + spacing.lg,
|
||||
liftedClearance: spacing.md
|
||||
})}
|
||||
onCopy={() =>
|
||||
void clipboard.writeText(props.offer.content).then(triggerSuccess, triggerError)
|
||||
}
|
||||
|
||||
@@ -1,188 +0,0 @@
|
||||
import { useRef, useState } from 'react'
|
||||
import { ActivityIndicator, Pressable, Text, View } from 'react-native'
|
||||
import { ChevronDown, Keyboard as KeyboardIcon, RefreshCw } from 'lucide-react-native'
|
||||
import {
|
||||
MobileRichMarkdownEditor,
|
||||
type MobileRichMarkdownEditorHandle
|
||||
} from '../../components/MobileRichMarkdownEditor'
|
||||
import { colors, spacing, pressedStyle } from '../../theme/mobile-theme'
|
||||
import { useMobileColorScheme } from '../../theme/use-mobile-color-scheme'
|
||||
import {
|
||||
resolveMarkdownFloatingActionsBottom,
|
||||
shouldShowMarkdownFloatingActions
|
||||
} from './markdown-floating-actions-layout'
|
||||
import type { MarkdownDocState } from './session-document-state'
|
||||
import { styles } from '../../session/mobile-session-styles'
|
||||
import { MobileLoadErrorState, MobileStateView } from '../../components/MobileStateView'
|
||||
import { useMobileTranslation } from '../../i18n/use-mobile-translation'
|
||||
|
||||
type Props = {
|
||||
documentId: string
|
||||
doc: MarkdownDocState | undefined
|
||||
onRefresh: () => void
|
||||
onChange: (content: string) => void
|
||||
onSave: () => void
|
||||
onCopy: () => void
|
||||
onDiscard: () => void
|
||||
keyboardLift: number
|
||||
}
|
||||
|
||||
export function MobileMarkdownReader({
|
||||
documentId,
|
||||
doc,
|
||||
onRefresh,
|
||||
onChange,
|
||||
onSave,
|
||||
onCopy,
|
||||
onDiscard,
|
||||
keyboardLift
|
||||
}: Props) {
|
||||
useMobileColorScheme()
|
||||
const t = useMobileTranslation()
|
||||
const editorRef = useRef<MobileRichMarkdownEditorHandle>(null)
|
||||
// Native Keyboard events under-report the WebView editor's covered area, so prefer the larger WebView-measured inset.
|
||||
const [webviewKeyboardInset, setWebviewKeyboardInset] = useState(0)
|
||||
const effectiveKeyboardLift = Math.max(keyboardLift, webviewKeyboardInset)
|
||||
const keyboardOpen = effectiveKeyboardLift > 0
|
||||
|
||||
if (!doc || doc.status === 'loading') {
|
||||
return (
|
||||
<MobileStateView loading title={t('session.markdownReader.loading', 'Loading document…')} />
|
||||
)
|
||||
}
|
||||
if (doc.status === 'error') {
|
||||
return <MobileLoadErrorState error={doc.message} onRetry={onRefresh} />
|
||||
}
|
||||
|
||||
const statusText = doc.saveError
|
||||
? doc.saveError
|
||||
: doc.readOnlyReason
|
||||
? t('session.markdownReader.readOnly', 'Read only')
|
||||
: doc.stale
|
||||
? t('session.markdownReader.changedOnDesktop', 'Changed on desktop')
|
||||
: null
|
||||
const showRefresh = Boolean((doc.stale && !doc.isDirty) || !doc.editable)
|
||||
const showCopy = Boolean(doc.saveError || !doc.editable)
|
||||
const showSave = Boolean(doc.isDirty || doc.saving)
|
||||
const showFloatingActions = shouldShowMarkdownFloatingActions({
|
||||
keyboardLift: effectiveKeyboardLift,
|
||||
hasStatus: statusText != null,
|
||||
showRefresh,
|
||||
showCopy,
|
||||
showSave
|
||||
})
|
||||
|
||||
return (
|
||||
<View style={styles.markdownEditor}>
|
||||
<MobileRichMarkdownEditor
|
||||
ref={editorRef}
|
||||
key={documentId}
|
||||
content={doc.localContent}
|
||||
editable={doc.editable && !doc.saving}
|
||||
onChange={onChange}
|
||||
onKeyboardInsetChange={setWebviewKeyboardInset}
|
||||
/>
|
||||
{showFloatingActions ? (
|
||||
<View
|
||||
pointerEvents="box-none"
|
||||
style={[
|
||||
styles.markdownFloatingBar,
|
||||
// Why: editor focus lives in a WebView, so lift native Save/Discard controls instead of resizing it.
|
||||
{
|
||||
bottom: resolveMarkdownFloatingActionsBottom({
|
||||
keyboardLift: effectiveKeyboardLift,
|
||||
restingBottom: spacing.lg,
|
||||
liftedClearance: spacing.md
|
||||
})
|
||||
}
|
||||
]}
|
||||
>
|
||||
{statusText ? (
|
||||
<Text
|
||||
style={[styles.markdownFloatingStatus, doc.saveError ? styles.markdownError : null]}
|
||||
numberOfLines={2}
|
||||
>
|
||||
{statusText}
|
||||
</Text>
|
||||
) : null}
|
||||
<View style={styles.markdownFloatingActions}>
|
||||
{keyboardOpen ? (
|
||||
<Pressable
|
||||
style={({ pressed }) => [
|
||||
styles.markdownFloatingButton,
|
||||
styles.markdownKeyboardDismissButton,
|
||||
pressed && pressedStyle
|
||||
]}
|
||||
onPress={() => editorRef.current?.dismissKeyboard()}
|
||||
hitSlop={8}
|
||||
accessibilityRole="button"
|
||||
accessibilityLabel={t('session.markdownReader.dismissKeyboard', 'Dismiss keyboard')}
|
||||
accessibilityHint={t(
|
||||
'session.markdownReader.dismissKeyboardHint',
|
||||
'Hides the software keyboard and keeps the markdown editor open.'
|
||||
)}
|
||||
>
|
||||
<View style={styles.keyboardDismissGlyph}>
|
||||
<KeyboardIcon size={15} color={colors.textSecondary} strokeWidth={2} />
|
||||
<ChevronDown
|
||||
size={10}
|
||||
color={colors.textSecondary}
|
||||
strokeWidth={2.5}
|
||||
style={styles.keyboardDismissChevron}
|
||||
/>
|
||||
</View>
|
||||
</Pressable>
|
||||
) : null}
|
||||
{showCopy ? (
|
||||
<Pressable
|
||||
style={({ pressed }) => [styles.markdownFloatingButton, pressed && pressedStyle]}
|
||||
onPress={onCopy}
|
||||
>
|
||||
<Text style={styles.markdownFloatingButtonText}>{t('common.copy', 'Copy')}</Text>
|
||||
</Pressable>
|
||||
) : null}
|
||||
{showRefresh ? (
|
||||
<Pressable
|
||||
style={({ pressed }) => [styles.markdownFloatingButton, pressed && pressedStyle]}
|
||||
onPress={onRefresh}
|
||||
>
|
||||
<RefreshCw size={13} color={colors.textPrimary} />
|
||||
<Text style={styles.markdownFloatingButtonText}>
|
||||
{t('common.refresh', 'Refresh')}
|
||||
</Text>
|
||||
</Pressable>
|
||||
) : null}
|
||||
{doc.isDirty ? (
|
||||
<Pressable
|
||||
style={({ pressed }) => [styles.markdownFloatingButton, pressed && pressedStyle]}
|
||||
onPress={onDiscard}
|
||||
>
|
||||
<Text style={styles.markdownFloatingButtonText}>
|
||||
{t('session.markdownReader.discard', 'Discard')}
|
||||
</Text>
|
||||
</Pressable>
|
||||
) : null}
|
||||
{showSave ? (
|
||||
<Pressable
|
||||
style={({ pressed }) => [
|
||||
styles.markdownFloatingButton,
|
||||
styles.markdownSaveButton,
|
||||
(!doc.editable || !doc.isDirty || doc.saving) && styles.markdownButtonDisabled,
|
||||
pressed && pressedStyle
|
||||
]}
|
||||
disabled={!doc.editable || !doc.isDirty || doc.saving}
|
||||
onPress={onSave}
|
||||
>
|
||||
{doc.saving ? (
|
||||
<ActivityIndicator size="small" color={colors.textPrimary} />
|
||||
) : (
|
||||
<Text style={styles.markdownFloatingButtonText}>{t('common.save', 'Save')}</Text>
|
||||
)}
|
||||
</Pressable>
|
||||
) : null}
|
||||
</View>
|
||||
</View>
|
||||
) : null}
|
||||
</View>
|
||||
)
|
||||
}
|
||||
@@ -9,19 +9,3 @@ export function resolveMarkdownFloatingActionsBottom({
|
||||
}): number {
|
||||
return keyboardLift > 0 ? keyboardLift + liftedClearance : restingBottom
|
||||
}
|
||||
|
||||
export function shouldShowMarkdownFloatingActions({
|
||||
keyboardLift,
|
||||
hasStatus,
|
||||
showRefresh,
|
||||
showCopy,
|
||||
showSave
|
||||
}: {
|
||||
keyboardLift: number
|
||||
hasStatus: boolean
|
||||
showRefresh: boolean
|
||||
showCopy: boolean
|
||||
showSave: boolean
|
||||
}): boolean {
|
||||
return keyboardLift > 0 || hasStatus || showRefresh || showCopy || showSave
|
||||
}
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import { translate } from '../../i18n/mobile-i18n'
|
||||
import { formatPreviewByteLength } from '../mobile-file-preview-response'
|
||||
import type { MarkdownDocState } from './session-document-state'
|
||||
|
||||
@@ -9,11 +10,17 @@ export function markdownReaderStatusText(
|
||||
}
|
||||
if (doc.truncated) {
|
||||
return doc.byteLength === undefined
|
||||
? 'Preview truncated.'
|
||||
: `Preview truncated. File size: ${formatPreviewByteLength(doc.byteLength)}.`
|
||||
? translate('session.markdownReader.previewTruncated', 'Preview truncated.')
|
||||
: translate(
|
||||
'files.filePreviewSourceText.truncatedNote',
|
||||
'Preview truncated. File size: {{size}}.',
|
||||
{ size: formatPreviewByteLength(doc.byteLength) }
|
||||
)
|
||||
}
|
||||
if (doc.readOnlyReason) {
|
||||
return 'Read only'
|
||||
return translate('session.markdownReader.readOnly', 'Read only')
|
||||
}
|
||||
return doc.stale ? 'Changed on desktop' : null
|
||||
return doc.stale
|
||||
? translate('session.markdownReader.changedOnDesktop', 'Changed on desktop')
|
||||
: null
|
||||
}
|
||||
|
||||
@@ -29,6 +29,7 @@ import { useOpenMobileHostEdit } from '../host-screen/use-open-mobile-host-edit'
|
||||
import { mobileConnectionPathLabel } from '../transport/connection/mobile-connection-path-label'
|
||||
import { newWorkspaceOverlayHref } from '../new-workspace/new-workspace-overlay-route'
|
||||
import { useMobileHomeData } from './use-mobile-home-data'
|
||||
import { useHomeSparePage } from './use-home-spare-page'
|
||||
import { HOME_TABS, type HomeTabId } from './tabs/home-tabs'
|
||||
import { MobileHomeAgentsTab } from './tabs/MobileHomeAgentsTab'
|
||||
import { MobileHomeAutomationsTab } from './tabs/MobileHomeAutomationsTab'
|
||||
@@ -45,6 +46,7 @@ export function MobileHomeScreen() {
|
||||
const t = useMobileTranslation()
|
||||
useMobileColorScheme()
|
||||
const data = useMobileHomeData()
|
||||
useHomeSparePage(data.hostCatalogLoaded ? data.sortedHosts.map((host) => host.id) : [])
|
||||
const insets = useSafeAreaInsets()
|
||||
const openMobileHostEdit = useOpenMobileHostEdit()
|
||||
const openMobileTasks = useOpenMobileTasks()
|
||||
|
||||
@@ -0,0 +1,48 @@
|
||||
import { useFocusEffect } from 'expo-router'
|
||||
import { useCallback } from 'react'
|
||||
import { AppState } from 'react-native'
|
||||
import { setForegroundTimer } from '../mobile-web-shell/foreground-timer'
|
||||
import {
|
||||
enterHomeSparePage,
|
||||
leaveHomeSparePage,
|
||||
prepareHomeSparePage
|
||||
} from '../mobile-web-shell/home-spare-page'
|
||||
import { processGenerationStore } from '../mobile-web-shell/process-generation-store'
|
||||
|
||||
// Past Home's first paint and its first reads, so the boot never competes with them.
|
||||
const HOME_SPARE_IDLE_MS = 1000
|
||||
|
||||
const HOST_ID_SEPARATOR = '\n'
|
||||
|
||||
// While Home is shown, keep one page booted for the most recently connected host with a cached build.
|
||||
// Native drops it when the app leaves the foreground, so every return to it arms again.
|
||||
export function useHomeSparePage(hostIds: readonly string[]): void {
|
||||
const hosts = hostIds.join(HOST_ID_SEPARATOR)
|
||||
useFocusEffect(
|
||||
useCallback(() => {
|
||||
if (hosts === '') {
|
||||
return undefined
|
||||
}
|
||||
enterHomeSparePage()
|
||||
let cancelTimer = (): void => undefined
|
||||
const arm = (): void => {
|
||||
cancelTimer()
|
||||
cancelTimer = setForegroundTimer(
|
||||
() => void prepareHomeSparePage(processGenerationStore(), hosts.split(HOST_ID_SEPARATOR)),
|
||||
HOME_SPARE_IDLE_MS
|
||||
)
|
||||
}
|
||||
arm()
|
||||
const subscription = AppState.addEventListener('change', (state) => {
|
||||
if (state === 'active') {
|
||||
arm()
|
||||
}
|
||||
})
|
||||
return () => {
|
||||
subscription.remove()
|
||||
cancelTimer()
|
||||
leaveHomeSparePage()
|
||||
}
|
||||
}, [hosts])
|
||||
)
|
||||
}
|
||||
@@ -1,5 +1,10 @@
|
||||
import * as z from 'zod'
|
||||
import { getRepoExecutionHostId, parseExecutionHostId } from '../../../src/shared/execution-host'
|
||||
import {
|
||||
getRepoExecutionHostId,
|
||||
parseExecutionHostId,
|
||||
type ExecutionHostId
|
||||
} from '../../../src/shared/execution-host'
|
||||
import { MOBILE_RELAY_HOST_WORKTREE_DELTAS_RUNTIME_CAPABILITY } from '../../../src/shared/mobile-desktop-relay-contract'
|
||||
import type { MobileRelayHost } from '../../../src/shared/remote-runtime/relay/mobile-relay-hosts-contract'
|
||||
import type { Query, QueryClient } from '@tanstack/react-query'
|
||||
import { defineHostQuery } from '../query/host-query'
|
||||
@@ -18,8 +23,13 @@ import {
|
||||
} from '../worktree/worktree-catalog-snapshot-client'
|
||||
import type { Worktree } from '../worktree/workspace-list-types'
|
||||
import { getCachedWorktrees } from '../cache/worktree-cache'
|
||||
import { hostRepoCatalogRepos, type HostRepoCatalogRow } from './host-screen-reply-schema'
|
||||
import {
|
||||
hostRepoCatalogRepos,
|
||||
hostSshTargetSummarySchema,
|
||||
type HostRepoCatalogRow
|
||||
} from './host-screen-reply-schema'
|
||||
import { hostPlatformRead, hostRepoCatalogSnapshotRead } from './host-screen-operations'
|
||||
import { NODE_PLATFORM_NAMES } from '../transport/connection/mobile-runtime-host-platform'
|
||||
import {
|
||||
acceptedMetadata,
|
||||
readHostSshTargetLabels,
|
||||
@@ -119,6 +129,18 @@ const serverRowSnapshots = {
|
||||
full: new ServerRowSnapshots(false)
|
||||
}
|
||||
|
||||
/**
|
||||
* The server rows' input. Before the host's status is read it names the key a current desktop stores them
|
||||
* under, so they paint from the store: the page came from that desktop, which sends the deltas capability.
|
||||
*/
|
||||
export function hostServerWorkspacesInput(hostCapabilities: readonly string[] | null): {
|
||||
deltas: boolean
|
||||
} {
|
||||
return {
|
||||
deltas: hostCapabilities?.includes(MOBILE_RELAY_HOST_WORKTREE_DELTAS_RUNTIME_CAPABILITY) ?? true
|
||||
}
|
||||
}
|
||||
|
||||
// Workspaces on the servers this desktop relays to; a server whose read fails keeps its rows.
|
||||
export const hostServerWorkspacesQuery = defineHostQuery<{ deltas: boolean }, ServerWorkspaces>({
|
||||
family: 'relayHosts.workspaces',
|
||||
@@ -187,10 +209,18 @@ export function catalogNeedsHostLabels(catalog: readonly HostRepoCatalogRow[]):
|
||||
return hostIds.size > 1 || [...hostIds].some((id) => parseExecutionHostId(id)?.kind === 'ssh')
|
||||
}
|
||||
|
||||
export type HostRepoLabels = Awaited<ReturnType<typeof readHostSshTargetLabels>> & {
|
||||
export type HostRepoLabels = {
|
||||
sshTargetSummaries: z.output<typeof hostSshTargetSummarySchema>[]
|
||||
// Entries rather than a Map, so the record can be stored.
|
||||
hostLabels: [ExecutionHostId, string][]
|
||||
platform: NodeJS.Platform | null
|
||||
}
|
||||
|
||||
const storedHostLabelSchema = z.tuple([
|
||||
z.custom<ExecutionHostId>((id) => typeof id === 'string' && parseExecutionHostId(id) !== null),
|
||||
z.string()
|
||||
])
|
||||
|
||||
export const hostRepoLabelsQuery = defineHostQuery<typeof NO_HOST_LIST_INPUT, HostRepoLabels>({
|
||||
family: 'repo.hostLabels',
|
||||
fetch: async (client) => {
|
||||
@@ -198,13 +228,25 @@ export const hostRepoLabelsQuery = defineHostQuery<typeof NO_HOST_LIST_INPUT, Ho
|
||||
readHostSshTargetLabels(client),
|
||||
settledMetadataReply(() => hostPlatformRead.request(client))
|
||||
])
|
||||
return { ...labels, platform: acceptedMetadata(platform, hostPlatformRead.interpret) ?? null }
|
||||
return {
|
||||
sshTargetSummaries: labels.sshTargetSummaries,
|
||||
hostLabels: [...labels.hostLabelById],
|
||||
platform: acceptedMetadata(platform, hostPlatformRead.interpret) ?? null
|
||||
}
|
||||
},
|
||||
staleTime: 60_000,
|
||||
gcTime: 30 * 60_000,
|
||||
refetchOnWindowFocus: true,
|
||||
// SSH health and the host's own label overrides.
|
||||
signal: { events: ['reposChanged', 'sshStateChanged'] }
|
||||
signal: { events: ['reposChanged', 'sshStateChanged'] },
|
||||
persist: {
|
||||
version: 1,
|
||||
dataSchema: z.object({
|
||||
sshTargetSummaries: z.array(hostSshTargetSummarySchema),
|
||||
hostLabels: z.array(storedHostLabelSchema),
|
||||
platform: z.enum(NODE_PLATFORM_NAMES).nullable()
|
||||
})
|
||||
}
|
||||
})
|
||||
|
||||
// The host list's own reads, which pull to refresh repeats; project.sections lives with its hook.
|
||||
|
||||
@@ -83,20 +83,17 @@ export const hostRepoCatalogSnapshotSchema = z.union([
|
||||
])
|
||||
|
||||
// Keep target parsing total: absent/malformed targets yield [] and labels degrade to host ids on older hosts. A throw here would also skip the subsequent platform write.
|
||||
export const hostSshTargetSummarySchema = z.looseObject({
|
||||
id: z.string(),
|
||||
label: z.string(),
|
||||
// Read raw: an arm a newer desktop adds must leave the badge as it is, not read as a verdict.
|
||||
connected: salvagedOptional('connected', z.boolean()),
|
||||
connectionStatus: salvagedOptional('connectionStatus', z.string())
|
||||
})
|
||||
|
||||
export const hostSshTargetSummariesSchema = z
|
||||
.looseObject({
|
||||
targets: salvagedOptional(
|
||||
'targets',
|
||||
salvagingArray(
|
||||
z.looseObject({
|
||||
id: z.string(),
|
||||
label: z.string(),
|
||||
// Read raw: an arm a newer desktop adds must leave the badge as it is, not read as a verdict.
|
||||
connected: salvagedOptional('connected', z.boolean()),
|
||||
connectionStatus: salvagedOptional('connectionStatus', z.string())
|
||||
})
|
||||
)
|
||||
)
|
||||
targets: salvagedOptional('targets', salvagingArray(hostSshTargetSummarySchema))
|
||||
})
|
||||
.transform((reply) => reply.targets ?? [])
|
||||
.catch(() => [])
|
||||
|
||||
@@ -66,7 +66,7 @@ export function useHostRepoMetadata(args: {
|
||||
useEffect(() => {
|
||||
if (needsLabels && labels.data) {
|
||||
setHostHealthById(buildSshHostHealthById(labels.data.sshTargetSummaries))
|
||||
setHostLabelById(labels.data.hostLabelById)
|
||||
setHostLabelById(new Map(labels.data.hostLabels))
|
||||
setHostPlatform(labels.data.platform)
|
||||
} else if (repos.data && !needsLabels) {
|
||||
// Clear labels for departed hosts so stale metadata cannot badge remaining rows.
|
||||
|
||||
@@ -60,7 +60,8 @@ export function useHostScreenController({
|
||||
const relayRecovery = useRelayRecoveryStatus(hostId)
|
||||
const forgetHostClient = useForgetHostClient()
|
||||
const forceReconnectHost = useForceReconnect()
|
||||
const { hostCapabilities, floatingWorkspaceEnabled, hostInstallationId } = useHostProtocolGates()
|
||||
const { hostCapabilities, statusReadable, floatingWorkspaceEnabled, hostInstallationId } =
|
||||
useHostProtocolGates()
|
||||
const state = useHostScreenState(hostId, peekStoredHost(hostId))
|
||||
const settings = useHostViewSettings({ client, connState, state })
|
||||
const connectionVerdict = classifyConnection({
|
||||
@@ -83,6 +84,7 @@ export function useHostScreenController({
|
||||
connState,
|
||||
embedded,
|
||||
hostCapabilities,
|
||||
hostStatusReadable: statusReadable,
|
||||
hostId,
|
||||
sidebarFeed: sidebarFeed?.triggers ?? null,
|
||||
state,
|
||||
|
||||
@@ -1,4 +1,3 @@
|
||||
import { MOBILE_RELAY_HOST_WORKTREE_DELTAS_RUNTIME_CAPABILITY } from '../../../src/shared/mobile-desktop-relay-contract'
|
||||
import { WORKTREE_ROWS_CHANGED_EVENT_RUNTIME_CAPABILITY } from '../../../src/shared/worktree-runtime-capabilities'
|
||||
import { readWorktreeFirstPage } from '../worktree/worktree-catalog-first-page'
|
||||
import type { Worktree } from '../worktree/workspace-list-types'
|
||||
@@ -32,6 +31,7 @@ import {
|
||||
HOST_LIST_BACKSTOP_POLL_MS,
|
||||
HOST_LIST_POLL_MS,
|
||||
HOST_LIST_TARGET,
|
||||
hostServerWorkspacesInput,
|
||||
hostServerWorkspacesQuery,
|
||||
hostWorktreeCatalogKey,
|
||||
hostWorktreeCatalogQuery,
|
||||
@@ -54,6 +54,8 @@ export function useHostWorktreeCatalog(args: {
|
||||
connState: ConnectionState
|
||||
embedded: boolean
|
||||
hostCapabilities: readonly string[]
|
||||
// Whether the host answered its status: capabilities are unknown, not absent, until it has.
|
||||
hostStatusReadable: boolean
|
||||
hostId: string | undefined
|
||||
sidebarFeed: HostSidebarFeedTriggers | null
|
||||
state: HostScreenState
|
||||
@@ -64,6 +66,7 @@ export function useHostWorktreeCatalog(args: {
|
||||
connState,
|
||||
embedded,
|
||||
hostCapabilities,
|
||||
hostStatusReadable,
|
||||
hostId,
|
||||
sidebarFeed,
|
||||
state,
|
||||
@@ -117,11 +120,13 @@ export function useHostWorktreeCatalog(args: {
|
||||
)
|
||||
// An older desktop or shell lists no server rows, rather than rows that could not open.
|
||||
const relays = client !== null && relaysToServers(client, hostCapabilities)
|
||||
// Until the host's status is read, stored server rows paint and nothing reads them.
|
||||
const relaysRuledOut = hostStatusReadable && !relays
|
||||
const servers = useHostQuery(
|
||||
hostServerWorkspacesQuery,
|
||||
host,
|
||||
HOST_LIST_TARGET,
|
||||
{ deltas: hostCapabilities.includes(MOBILE_RELAY_HOST_WORKTREE_DELTAS_RUNTIME_CAPABILITY) },
|
||||
hostServerWorkspacesInput(hostStatusReadable ? hostCapabilities : null),
|
||||
// Execution hosts' notices are not relayed, so server rows keep the full poll.
|
||||
{ enabled: !!hostId && relays, subscribed, refetchInterval: pollMs }
|
||||
)
|
||||
@@ -210,12 +215,13 @@ export function useHostWorktreeCatalog(args: {
|
||||
}, [catalog.status, catalog.errorUpdatedAt])
|
||||
|
||||
useEffect(() => {
|
||||
if (!relays) {
|
||||
setServerWorkspaces(NO_SERVER_WORKSPACES)
|
||||
} else if (servers.data) {
|
||||
if (servers.data && !relaysRuledOut) {
|
||||
setServerWorkspaces(servers.data)
|
||||
} else if (!relays) {
|
||||
// Also drops a previous host's rows when the sidebar switches to one with none stored.
|
||||
setServerWorkspaces(NO_SERVER_WORKSPACES)
|
||||
}
|
||||
}, [relays, servers.data])
|
||||
}, [relays, relaysRuledOut, servers.data])
|
||||
|
||||
const fetchWorktrees = useCallback(
|
||||
async (options: { allowDuringModal?: boolean } = {}) => {
|
||||
|
||||
@@ -2193,8 +2193,7 @@
|
||||
"copyPathLabel": "Pfad der Markdown-Datei kopieren",
|
||||
"copySource": "Markdown-Quelltext kopieren",
|
||||
"discard": "Verwerfen",
|
||||
"dismissKeyboard": "Tastatur ausblenden",
|
||||
"dismissKeyboardHint": "Blendet die Bildschirmtastatur aus und lässt den Markdown-Editor geöffnet.",
|
||||
"previewTruncated": "Vorschau gekürzt.",
|
||||
"readOnly": "Schreibgeschützt"
|
||||
},
|
||||
"nativeChatAttachActions": {
|
||||
|
||||
@@ -1962,8 +1962,7 @@
|
||||
"markdownReader": {
|
||||
"readOnly": "Read only",
|
||||
"changedOnDesktop": "Changed on desktop",
|
||||
"dismissKeyboard": "Dismiss keyboard",
|
||||
"dismissKeyboardHint": "Hides the software keyboard and keeps the markdown editor open.",
|
||||
"previewTruncated": "Preview truncated.",
|
||||
"discard": "Discard",
|
||||
"copyLoadedSource": "Copy loaded Markdown source",
|
||||
"copySource": "Copy Markdown source",
|
||||
|
||||
@@ -2260,8 +2260,7 @@
|
||||
"copyPathLabel": "Copiar la ruta del archivo Markdown",
|
||||
"copySource": "Copiar el código fuente Markdown",
|
||||
"discard": "Descartar",
|
||||
"dismissKeyboard": "Ocultar teclado",
|
||||
"dismissKeyboardHint": "Oculta el teclado en pantalla y mantiene abierto el editor de Markdown.",
|
||||
"previewTruncated": "Vista previa truncada.",
|
||||
"readOnly": "Solo lectura"
|
||||
},
|
||||
"nativeChatAttachActions": {
|
||||
|
||||
@@ -2260,8 +2260,7 @@
|
||||
"copyPathLabel": "Copier le chemin du fichier Markdown",
|
||||
"copySource": "Copier la source Markdown",
|
||||
"discard": "Abandonner",
|
||||
"dismissKeyboard": "Masquer le clavier",
|
||||
"dismissKeyboardHint": "Masque le clavier virtuel et laisse l'éditeur Markdown ouvert.",
|
||||
"previewTruncated": "Aperçu tronqué.",
|
||||
"readOnly": "Lecture seule"
|
||||
},
|
||||
"nativeChatAttachActions": {
|
||||
|
||||
@@ -2189,8 +2189,7 @@
|
||||
"copyPathLabel": "Markdown ファイルのパスをコピー",
|
||||
"copySource": "Markdown ソースをコピー",
|
||||
"discard": "破棄",
|
||||
"dismissKeyboard": "キーボードを閉じる",
|
||||
"dismissKeyboardHint": "Markdown エディターを開いたまま、ソフトウェアキーボードを非表示にします。",
|
||||
"previewTruncated": "プレビューは一部省略されています。",
|
||||
"readOnly": "読み取り専用"
|
||||
},
|
||||
"nativeChatAttachActions": {
|
||||
|
||||
@@ -2189,8 +2189,7 @@
|
||||
"copyPathLabel": "Markdown 경로 복사",
|
||||
"copySource": "Markdown 소스 복사",
|
||||
"discard": "버리기",
|
||||
"dismissKeyboard": "키보드 닫기",
|
||||
"dismissKeyboardHint": "소프트웨어 키보드를 숨기고 Markdown 편집기를 열린 상태로 유지합니다.",
|
||||
"previewTruncated": "미리보기가 일부만 표시됩니다.",
|
||||
"readOnly": "읽기 전용"
|
||||
},
|
||||
"nativeChatAttachActions": {
|
||||
|
||||
@@ -2260,8 +2260,7 @@
|
||||
"copyPathLabel": "Copiar caminho do arquivo Markdown",
|
||||
"copySource": "Copiar código-fonte Markdown",
|
||||
"discard": "Descartar",
|
||||
"dismissKeyboard": "Ocultar teclado",
|
||||
"dismissKeyboardHint": "Oculta o teclado virtual e mantém o editor Markdown aberto.",
|
||||
"previewTruncated": "Pré-visualização truncada.",
|
||||
"readOnly": "Somente leitura"
|
||||
},
|
||||
"nativeChatAttachActions": {
|
||||
|
||||
@@ -2327,8 +2327,7 @@
|
||||
"copyPathLabel": "Скопировать путь к файлу Markdown",
|
||||
"copySource": "Скопировать исходный текст Markdown",
|
||||
"discard": "Отменить изменения",
|
||||
"dismissKeyboard": "Скрыть клавиатуру",
|
||||
"dismissKeyboardHint": "Скрывает экранную клавиатуру и оставляет редактор Markdown открытым.",
|
||||
"previewTruncated": "Показана часть файла.",
|
||||
"readOnly": "Только чтение"
|
||||
},
|
||||
"nativeChatAttachActions": {
|
||||
|
||||
@@ -2193,8 +2193,7 @@
|
||||
"copyPathLabel": "Markdown yolunu kopyala",
|
||||
"copySource": "Markdown kaynağını kopyala",
|
||||
"discard": "Vazgeç",
|
||||
"dismissKeyboard": "Klavyeyi gizle",
|
||||
"dismissKeyboardHint": "Ekran klavyesini gizler ve Markdown düzenleyicisini açık tutar.",
|
||||
"previewTruncated": "Önizleme kısaltıldı.",
|
||||
"readOnly": "Salt okunur"
|
||||
},
|
||||
"nativeChatAttachActions": {
|
||||
|
||||
@@ -2189,8 +2189,7 @@
|
||||
"copyPathLabel": "複製 Markdown 路徑",
|
||||
"copySource": "複製 Markdown 原始碼",
|
||||
"discard": "放棄",
|
||||
"dismissKeyboard": "收起鍵盤",
|
||||
"dismissKeyboardHint": "隱藏螢幕鍵盤,並保持 Markdown 編輯器開啟。",
|
||||
"previewTruncated": "預覽內容已截斷。",
|
||||
"readOnly": "唯讀"
|
||||
},
|
||||
"nativeChatAttachActions": {
|
||||
|
||||
@@ -2189,8 +2189,7 @@
|
||||
"copyPathLabel": "复制 Markdown 文件路径",
|
||||
"copySource": "复制 Markdown 源码",
|
||||
"discard": "放弃",
|
||||
"dismissKeyboard": "关闭键盘",
|
||||
"dismissKeyboardHint": "隐藏软键盘,并保持 Markdown 编辑器打开。",
|
||||
"previewTruncated": "预览已截断。",
|
||||
"readOnly": "只读"
|
||||
},
|
||||
"nativeChatAttachActions": {
|
||||
|
||||
@@ -20,6 +20,7 @@ export type BridgeInboundFramePort = {
|
||||
acceptState: (connection: BridgeConnectionSnapshot) => void
|
||||
acceptConnectionPath: (connection: BridgeConnectionSnapshot) => void
|
||||
acceptBack: () => void
|
||||
acceptParked: () => void
|
||||
acceptTerminalKey: (key: BridgeTerminalKeyId, inputOwner?: string) => void
|
||||
}
|
||||
|
||||
@@ -66,6 +67,9 @@ export function createBridgeInboundFrameReader(
|
||||
case 'back':
|
||||
port.acceptBack()
|
||||
return
|
||||
case 'parked':
|
||||
port.acceptParked()
|
||||
return
|
||||
case 'terminalKey':
|
||||
port.acceptTerminalKey(message.key, message.inputOwner)
|
||||
return
|
||||
|
||||
@@ -236,6 +236,8 @@ const BridgeHostMessageSchema = z.union([
|
||||
}),
|
||||
// Back names no destination; only the native stack knows what screen lies beneath.
|
||||
z.object({ v: versionSchema, type: z.literal(BRIDGE_BACK_FRAME) }),
|
||||
// Native booted this page ahead of its screen and keeps its ready for the screen that adopts it.
|
||||
z.object({ v: versionSchema, type: z.literal('parked') }),
|
||||
// One press on the shell's key rail. Sent only to a page granted the rail, which knows the frame.
|
||||
z.object({
|
||||
v: versionSchema,
|
||||
|
||||
@@ -198,6 +198,8 @@ export function createBridgeRpcClient(options: BridgeRpcClientOptions): BridgeRp
|
||||
acceptState: (connection) => acceptState(cache.apply(connection)),
|
||||
acceptConnectionPath: (connection) => acceptState(cache.applyPath(connection)),
|
||||
acceptBack: back.press,
|
||||
// Only a page booted before its screen, with no init yet, is parked; the shell answers its ready on adoption.
|
||||
acceptParked: handshake.stop,
|
||||
acceptTerminalKey: (key, inputOwner) => terminalKeys.accept(key, inputOwner)
|
||||
})
|
||||
|
||||
|
||||
@@ -0,0 +1,27 @@
|
||||
import { joinUri } from './generation-cache-uri'
|
||||
import type { GenerationDirectoryEntry, GenerationFileSystem } from './generation-store-file-system'
|
||||
import { isHostCacheKey } from './host-cache-key'
|
||||
|
||||
export const GENERATIONS_DIRECTORY_NAME = 'generations'
|
||||
|
||||
// One directory per host under the cache root; anything else there is not the store's.
|
||||
export async function listGenerationHostDirectories(
|
||||
fs: GenerationFileSystem
|
||||
): Promise<readonly GenerationDirectoryEntry[]> {
|
||||
const entries = await fs.list(fs.rootUri)
|
||||
return entries.filter((entry) => entry.isDirectory && isHostCacheKey(entry.name))
|
||||
}
|
||||
|
||||
// Count/evict only hosts with generations; evicting staged-only hosts would delete a tree awaiting commit. Sweeps still visit them.
|
||||
export async function listActivatedGenerationHosts(
|
||||
fs: GenerationFileSystem
|
||||
): Promise<readonly string[]> {
|
||||
const activated: string[] = []
|
||||
for (const host of await listGenerationHostDirectories(fs)) {
|
||||
const generations = await fs.list(joinUri(fs.rootUri, host.name, GENERATIONS_DIRECTORY_NAME))
|
||||
if (generations.some((entry) => entry.isDirectory)) {
|
||||
activated.push(host.name)
|
||||
}
|
||||
}
|
||||
return activated
|
||||
}
|
||||
@@ -544,4 +544,22 @@ describe('an update staged behind a live page', () => {
|
||||
expect((await relaunched.readActiveGeneration(HOST))?.buildId).toBe(SECOND_BUILD)
|
||||
expect(await fs.fileExists(`${ROOT}/${HOST}/generations/${SECOND_BUILD}/index.html`)).toBe(true)
|
||||
})
|
||||
|
||||
it('lets a reader of a host’s build go before a commit or a removal deletes it', async () => {
|
||||
const fs = createFakeFileSystem()
|
||||
const onDisk: boolean[] = []
|
||||
let reading = BUILD
|
||||
const store = createGenerationStore({
|
||||
fileSystem: fs,
|
||||
beforeHostFilesDeleted: async (hostKey) => {
|
||||
onDisk.push(await fs.fileExists(`${ROOT}/${hostKey}/generations/${reading}/manifest.json`))
|
||||
}
|
||||
})
|
||||
await activate(store, HOST)
|
||||
onDisk.length = 0
|
||||
await activate(store, HOST, buildResult(SECOND))
|
||||
reading = SECOND_BUILD
|
||||
await store.deleteHostCache(HOST)
|
||||
expect(onDisk).toEqual([true, true])
|
||||
})
|
||||
})
|
||||
|
||||
@@ -10,7 +10,12 @@ import { MANIFEST_FILE_NAME } from './generation-asset-path'
|
||||
import { parseGenerationManifest, readWaitingStage } from './generation-manifest-read'
|
||||
import { reusableAssetsOf, reusableAssetsOfHosts } from './generation-reuse'
|
||||
import { stagingAssetsOf } from './generation-staging-assets'
|
||||
import type { GenerationDirectoryEntry, GenerationFileSystem } from './generation-store-file-system'
|
||||
import type { GenerationFileSystem } from './generation-store-file-system'
|
||||
import {
|
||||
GENERATIONS_DIRECTORY_NAME,
|
||||
listActivatedGenerationHosts,
|
||||
listGenerationHostDirectories
|
||||
} from './generation-host-directories'
|
||||
import { isHostCacheKey } from './host-cache-key'
|
||||
import type { MobileWebShellUpdateFailure } from './mobile-web-shell-update-failure'
|
||||
import {
|
||||
@@ -19,7 +24,6 @@ import {
|
||||
recordUpdateFailureIn
|
||||
} from './mobile-web-shell-update-failure-log'
|
||||
|
||||
const GENERATIONS_DIRECTORY_NAME = 'generations'
|
||||
const STAGING_DIRECTORY_NAME = 'tmp'
|
||||
|
||||
export const MAX_CACHED_HOSTS = 6
|
||||
@@ -66,6 +70,8 @@ export type GenerationStore = {
|
||||
|
||||
export function createGenerationStore(options: {
|
||||
fileSystem: GenerationFileSystem
|
||||
// Runs before a host's built files are deleted, so nothing still reading them outlives them.
|
||||
beforeHostFilesDeleted?: (hostKey: string) => Promise<void>
|
||||
}): GenerationStore {
|
||||
const fs = options.fileSystem
|
||||
const hostOrder = createGenerationHostOrder(fs)
|
||||
@@ -87,31 +93,15 @@ export function createGenerationStore(options: {
|
||||
const stagingRoot = (hostKey: string): string =>
|
||||
joinUri(hostRoot(hostKey), STAGING_DIRECTORY_NAME)
|
||||
|
||||
async function listHostDirectories(): Promise<readonly GenerationDirectoryEntry[]> {
|
||||
const entries = await fs.list(fs.rootUri)
|
||||
return entries.filter((entry) => entry.isDirectory && isHostCacheKey(entry.name))
|
||||
}
|
||||
|
||||
// Count/evict only hosts with generations; evicting staged-only hosts would delete a tree awaiting commit. Sweeps still visit them.
|
||||
async function listActivatedHosts(): Promise<readonly string[]> {
|
||||
const activated: string[] = []
|
||||
for (const host of await listHostDirectories()) {
|
||||
const generations = await fs.list(joinUri(fs.rootUri, host.name, GENERATIONS_DIRECTORY_NAME))
|
||||
if (generations.some((entry) => entry.isDirectory)) {
|
||||
activated.push(host.name)
|
||||
}
|
||||
}
|
||||
return activated
|
||||
}
|
||||
|
||||
async function dropHostTree(hostKey: string): Promise<void> {
|
||||
activeMemo.delete(hostKey)
|
||||
deferred.drop(hostKey)
|
||||
await options.beforeHostFilesDeleted?.(hostKey)
|
||||
await fs.delete(hostRoot(hostKey))
|
||||
}
|
||||
|
||||
async function enforceHostLimit(order: readonly string[]): Promise<void> {
|
||||
const hosts = await listActivatedHosts()
|
||||
const hosts = await listActivatedGenerationHosts(fs)
|
||||
// Unlisted hosts sort first after index loss; keep the just-activated host last so it survives eviction.
|
||||
const evicted = new Set(
|
||||
[...hosts]
|
||||
@@ -238,6 +228,7 @@ export function createGenerationStore(options: {
|
||||
if (!(await fs.fileExists(joinUri(staged.directory, MANIFEST_FILE_NAME)))) {
|
||||
throw new Error(`staged generation ${staged.buildId} is no longer on disk`)
|
||||
}
|
||||
await options.beforeHostFilesDeleted?.(staged.hostKey)
|
||||
// Delete old generations before rename: a crash then leaves no activation, whereas renaming first can leave two with no way to choose.
|
||||
for (const entry of entries) {
|
||||
await fs.delete(joinUri(generations, entry.name))
|
||||
@@ -276,7 +267,9 @@ export function createGenerationStore(options: {
|
||||
async function openReusable(hostKey: string): Promise<MobileWebBundleReusableAssets> {
|
||||
const hosts = [
|
||||
hostKey,
|
||||
...(await listHostDirectories()).map((host) => host.name).filter((key) => key !== hostKey)
|
||||
...(await listGenerationHostDirectories(fs))
|
||||
.map((host) => host.name)
|
||||
.filter((key) => key !== hostKey)
|
||||
]
|
||||
// Reuse discovery must not clean up another shell's active or staged files.
|
||||
const reusable = await reusableAssetsOfHosts(fs, hosts, (key) => readActive(key, false))
|
||||
@@ -290,7 +283,7 @@ export function createGenerationStore(options: {
|
||||
return
|
||||
}
|
||||
// Interrupted downloads may belong to a host this launch never opens, so visit every host's tmp tree.
|
||||
for (const host of await listHostDirectories()) {
|
||||
for (const host of await listGenerationHostDirectories(fs)) {
|
||||
// Unreadable (undefined) is not corrupt: leave that tree for a later launch rather than fail every read.
|
||||
const waiting = await readWaitingStage(fs, host.name, stagingRoot(host.name)).catch(
|
||||
() => undefined
|
||||
|
||||
@@ -0,0 +1,91 @@
|
||||
import {
|
||||
claimSpareDocument,
|
||||
discardSpareDocument,
|
||||
prepareSpareDocument
|
||||
} from '../../modules/orca-mobile-web-shell/src/spare-document'
|
||||
import type { GenerationStore } from './generation-store'
|
||||
import { generationDirectoryPath } from './generation-store-file-system'
|
||||
import { deriveHostCacheKey } from './host-cache-key'
|
||||
import { mintShellSessionId } from './shell-session-id'
|
||||
|
||||
// A Home entry claims the spare about 0.2 s after the tap on a simulator; a native screen keeps it no longer.
|
||||
const HOME_SPARE_CLAIM_GRACE_MS = 2000
|
||||
|
||||
// What JS last asked native to park, until a claim or a drop. Native may since have dropped it on
|
||||
// its own (background, memory); this only saves the claim's native round trip when nothing can match.
|
||||
let parkedDirectory: string | null = null
|
||||
let dropTimer: ReturnType<typeof setTimeout> | null = null
|
||||
// A prepare still reading the store when Home goes must not park a spare after the drop ran.
|
||||
let homeShown = false
|
||||
|
||||
function cancelDrop(): void {
|
||||
if (dropTimer !== null) {
|
||||
clearTimeout(dropTimer)
|
||||
dropTimer = null
|
||||
}
|
||||
}
|
||||
|
||||
// Boot one page from the first of `hostIds` (most recently connected first) that has a cached build.
|
||||
export async function prepareHomeSparePage(
|
||||
store: GenerationStore,
|
||||
hostIds: readonly string[]
|
||||
): Promise<void> {
|
||||
try {
|
||||
for (const hostId of hostIds) {
|
||||
const hostKey = deriveHostCacheKey(hostId)
|
||||
const active = await store.readActiveGeneration(hostKey)
|
||||
if (active === null) {
|
||||
continue
|
||||
}
|
||||
if (!homeShown) {
|
||||
return
|
||||
}
|
||||
const directory = generationDirectoryPath(active.directory)
|
||||
const prepared = await prepareSpareDocument(directory, mintShellSessionId())
|
||||
if (prepared && !homeShown) {
|
||||
await dropHomeSparePage()
|
||||
} else if (prepared) {
|
||||
parkedDirectory = directory
|
||||
}
|
||||
return
|
||||
}
|
||||
} catch {
|
||||
// A spare only saves time; the next entry boots its own page without one.
|
||||
}
|
||||
}
|
||||
|
||||
// The spare's session id when Home booted it from `directory`; the view mounted with it adopts that page.
|
||||
export async function claimHomeSparePage(directory: string): Promise<string | null> {
|
||||
if (parkedDirectory !== directory) {
|
||||
return null
|
||||
}
|
||||
parkedDirectory = null
|
||||
cancelDrop()
|
||||
try {
|
||||
return await claimSpareDocument(directory)
|
||||
} catch {
|
||||
return null
|
||||
}
|
||||
}
|
||||
|
||||
// Home is shown; a spare still inside the grace after leaving it stays.
|
||||
export function enterHomeSparePage(): void {
|
||||
homeShown = true
|
||||
cancelDrop()
|
||||
}
|
||||
|
||||
// Home lost focus: a page opening from it claims the spare within the grace, anything else drops it.
|
||||
export function leaveHomeSparePage(): void {
|
||||
homeShown = false
|
||||
cancelDrop()
|
||||
dropTimer = setTimeout(() => {
|
||||
dropTimer = null
|
||||
void dropHomeSparePage()
|
||||
}, HOME_SPARE_CLAIM_GRACE_MS)
|
||||
}
|
||||
|
||||
// Also runs before any host's built files go: that is rare, and a spare must not outlive its files.
|
||||
export function dropHomeSparePage(): Promise<void> {
|
||||
parkedDirectory = null
|
||||
return discardSpareDocument().catch(() => undefined)
|
||||
}
|
||||
@@ -165,6 +165,7 @@ async function mountRoute(fileSystem: FakeGenerationFileSystem): Promise<Mounted
|
||||
runtime: {
|
||||
createStore: () => createGenerationStore({ fileSystem }),
|
||||
mintSessionId: () => 'session-id',
|
||||
claimSpareSessionId: async () => null,
|
||||
now: () => 0,
|
||||
setForegroundTimer: () => () => {}
|
||||
}
|
||||
|
||||
@@ -1,12 +1,9 @@
|
||||
import * as ExpoCrypto from 'expo-crypto'
|
||||
import { encodeBase64Url } from '../transport/encryption/mobile-session-id-encoding'
|
||||
import { BRIDGE_READY_RETRY_MAX_MS } from './bridge/bridge-client-init-handshake'
|
||||
import type { GenerationStore } from './generation-store'
|
||||
import { processGenerationStore } from './process-generation-store'
|
||||
import { setForegroundTimer } from './foreground-timer'
|
||||
|
||||
// Use 32 random base64url bytes: each mount/remount needs a fresh id for the view’s private origin.
|
||||
const SESSION_ID_BYTES = 32
|
||||
import { claimHomeSparePage } from './home-spare-page'
|
||||
import { mintShellSessionId } from './shell-session-id'
|
||||
|
||||
// Allow five ready-backoff ceilings before treating a loaded document as silent; startup import failures may prevent every ready attempt.
|
||||
export const PAGE_READY_DEADLINE_MS = BRIDGE_READY_RETRY_MAX_MS * 5
|
||||
@@ -17,6 +14,8 @@ export const DOCUMENT_LOAD_DEADLINE_MS = 20_000
|
||||
export type MobileWebShellRuntime = {
|
||||
createStore(): GenerationStore
|
||||
mintSessionId(): string
|
||||
// The session id of a page Home booted from this directory, so the view adopts it instead of a new one.
|
||||
claimSpareSessionId(directory: string): Promise<string | null>
|
||||
now(): number
|
||||
// Count only foreground time and return cancellation; tests replace this seam instead of waiting on wall time.
|
||||
setForegroundTimer(run: () => void, delayMs: number): () => void
|
||||
@@ -25,7 +24,8 @@ export type MobileWebShellRuntime = {
|
||||
export function createMobileWebShellRuntime(): MobileWebShellRuntime {
|
||||
return {
|
||||
createStore: processGenerationStore,
|
||||
mintSessionId: () => encodeBase64Url(ExpoCrypto.getRandomBytes(SESSION_ID_BYTES)),
|
||||
mintSessionId: mintShellSessionId,
|
||||
claimSpareSessionId: claimHomeSparePage,
|
||||
now: Date.now,
|
||||
setForegroundTimer
|
||||
}
|
||||
|
||||
@@ -103,6 +103,7 @@ describe('a download that reuses the cached generation', () => {
|
||||
runtime: {
|
||||
createStore: () => store,
|
||||
mintSessionId: () => 's',
|
||||
claimSpareSessionId: async () => null,
|
||||
now: () => 0,
|
||||
setForegroundTimer: () => () => {}
|
||||
},
|
||||
|
||||
@@ -264,17 +264,20 @@ export async function runShellEffect(
|
||||
context.manifest.current = null
|
||||
await (effect.kind === 'download' ? download : stageUpdate)({ ...context, opened })
|
||||
return
|
||||
case 'open-generation':
|
||||
case 'open-generation': {
|
||||
// A remount mints its own id below; only a first open adopts a page Home booted.
|
||||
const spare = await runtime.claimSpareSessionId(effect.directory)
|
||||
send({
|
||||
type: 'activated',
|
||||
flow,
|
||||
generationDirectory: effect.directory,
|
||||
sessionId: runtime.mintSessionId(),
|
||||
sessionId: spare ?? runtime.mintSessionId(),
|
||||
buildId: effect.buildId,
|
||||
totalBytes: effect.totalBytes,
|
||||
elapsedMs: runtime.now() - context.startedAt
|
||||
})
|
||||
return
|
||||
}
|
||||
case 'remount': {
|
||||
const remount = (): void =>
|
||||
send({ type: 'remounted', flow, sessionId: runtime.mintSessionId() })
|
||||
|
||||
@@ -0,0 +1,40 @@
|
||||
import { readBridgeClientMessage } from './bridge/bridge-envelope'
|
||||
import { frameWithoutHostLine } from './shell-bridge-log-lines'
|
||||
import { recordShellLifecycleLine } from './shell-lifecycle-line-recorder'
|
||||
|
||||
export type FrameWithoutHostFacts = { hostId: string; clientReady: boolean; snapshotReady: boolean }
|
||||
|
||||
export type PageFramesWithoutHost = {
|
||||
/** A frame no host serves yet; `facts` is null when a retired session's host is still mounted. */
|
||||
receive: (sessionId: string, json: string, facts: FrameWithoutHostFacts | null) => void
|
||||
/** Hands the page's latest ready for this session to the host just built for it, once. */
|
||||
replayReady: (sessionId: string, host: { receive: (json: string) => void }) => void
|
||||
}
|
||||
|
||||
// Keep the ready instead of dropping it, so init does not wait on the page's 50 ms to 2 s backoff.
|
||||
export function createPageFramesWithoutHost(): PageFramesWithoutHost {
|
||||
let loggedSessionId: string | null = null
|
||||
let ready: { sessionId: string; json: string } | null = null
|
||||
return {
|
||||
receive: (sessionId, json, facts) => {
|
||||
if (facts !== null && loggedSessionId !== sessionId) {
|
||||
loggedSessionId = sessionId
|
||||
recordShellLifecycleLine(facts.hostId, frameWithoutHostLine(facts))
|
||||
}
|
||||
const read = readBridgeClientMessage(json)
|
||||
if (read.ok && read.message.type === 'ready') {
|
||||
ready = { sessionId, json }
|
||||
} else if (read.ok && read.message.type === 'close') {
|
||||
// The document that asked is gone, so its ready must not be answered.
|
||||
ready = null
|
||||
}
|
||||
},
|
||||
replayReady: (sessionId, host) => {
|
||||
const kept = ready
|
||||
ready = null
|
||||
if (kept?.sessionId === sessionId) {
|
||||
host.receive(kept.json)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,11 +1,15 @@
|
||||
import { createGenerationStore, type GenerationStore } from './generation-store'
|
||||
import { createExpoGenerationFileSystem } from './generation-store-file-system'
|
||||
import { dropHomeSparePage } from './home-spare-page'
|
||||
|
||||
let processStore: GenerationStore | null = null
|
||||
|
||||
// Share one store queue across native callers so host removal cannot interleave with generation/index/failure-log writes.
|
||||
export function processGenerationStore(): GenerationStore {
|
||||
processStore ??= createGenerationStore({ fileSystem: createExpoGenerationFileSystem() })
|
||||
processStore ??= createGenerationStore({
|
||||
fileSystem: createExpoGenerationFileSystem(),
|
||||
beforeHostFilesDeleted: dropHomeSparePage
|
||||
})
|
||||
return processStore
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,9 @@
|
||||
import * as ExpoCrypto from 'expo-crypto'
|
||||
import { encodeBase64Url } from '../transport/encryption/mobile-session-id-encoding'
|
||||
|
||||
// Use 32 random base64url bytes: each mount/remount needs a fresh id for the view’s private origin.
|
||||
const SESSION_ID_BYTES = 32
|
||||
|
||||
export function mintShellSessionId(): string {
|
||||
return encodeBase64Url(ExpoCrypto.getRandomBytes(SESSION_ID_BYTES))
|
||||
}
|
||||
@@ -14,6 +14,7 @@ import {
|
||||
import type { BridgeErrorCapture } from './bridge/bridge-error-capture'
|
||||
import type { MobileWebShellSessionState } from './mobile-web-shell-session-contract'
|
||||
import type { FakeRpcClient } from './bridge-host-test-fakes'
|
||||
import type { PageHostSnapshot } from './use-page-host-snapshot'
|
||||
|
||||
const doubles = vi.hoisted((): { client: FakeRpcClient | null } => ({ client: null }))
|
||||
|
||||
@@ -82,6 +83,7 @@ function FakeShellView(props: {
|
||||
function Harness(props: {
|
||||
session: MobileWebShellSessionState
|
||||
sessionEstablished?: boolean
|
||||
snapshot?: PageHostSnapshot | null
|
||||
posted: PostedFrame[]
|
||||
probe: Probe
|
||||
faults: BridgeErrorCapture[]
|
||||
@@ -121,7 +123,7 @@ function Harness(props: {
|
||||
props.probe.backPops += 1
|
||||
return 'popped'
|
||||
},
|
||||
snapshot: SNAPSHOT,
|
||||
snapshot: props.snapshot === undefined ? SNAPSHOT : props.snapshot,
|
||||
readStorage: () => ({ storage: STORAGE, storageOversize: [] }),
|
||||
onStorageWrite: (key, value) => props.probe.storageWrites.push({ key, value }),
|
||||
// Use fresh callbacks each render; rebuilding for them would settle pending requests.
|
||||
@@ -198,7 +200,8 @@ afterEach(async () => {
|
||||
|
||||
async function mount(
|
||||
session: MobileWebShellSessionState,
|
||||
sessionEstablished?: boolean
|
||||
sessionEstablished?: boolean,
|
||||
snapshot?: PageHostSnapshot | null
|
||||
): Promise<Mounted> {
|
||||
const posted: PostedFrame[] = []
|
||||
const probe: Probe = {
|
||||
@@ -219,6 +222,7 @@ async function mount(
|
||||
createElement(Harness, {
|
||||
session: next,
|
||||
...(sessionEstablished === undefined ? {} : { sessionEstablished }),
|
||||
...(snapshot === undefined ? {} : { snapshot }),
|
||||
posted,
|
||||
probe,
|
||||
faults,
|
||||
@@ -312,3 +316,26 @@ describe('a session that handshook before this host existed', () => {
|
||||
expect(fakeClient().requests).toEqual([])
|
||||
})
|
||||
})
|
||||
|
||||
describe('a ready the page sent before its host existed', () => {
|
||||
it('is answered with one init as soon as the host snapshot arrives', async () => {
|
||||
const mounted = await mount(readyState('session-one'), undefined, null)
|
||||
await mounted.deliver(clientFrame({ type: 'ready' }))
|
||||
expect(mounted.posted).toEqual([])
|
||||
await act(async () => {
|
||||
mounted.tree.update(
|
||||
createElement(Harness, {
|
||||
session: readyState('session-one'),
|
||||
snapshot: SNAPSHOT,
|
||||
posted: mounted.posted,
|
||||
probe: mounted.probe,
|
||||
faults: mounted.faults,
|
||||
readies: mounted.readies
|
||||
})
|
||||
)
|
||||
})
|
||||
expect(mounted.frames('session-one')).toEqual([
|
||||
expect.objectContaining({ type: 'init', sessionId: 'session-one', buildId: 'build-a' })
|
||||
])
|
||||
})
|
||||
})
|
||||
|
||||
@@ -5,14 +5,14 @@ import type {
|
||||
BridgeTerminalKeyRail
|
||||
} from './bridge/bridge-terminal-key'
|
||||
import type { BridgePageGeometry } from './bridge/bridge-page-geometry'
|
||||
import { useCallback, useEffect, useLayoutEffect, useRef } from 'react'
|
||||
import { useCallback, useEffect, useLayoutEffect, useRef, useState } from 'react'
|
||||
import type {
|
||||
MobileWebShellBridgeMessagePayload,
|
||||
OrcaMobileWebShellViewHandle
|
||||
} from '../../modules/orca-mobile-web-shell/src'
|
||||
import { useHostClient } from '../transport/connection/host-client-hooks'
|
||||
import { createBridgeDiagnosticReporter } from './bridge-diagnostic-log'
|
||||
import { bridgeDiagnosticLine, frameWithoutHostLine } from './shell-bridge-log-lines'
|
||||
import { bridgeDiagnosticLine } from './shell-bridge-log-lines'
|
||||
import { recordShellLifecycleLine } from './shell-lifecycle-line-recorder'
|
||||
import type { BridgeColorScheme, BridgeInitRoute, BridgeUiLocale } from './bridge/bridge-envelope'
|
||||
import type { BridgeClearableRouteParam } from './bridge/bridge-route-update'
|
||||
@@ -27,6 +27,7 @@ import type { BridgeErrorCapture } from './bridge/bridge-error-capture'
|
||||
import type { MobileWebShellSessionState } from './mobile-web-shell-session-contract'
|
||||
import type { PageHostSnapshot } from './use-page-host-snapshot'
|
||||
import type { PageStorageForInit } from './page-storage-keys'
|
||||
import { createPageFramesWithoutHost } from './page-frames-without-host'
|
||||
|
||||
class BridgeViewGoneError extends Error {
|
||||
constructor() {
|
||||
@@ -135,7 +136,7 @@ export function useMobileWebShellBridge(args: MobileWebShellBridgeArgs): MobileW
|
||||
// Read identity lazily without rebuilding a live host just to refresh a string.
|
||||
const clientIdRef = useRef(clientId)
|
||||
const clientRef = useRef(client)
|
||||
const droppedFrameLoggedRef = useRef<string | null>(null)
|
||||
const [framesWithoutHost] = useState(createPageFramesWithoutHost)
|
||||
// Update refs on every commit before host construction; native frames may arrive before passive effects.
|
||||
useLayoutEffect(() => {
|
||||
argsRef.current = args
|
||||
@@ -207,13 +208,14 @@ export function useMobileWebShellBridge(args: MobileWebShellBridgeArgs): MobileW
|
||||
hostRef.current = { sessionId, host }
|
||||
// Reset host-owned drop totals on rebuild so a new lower count cannot look like frames being recovered.
|
||||
latest.onBinaryFramesDropped(0)
|
||||
framesWithoutHost.replayReady(sessionId, host)
|
||||
return () => {
|
||||
// Capture Back before disposal so the next host for this document inherits it.
|
||||
establishedBackRef.current = { sessionId, back: host.readSessionBack() }
|
||||
hostRef.current = null
|
||||
host.dispose()
|
||||
}
|
||||
}, [buildId, client, sessionId, snapshot])
|
||||
}, [buildId, client, framesWithoutHost, sessionId, snapshot])
|
||||
|
||||
useEffect(() => {
|
||||
const mounted = hostRef.current
|
||||
@@ -246,25 +248,24 @@ export function useMobileWebShellBridge(args: MobileWebShellBridgeArgs): MobileW
|
||||
(event: MobileWebShellBridgeMessageEvent) => {
|
||||
const mounted = hostRef.current
|
||||
if (mounted === null || mounted.sessionId !== sessionId) {
|
||||
if (
|
||||
mounted === null &&
|
||||
sessionId !== null &&
|
||||
droppedFrameLoggedRef.current !== sessionId
|
||||
) {
|
||||
droppedFrameLoggedRef.current = sessionId
|
||||
recordShellLifecycleLine(
|
||||
argsRef.current.hostId,
|
||||
frameWithoutHostLine({
|
||||
clientReady: clientRef.current !== null,
|
||||
snapshotReady: argsRef.current.snapshot !== null
|
||||
})
|
||||
if (sessionId !== null) {
|
||||
framesWithoutHost.receive(
|
||||
sessionId,
|
||||
event.nativeEvent.json,
|
||||
mounted === null
|
||||
? {
|
||||
hostId: argsRef.current.hostId,
|
||||
clientReady: clientRef.current !== null,
|
||||
snapshotReady: argsRef.current.snapshot !== null
|
||||
}
|
||||
: null
|
||||
)
|
||||
}
|
||||
return
|
||||
}
|
||||
mounted.host.receive(event.nativeEvent.json)
|
||||
},
|
||||
[sessionId]
|
||||
[framesWithoutHost, sessionId]
|
||||
),
|
||||
// Fenced on the session the same way inbound frames are: a host left over from a session this
|
||||
// render has moved past must not be handed this one's route.
|
||||
|
||||
@@ -264,7 +264,8 @@ afterEach(async () => {
|
||||
|
||||
async function mount(
|
||||
store: GenerationStore,
|
||||
setForegroundTimer?: MobileWebShellRuntime['setForegroundTimer']
|
||||
setForegroundTimer?: MobileWebShellRuntime['setForegroundTimer'],
|
||||
claimSpareSessionId: MobileWebShellRuntime['claimSpareSessionId'] = async () => null
|
||||
): Promise<Mounted> {
|
||||
const timers = createTimerSeam()
|
||||
// Mint distinct ids so a remount's replacement view can be told from the one it retires.
|
||||
@@ -297,6 +298,7 @@ async function mount(
|
||||
runtime: {
|
||||
createStore: () => store,
|
||||
mintSessionId: () => `session-${++minted}`,
|
||||
claimSpareSessionId,
|
||||
now: () => 0,
|
||||
setForegroundTimer: setForegroundTimer ?? timers.setTimer
|
||||
}
|
||||
@@ -374,6 +376,19 @@ describe('the wait for the page to speak', () => {
|
||||
expect(mounted.states().at(-1)?.kind).toBe('ready')
|
||||
})
|
||||
|
||||
it('opens a page Home booted under its session id, and remounts under a fresh one', async () => {
|
||||
const fake = createFakeStore()
|
||||
const mounted = await mount(fake.store, undefined, async () => 'home-spare')
|
||||
fake.settleCacheRead(activeGeneration())
|
||||
await flush()
|
||||
expect(mounted.states().at(-1)).toMatchObject({ kind: 'ready', sessionId: 'home-spare' })
|
||||
await act(async () => {
|
||||
mounted.shellFailed('document-load-failed')
|
||||
})
|
||||
await flush()
|
||||
expect(mounted.states().at(-1)).toMatchObject({ kind: 'ready', sessionId: 'session-1' })
|
||||
})
|
||||
|
||||
it('stays ready when the page speaks after document load and the timers fire', async () => {
|
||||
const mounted = await ready()
|
||||
await act(async () => {
|
||||
@@ -401,6 +416,7 @@ describe('the wait for the page to speak', () => {
|
||||
runtime: {
|
||||
createStore: () => fake.store,
|
||||
mintSessionId: () => 'session-id',
|
||||
claimSpareSessionId: async () => null,
|
||||
now: () => 0,
|
||||
setForegroundTimer: createTimerSeam().setTimer
|
||||
}
|
||||
|
||||
@@ -20,7 +20,7 @@ export function NewWorkspacePageScreen() {
|
||||
const { hostCapabilities } = useHostProtocolGates()
|
||||
const connected = connState === 'connected'
|
||||
const worktrees = useHostWorktreeRows(client, connected, hostId)
|
||||
const hostLabelById = useHostLabelById(client, connected)
|
||||
const hostLabelById = useHostLabelById(client, connected, hostId)
|
||||
const worktreePaths = useMemo(() => worktrees.map((worktree) => worktree.path), [worktrees])
|
||||
|
||||
return (
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user