Testing the extension polyfill
A TypeScript-safe, five-layer strategy for browser LLM features
WebInfer crosses emitted TypeScript declarations, a page global, an injected script, a content script, an MV3 worker and a provider. Test those boundaries in layers so a failure identifies the contract that broke instead of becoming a flaky end-to-end mystery.
Run the deterministic gate
npm ci
# Exact npm-pack artifacts, Bundler + NodeNext
npm run test:sdk-contract
# Fast SDK and real-relay integration suites
npm --workspace @webinfer/client test
npm --workspace @webinfer/extension test
# Production bundle in pinned Chrome for Testing
npm run build:extension
npm --workspace @webinfer/extension run test:chrome-ai-sw:provisionedThe Chrome command provisions a pinned official Chrome for Testing build. It needs no model download, API key, special hardware or live inference network. Set WEBINFER_CFT_CACHE to keep the browser in a persistent cache, or CHROME_BIN to use an already-provisioned unbranded Chromium-compatible executable.
What each layer proves
1. Packed TypeScript contract
Proves: Export maps, emitted declarations, inference and negative type contracts in a clean consumer.
Does not prove: Chrome, the extension manifest and runtime messaging.
2. SDK and helper unit tests
Proves: Prompt/schema behavior, result metadata, errors and application policy without a browser.
Does not prove: Structured clone, content scripts and MV3 lifecycle.
3. Relay integration harness
Proves: The real page API and both real content relays agree with runtime messages and a deterministic native fake.
Does not prove: Chrome manifest matching and service-worker suspension.
4. Installed production MV3
Proves: The built manifest, page injection, content relays, service worker, provider routing and result cleanup work in Chrome.
Does not prove: The actual Chrome-managed model because this layer injects a deterministic fake.
5. Real-model qualification
Proves: Supported hardware and stable Chrome can run the unmodified built-in model across release lifecycle states.
Does not prove: Nothing deterministic enough for normal hosted CI; this is a separate release gate.
1. Compile packed artifacts
npm run test:sdk-contract creates exact tarballs, installs them into a temporary application with no workspace aliases, rejects private source paths in declarations, and compiles TypeScript 5.9 with both Bundler and NodeNext resolution.
The fixture covers @webinfer/client, its helper subpath, the local public-package artifact, navigator.llm, text, streaming through textStream, structured output, concrete typed tools, cancellation, configuration and error narrowing. Invalid capabilities, schemas and response fields are pinned with@ts-expect-error.
A green result proves the checked local artifacts agree. It does not claim the first scoped npm release has happened. The unscoped local facade remains private and is exercised only as a contract fixture.
2. Inject SDK behavior
Common workflows live in @webinfer/client/helpers, outside React and AI Blocks. Use createLLMHelpers with test generation functions to inspect the actual prompt, schema and routing options without installing an extension.
const generateText = vi.fn(async () => ({
text: 'Short summary',
finishReason: 'stop',
usage: { promptTokens: 8, completionTokens: 3, totalTokens: 11 },
}))
const helpers = createLLMHelpers({
generateText,
generateObject: vi.fn(),
})
await helpers.summarizeText({ text: 'Long source', maxWords: 20 })
expect(generateText).toHaveBeenCalledWith(expect.objectContaining({
task: 'summarization',
prompt: 'Long source',
}))3. Exercise the real relays
The extension Vitest suite installs the real injectednavigator.llm API and both real content relays around simulated window.postMessage andchrome.runtime boundaries. Its dependency-freeLanguageModel fake supports availability and download states, progress, prompt, stream, usage, cloning, aborts, failures and call history.
Fake only globalThis.LanguageModel. Fakingnavigator.llm or the content relay skips the integration contract you are trying to test.
import { afterEach, expect, it } from 'vitest'
import {
createExtensionPolyfillHarness,
type ExtensionPolyfillHarness,
} from './extension-harness'
let harness: ExtensionPolyfillHarness | undefined
afterEach(() => {
harness?.cleanup()
harness = undefined
})
it('relays the public page request', async () => {
harness = createExtensionPolyfillHarness({
languageModel: { completion: 'deterministic result' },
})
await expect(harness.navigator.llm!.generateText({
prompt: 'Exercise the extension bridge.',
provider: 'chrome-ai',
temperature: 0,
})).resolves.toMatchObject({
text: 'deterministic result',
metadata: { provider: 'chrome-ai' },
})
expect(harness.runtime.sentMessages[0]).toMatchObject({
type: 'WEBLLM_REQUEST',
origin: 'https://extension-test.example',
})
})Put this beside apps/extension/src/test/extension-harness.ts. The complete maintained example is extension-polyfill.integration.test.ts; the harness is repository test infrastructure rather than a public SDK export.
4. Load the production extension
The Chrome-backed runner copies apps/extension/dist to a temporary unpacked extension, starts the real MV3 worker, serves a normal loopback HTTP page and callsnavigator.llm.generateText() from page code. It then disables the native seam and asserts the page receives a clean unavailable error instead of a ReferenceError.
- No extension marker: inspect manifest matching or content injection.
- Marker but no page API: inspect the web-accessible injected resource.
- Page API but no worker request: inspect relay correlation and serialization.
- No
LanguageModel.create(): inspect provider registration and routing. - Completion arrives but page hangs: inspect terminal response and listener cleanup.
5. Keep real-model evidence separate
Deterministic CI injects a native fake; it is not evidence that the machine can run Gemini Nano. The real-model release gate must use stable Chrome on supported hardware, reject an injected or replacedLanguageModel, and record available/download/offline states without prompt or completion contents. Unsupported hardware isnot supported, never a pass.
# Validate the evidence schema and release matrix without Chrome
npm --workspace @webinfer/extension run qualify:chrome-ai-real:validate
# Operator-owned stable Chrome only; see TESTING.md for the required attestations
npm --workspace @webinfer/extension run qualify:chrome-ai-realThe guarded command never provisions Chrome or starts a model download. It rejects replaced native methods before sending its fixed health request. Exit 0 means a native request passed, 2 means not supported, and 1 means qualification failed; only exit 0 satisfies the release gate.
Use stable errors in assertions
Do not match English error strings. Availability errors exposeavailabilityCode: install-extension,configure-providers, use-gateway orunsupported. General failures expose stable codes such asUNAVAILABLE, NO_PROVIDER,PERMISSION_DENIED, PROVIDER_AUTH,RATE_LIMITED, TIMEOUT,CANCELLED, NETWORK andVERSION_MISMATCH.
Treat Chrome's downloadable and downloading states as browser-owned observations: record them and stop. Treat unavailable as not supported, never as a fake-backed pass. Use PERMISSION_DENIED to inspect the origin grant, VERSION_MISMATCH to rebuild both protocol endpoints, and CANCELLED to assert cleanup without replaying the operation.
Privacy-safe diagnostics
A useful report includes the exact command, failing layer, commit, Node/Chrome/OS versions, stable error code, availability state, whether the extension marker and page API appeared, and whether the worker and native create call were reached. Never attach provider keys, access tokens, raw prompts, model completions or a copied Chrome profile.
See the repository TESTING.md for the full scenario matrix, permission/cancellation/worker-lifecycle ownership and optional live-provider diagnosis.
Promoted demo scenarios
The public /demo page exposes a versioned JSON manifest and stable data-webinfer-* selectors for text, streaming, structured output and translation. A new workflow joins that small conformance set only after it uses public SDK types, has deterministic output and provider/model assertions, covers a distinct behavior, and passes the relay harness. AI Blocks remain an optional UI catalog and are never promoted wholesale.