WebInfer

Checking Availability

Detect WebInfer availability and guide users to set up their environment

Before making LLM requests, you should check if WebInfer is available on the user's device. This guide covers how to detect availability, show helpful messages to users, and handle fallback scenarios.

Availability Helpers

WebInfer provides a set of helpers to simplify availability checking:

FunctionDescription
checkAvailability()Complete status check returning availability, transport, browser info, providers, and capabilities
hasCapability(type)Check if a capability is available: 'text', 'image', 'embedding', 'vision', 'audio', 'tool-use'
getCapabilities()Get all capabilities as a Record<Capability, boolean>
getProvidersByCapability()Get available providers grouped by capability type
useWebInferStatus()React hook for reactive availability status
isAvailable()Simple boolean check if any transport is available
getBrowserInfo()Get browser compatibility information
getProviderStatus()Get configured and available providers
promptInstall()Show install prompt UI, resolves when ready
webInferReady(timeout?)Wait for WebInfer to become available
Live Availability Check
isAvailable()
Not checked
getBrowserInfo()
Not checked
getProviderStatus()
Not checked
checkAvailability()
Not checked
getCapabilities()
Not checked
hasCapability("image")
Not checked
hasCapability("embedding")
Not checked
getProvidersByCapability()
Not checked
Click "Check All" to run these methods and see live results from your browser.

Quick Start

Use checkAvailability() to get a complete status in one call:

availability.ts
import { checkAvailability } from '@webinfer/client'const status = await checkAvailability()if (status.available) {  console.log(`Ready with ${status.providers?.count} providers`)  console.log('Transport:', status.transport) // 'extension' or 'daemon'  console.log('Capabilities:', status.capabilities)  // { text: true, image: true, embedding: false, vision: true, ... }} else {  console.log(status.actionMessage)  // "Install the WebInfer extension to get started."  // "Configure at least one AI provider to start using WebInfer."  console.log('Suggested action:', status.action)  // 'install-extension' | 'configure-providers' | 'unsupported'}

Availability States

There are several states your application needs to handle:

StateDescriptionUser Action
AvailableExtension installed and providers configuredReady to use
No ProvidersExtension installed but no providers set upConfigure an API provider, use Chrome's built-in AI when available, or connect a local daemon
Not InstalledCompatible browser but extension not installedInstall the WebInfer extension
Unsupported BrowserBrowser doesn't support Chrome extensionsSwitch browser or use gateway fallback

Browser Compatibility

The getBrowserInfo() function returns detailed compatibility information:

browser-info.ts
import { getBrowserInfo } from '@webinfer/client'interface BrowserInfo {  isSupported: boolean    // Can install the extension  browserName: string     // 'Chrome', 'Edge', 'Firefox', 'Safari', etc.  reason?: string         // Why it's not supported (if applicable)  installUrl?: string     // Link to extension store (if supported)}const info = getBrowserInfo()if (!info.isSupported) {  console.log(`${info.browserName}: ${info.reason}`)  // "Firefox: WebInfer extension for Firefox is coming soon"  // "Safari: WebInfer extension is not supported on Safari"  // "Mobile Browser: WebInfer extension is not supported on mobile browsers"}

Complete Availability Check

Here's a complete example that handles all availability states:

check-availability.ts
import { isAvailable, getBrowserInfo, getProviderStatus } from '@webinfer/client'interface AvailabilityResult {  ready: boolean  state: 'ready' | 'no-providers' | 'not-installed' | 'unsupported'  message: string  action?: {    label: string    url?: string  }}async function checkAvailability(): Promise<AvailabilityResult> {  const browserInfo = getBrowserInfo()  // Check browser compatibility first  if (!browserInfo.isSupported) {    return {      ready: false,      state: 'unsupported',      message: `${browserInfo.browserName} is not supported. ${browserInfo.reason || ''}`,      action: {        label: 'Use Chrome or Edge',        url: 'https://www.google.com/chrome/'      }    }  }  // Check if extension/daemon is available  const available = await isAvailable()  if (!available) {    return {      ready: false,      state: 'not-installed',      message: 'WebInfer extension is not installed.',      action: {        label: 'Install Extension',        url: browserInfo.installUrl      }    }  }  // Check if providers are configured  const status = await getProviderStatus()  if (!status.hasProviders) {    return {      ready: false,      state: 'no-providers',      message: 'No AI providers configured. Add an API key, use available Chrome built-in AI, or connect a local daemon.',      action: {        label: 'Configure Providers'      }    }  }  return {    ready: true,    state: 'ready',    message: `Ready with ${status.availableProviders.length} provider(s)`  }}

Handle Request Failures by Code

Availability checks tell you what is ready before a request. Requests can still fail later because a compatible provider is missing, credentials are invalid, quota is exhausted, or the site permission changed. Branch on the stable code rather than the human-readable message:

handle-webinfer-error.ts
import {  WebInferAvailabilityError,  WebInferError,  WireErrorCode,  generateText,} from '@webinfer/client'function showAction(label: string, href?: string) {  const status = document.querySelector('#webinfer-status')  if (status) status.textContent = href ? `${label}: ${href}` : label}try {  await generateText({ prompt: 'Summarize this page' })} catch (error) {  if (error instanceof WebInferAvailabilityError) {    if (error.availabilityCode === 'install-extension') {      showAction('Install or connect WebInfer', error.docsUrl)    } else if (error.availabilityCode === 'configure-providers') {      showAction('Open WebInfer and configure a provider')    }  } else if (error instanceof WebInferError) {    switch (error.code) {      case WireErrorCode.NO_PROVIDER:        showAction('Configure a compatible provider')        break      case WireErrorCode.PROVIDER_AUTH:        showAction('Check the selected provider credentials')        break      case WireErrorCode.QUOTA_EXCEEDED:      case WireErrorCode.RATE_LIMITED:        showAction('Check quota or try again later')        break      case WireErrorCode.PERMISSION_DENIED:        showAction('Review this site permission in WebInfer')        break      default:        showAction('Request failed')    }  }}

The extension transport reconstructs server failures as typedWebInferError subclasses while preserving the wire code and structured details. Unknown future codes normalize to INTERNAL instead of requiring message matching.

Showing User Prompts

The client includes a built-in install prompt that guides users through installation:

prompt-install.ts
import { promptInstall, webInferReady } from '@webinfer/client'// Option 1: Show install prompt if neededtry {  await promptInstall()  // User has installed and extension is ready} catch (error) {  // User's browser doesn't support the extension  console.error(error.message)}// Option 2: Wait for extension with timeouttry {  await webInferReady(30000) // 30 second timeout  // Extension is ready} catch (error) {  // Extension not available after timeout  console.error('WebInfer not available:', error.message)}

Checking Capabilities

Check if specific capabilities are available (e.g., image generation, embeddings):

check-capabilities.ts
import { hasCapability, getCapabilities, getProvidersByCapability } from '@webinfer/client'// Check a single capabilityif (await hasCapability('image')) {  // Show image generation UI}if (await hasCapability('embedding')) {  // Enable semantic search features}// Get all capabilities at onceconst caps = await getCapabilities()// { text: true, image: true, embedding: false, vision: true, audio: false, 'tool-use': true }// Get providers grouped by capabilityconst providers = await getProvidersByCapability()console.log(providers.image)     // ['openai', 'stability', 'replicate']console.log(providers.embedding) // ['openai', 'cohere', 'voyage']console.log(providers.vision)    // ['openai', 'anthropic', 'google']

React Hook

Use the useWebInferStatus hook for reactive availability checking:

WebInferStatus.tsx
import { useWebInferStatus } from '@webinfer/client'export function WebInferStatus() {  const {    status,      // 'loading' | 'ready' | 'no-providers' | 'not-installed' | 'unsupported'    available,   // boolean    loading,     // boolean    message,     // Human-readable status message    action,      // Suggested action: 'ready' | 'install-extension' | 'configure-providers' | ...    details,     // Full AvailabilityStatus object    capabilities,// { text, image, embedding, vision, audio, 'tool-use' }    providers,   // string[] of available provider IDs    refresh      // () => Promise<void> to re-check  } = useWebInferStatus()  if (loading) {    return <div>Checking availability...</div>  }  if (!available) {    return (      <div>        <p>{message}</p>        {action === 'install-extension' && (          <a href={details?.browser.installUrl}>Install Extension</a>        )}        {action === 'configure-providers' && (          <p>Click the WebInfer extension icon to add a provider</p>        )}      </div>    )  }  return (    <div>      <p>Ready with {providers.length} providers</p>      <p>Image generation: {capabilities.image ? 'Yes' : 'No'}</p>      <p>Embeddings: {capabilities.embedding ? 'Yes' : 'No'}</p>    </div>  )}

Fallback Options

When the extension isn't available, you have several fallback options:

Gateway Public Tokens

You can provide a pool of credits for users who don't have the extension installed. This is done through WebInfer Gateways with public access tokens:

gateway-fallback.ts
import { WebInferClient } from '@webinfer/client'async function getClient() {  // Check if extension is available  const available = await isAvailable()  if (available) {    // Use extension (user's own API keys/models)    return new WebInferClient()  }  // Fall back to gateway with public token  return new WebInferClient({    preferredTransport: 'daemon',    daemonUrl: 'https://your-gateway.webinfer.dev',    daemonToken: 'wlm-your-public-token.xxx'  })}

Mock Mode for Development

During development, you can use mock mode to test your UI without a real LLM:

mock-fallback.ts
import { generateText, isAvailable } from '@webinfer/client'const useMock = !(await isAvailable()) && process.env.NODE_ENV === 'development'const result = await generateText({  prompt: 'Hello, world!',  mock: useMock  // Returns lorem ipsum text instantly})

Listening for Availability Changes

The extension fires a webinfer:ready event when it becomes available:

listen-ready.ts
// Listen for extension becoming availablewindow.addEventListener('webinfer:ready', () => {  console.log('WebInfer extension is now available!')  // Re-check availability and update UI})// Check immediately and listen for changesasync function initWebInfer() {  if (await isAvailable()) {    // Already available    return startApp()  }  // Wait for extension  window.addEventListener('webinfer:ready', () => {    startApp()  }, { once: true })}

API Reference

isAvailable()

Check if WebInfer is available (extension or daemon).

api.ts
function isAvailable(): Promise<boolean>

getBrowserInfo()

Get browser compatibility information.

api.ts
interface BrowserInfo {  isSupported: boolean    // Can install the extension  browserName: string     // Browser name  reason?: string         // Why unsupported  installUrl?: string     // Extension store URL}function getBrowserInfo(): BrowserInfo

getProviderStatus()

Check if providers are configured and which ones are available.

api.ts
interface ProviderStatus {  hasProviders: boolean        // At least one provider is configured  availableProviders: string[] // List of available provider IDs  configuredProviders: string[] // List of configured provider IDs  error?: string               // Error message if check failed}function getProviderStatus(): Promise<ProviderStatus>

promptInstall()

Show a UI prompt to install the extension. Resolves when the extension becomes available.

api.ts
function promptInstall(): Promise<void>// Throws if browser doesn't support the extension

webInferReady(timeout?)

Wait for WebInfer to become available with an optional timeout.

api.ts
function webInferReady(timeout?: number): Promise<void>// timeout: milliseconds to wait (default: 30000)// Throws if not available after timeout

The former readiness helper remains available as a deprecated alias so existing applications keep working. New code should use webInferReady().

Next Steps