Frontend Quickstart (@jetpack-desktop/client)
The @jetpack-desktop/client TypeScript package (web/packages/jetpack-client) provides JetPackAppClient, a high-level wrapper over jetpack-wasm that automates cryptographic identity management, Out-of-Band jetpack://pair onboarding, catalog pulls, worker launch, correlated binary requests, and streaming event subscriptions.
Installation
Install @jetpack-desktop/client from NPM in any Vite, TypeScript, or modern ESM web project:
npm install @jetpack-desktop/client@jetpack-desktop/client bundles the compiled jetpack-wasm WebAssembly binary and JS glue directly inside the package (@jetpack-desktop/client/wasm). External applications work out-of-the-box with zero manual WASM copying or path overrides—both vite dev (dependency pre-bundling) and vite build resolve the bundled .wasm module automatically.
If you host the .wasm binary on a custom CDN path or supply pre-loaded bindings, you can still pass wasmModule, wasmModulePath, or wasmBinaryOrUrl to connectAndEnsureApp(). To access low-level bindings directly, import from the @jetpack-desktop/client/wasm subpath export.
1. Connect, Pair, Pull, and Launch in One Call
import { JetPackAppClient, JetPackClientError } from '@jetpack-desktop/client';
const client = new JetPackAppClient();
try {
await client.connectAndEnsureApp({
appId: 'io.jetpack.media-converter',
daemonPort: 9470,
posterUrl: 'https://example.com/media-converter-poster.webp',
onDaemonReconnect: (reconnectedClient) => {
console.log('JetPack daemon started and connected:', reconnectedClient.getAppId());
},
controlBar: {
appName: 'FFmpeg Media Converter',
warnOnUnsavedWork: () => hasActiveUnsavedWork(),
stopConfirmTitle: 'Stop Media Converter?',
stopConfirmMessage: 'Transcoding is active. Stopping the worker will lose progress.',
onBeforeStop: async () => {
// Optional extra async cleanup or veto (return false to keep worker running)
return true;
},
onAfterStop: () => {
console.log('Worker stopped cleanly from top bar');
},
},
onPairingUri: (uri) => {
// Optional: display an interactive "Approve Pairing in JetPack" button or link
console.log('Approve pairing URI:', uri);
},
onProgress: (progress) => {
console.log(
`[${progress.stage ?? 'pull'}] ${progress.percent ?? 0}% - ${progress.message ?? ''}`
);
},
});
console.log('Worker ready:', client.getAppId());
} catch (err) {
if (err instanceof JetPackClientError) {
if (err.code === 'DAEMON_NOT_RUNNING') {
console.error(`Install or start JetPack Desktop: ${err.downloadUrl}`);
} else {
console.error(`JetPack error [${err.code}]: ${err.message}`);
}
} else {
throw err;
}
}What connectAndEnsureApp() Automates
- Loopback Liveness, Cold-Visit Probe (
GET /health) & Blocking Install-Gate Overlay: Probeshttp://127.0.0.1:<daemonPort>/health(bounded byhealthProbeTimeoutMs = 2000by default). Ifjetpack-daemonis not installed or not running,connectAndEnsureApp()rejects immediately withJetPackClientError('DAEMON_NOT_RUNNING', ..., { downloadUrl })without triggering an unhandledjetpack://pairdeep link, transitionsJetPackControlBarto'Error'with a sanitized HTTPS "Download JetPack" link, and displays a full-viewport blurred install-gate overlay (unlessinstallBanner: false) with the app poster, an install prompt, and a curved dashed SVG arrow pointing straight at "Download JetPack". WhileautoReconnectOnDaemonStart !== falsein browser DOM environments, the client polls/health(daemonPollIntervalMs, default2000ms), automatically re-runsconnectAndEnsureApp()once JetPack responds200 OK, dismisses the overlay, and invokesonDaemonReconnect(client). - Environment Resolution (
DevEnvvsProdEnv): Whenenv('dev' | 'prod' | 'auto') orenvironments({ dev, prod }) is provided,connectAndEnsureApp()resolves per-environment overrides (appId,origin,daemonPort,wsUrl,controlBar,logTerminal, etc.). Whenenv === 'dev'andenvironments.dev.appIdis omitted, it automatically derivescom.dev.<slug>fromprod.appId(viaderiveDevAppId()), matchingapp.dev.tomlwithout colliding with publishedSignedAppCatalogentries (APP_SPOOFING_DETECTED). Plain{ appId }calls withoutenv/environmentsremain 100% unchanged and always resolve to'prod'. - WASM Initialization & Identity: Loads
jetpack-wasmand restores (or creates)WasmClientIdentity(Ed25519+X25519keys persisted inlocalStorage). - Auto-Pairing (
autoPair: true) & WebSocket Session: If/healthreportsorigin_paired: false(with W3C Private Network Access headers) or the initialClientHellofails because the origin is unpaired, generatesjetpack://pair?client_id=...&pubkey=...&origin=..., invokesonPairingUri(uri), triggers the deep link (unlessdisableAutoDeepLink: true), and polls until approved orpairingTimeoutMs(60000msdefault) elapses, then completes the encryptedX25519/Ed25519handshake onws://127.0.0.1:9470. - Install & Provision Check: Queries
list_apps(). IfappIdis missing, resolvesociReferencefrom options orget_catalog()(verifiedSignedAppCatalog, where host-aware pre-install size estimates viaestimate_catalog_sizes()separate initial download bytes from lazy[models.<name>]runtime weights) and runspull_app(), forwarding download, extraction, and environment stages (oci_layer,runtime_download,runtime_extract,uv_bootstrap,python_standalone,uv_sync) toonProgress(percentisnumber | null). - Worker Boot: Calls
launch_app(appId, resetVolumes, onProgress)if the worker is not alreadyRunning(or attaches this WebSocket session to the running worker), forwarding any just-in-timeruntime_*/uv_*/sandbox_launchapp.launch.progressupdates toonProgress. - Single Active SDK Top Control Bar (
JetPackControlBar): In browser environments (unlesscontrolBar: false), automatically mounts an isolated Shadow-DOM top bar displaying the JetPack logo, app name, aDEVbadge when the resolved environment is'dev', live status pill (Connecting,Running,Stopped,Error),"Control Center"link, optional"Download JetPack"link (onDAEMON_NOT_RUNNING), and a single context-awareLaunch/Stopaction button (enabledStopwhile'Running', enabledLaunchwhile'Stopped'to relaunch or reconnect, and disabledLaunchwhile'Connecting'or'Error'). BothJetPackControlBarandJetPackLogTerminalenforce a strict per-document singleton invariant so reconnecting or creating a new client after connection loss never renders duplicate bars.
Two-Environment Setup (DevEnv & ProdEnv)
Pair app.toml + app.dev.toml on the worker side with env + environments in your frontend (and .env.development / .env.production generated by jetpack init --template fullstack):
import { JetPackAppClient } from '@jetpack-desktop/client';
const client = new JetPackAppClient();
await client.connectAndEnsureApp({
env: 'auto', // Reads VITE_JETPACK_ENV, JETPACK_ENV, import.meta.env.DEV/PROD, NODE_ENV
environments: {
dev: {
appId: import.meta.env.VITE_JETPACK_APP_ID ?? 'com.dev.ocr', // Optional: auto-derives com.dev.ocr from prod.appId
origin: 'http://127.0.0.1:5173',
logTerminal: { developerMode: true },
},
prod: {
appId: 'com.acme.ocr',
origin: 'https://ocr.acme.example',
},
},
});
console.log('Active app:', client.getAppId(), 'env:', client.getEnvironment()); // "com.dev.ocr" / "dev"2. Send Correlated Zero-Copy Binary Requests (request)
Send structured metadata (encoded as MsgPack by jetpack-wasm) alongside a zero-copy Uint8Array payload directly to your ensured worker:
const fileBytes = new Uint8Array(await selectedFile.arrayBuffer());
const response = await client.request(
'media.inspect',
{ filename: selectedFile.name, include_streams: true },
fileBytes,
{ timeoutMs: 30_000 }
);
console.log('Reply opcode:', response.opcode);
console.log('Correlation ID:', response.correlationId);
const jsonSummary = JSON.parse(new TextDecoder().decode(response.payload));
console.log('Probe result:', jsonSummary);Under the hood, request() assigns a monotonic correlation_id, encrypts the HybridFrame with ChaCha20-Poly1305, and resolves once the worker replies with the matching correlation_id (or rejects on app.error / system.error / REQUEST_TIMEOUT). Launched workers stay running until explicitly stopped by the user or daemon/session teardown; if the worker is stopped externally (for example from Control Center or the system tray), exits ("app.worker.stopped"), or client.close() disconnects the session, JetPackControlBar switches to 'Stopped' with an active Launch button that calls ensureWorkerRunning() (or reconnects transparently via connectAndEnsureApp()) when clicked, and request() transparently wakes the worker via ensureWorkerRunning() on your next action.
3. Subscribe to Streaming Events (onStream) & Clean Up (close / destroy)
Subscribe to real-time progress frames, telemetry, or unsolicited worker streams by exact opcode or wildcard '*':
const unsubscribeProgress = client.onStream('media.transcode.progress', (payload, ctx) => {
const text = new TextDecoder().decode(payload);
console.log(`Progress (corr=${ctx.correlationId}):`, text);
});
const unsubscribeAll = client.onStream('*', (payload, ctx) => {
console.debug(`[stream:${ctx.opcode}] ${payload.byteLength} bytes`);
});
// Trigger a long-running transcode request
const result = await client.request(
'media.transcode',
{ preset: 'hevc_videotoolbox', crf: 24 },
new Uint8Array(0)
);
// Clean up when unmounting your UI component
unsubscribeProgress();
unsubscribeAll();
client.close();
// Or call client.destroy() to close the session AND unmount JetPackControlBarclient.close() shuts down the WebSocket, clears all onStream handlers, rejects any pending request() promises with JetPackClientError('CLIENT_CLOSED', ...), and transitions JetPackControlBar to 'Stopped'.
4. Safe Worker Stop, Standalone /apps/<app-id>/, and External https:// Hosting
JetPackControlBar uses attachShadow({ mode: 'open' }) so host CSS never leaks into the bar or confirmation modal, and Control Bar styles never affect your application:
- Confirmation Guard: Clicking Stop opens an in-Shadow-DOM confirmation dialog whenever
warnOnUnsavedWorkevaluates totrue(boolean or predicate callback) oronBeforeStopis provided (andwarnOnUnsavedWorkis notfalse). - Programmatic Stop: Call
await client.stopApp()to sendapp.terminate(terminate_app(appId)) without tearing down the bar, keeping it visible with status'Stopped'. - Standalone MPA/SPA Routes, Dynamic
ui/Bundles & Window Downloads: App frontends served byjetpack-daemonlive under/apps/<app-id>/(http://127.0.0.1:9470/apps/<app-id>/). When an installed package ships its ownui/folder (<root>/apps/<app-id>/<active_version>/ui/),jetpack-daemonserves that decoupled bundle directly (with canonical boundary checks, MPA<subpath>/index.html, and extensionless SPA fallback) before falling back to embedded Control Center assets. By default (open_in_app_window = true), Control Center usesclient.open_url(...)("ui.open_url") sojetpack-daemonopens each app (/apps/<app-id>/) and Control Center in its own OS-nativewryWebView desktop window (WKWebViewon macOS,WebView2on Windows,WebKitGTKon Linux) sharing persistent storage in<root>/webview-dataand supporting both standard HTTP file downloads (into the user'sDownloadsdirectory) andblob:/data:<a download>exports via a nativerfdsave-file dialog (with transparent default-browser fallback when running headless, or browser tabs when"Open Dashboard & Apps in Standalone Windows"is turned off in My Hardware & Security), whilejetpack-daemonmultiplexes HTTP static serving, cross-session worker attachment, and reference-counted cleanup on127.0.0.1:9470. - External
https://Domains &CatalogAppEntry.launch_url: Third-party web frontends hosted on developer domains (e.g., Vercel, Cloudflare Pages, or a customhttps://site) connect seamlessly tohttp://127.0.0.1:9470/healthandws://127.0.0.1:9470thanks to W3C Private Network Access (Access-Control-Allow-Private-Network: true) and canonicalOriginnormalization inpaired_clients.db. When anEd25519-signedSignedAppCatalogentry specifieslaunch_url(anhttps://URL—or loopbackhttp://for local development—whose normalized origin is listed inallowed_origins), Control Center, the system tray Launch / Open menu, andui.open_urlopen that external URL directly (preserving existing query/fragment parameters and appending?lang=<code>) in a dedicated OS-nativewrywindow (WKWebViewwithNSAllowsLocalNetworkingon macOS,WebView2on Windows,WebKitGTKon Linux) or default browser tab instead of/apps/<app-id>/. Both navigation andwindow.openhandlers insidewryinterceptjetpack://pairdeep links cleanly without error pages. - Blocking Install-Gate Overlay for First-Time Visitors: When
jetpack-daemonis unreachable (DAEMON_NOT_RUNNING),JetPackControlBarrenders a Shadow-DOM backdrop scrim (#jetpack-install-banner-host,z-index: 2147483645) that blurs and blocks interaction with the underlying web app while framing strictly belowJetPackControlBar(2147483647) and above the Developer ModeJetPackLogTerminal(2147483646). It never flashes during'Connecting','Running', or'Stopped'. The poster resolves safely frominstallBanner.posterUrl->posterUrl->og:image/twitter:imagemeta tags -> built-in app card fallback, paired with a curved dashed SVG arrow pointing dynamically to "Download JetPack". PassinstallBanner: falseto opt out, orinstallBanner: { posterUrl, message }to customize.
5. Developer Mode Live Log Terminal (JetPackLogTerminal)
When Developer Mode is enabled on the local daemon (developer_mode === true), connectAndEnsureApp() automatically checks get_settings(), subscribes via logs.subscribe, and mounts an isolated Shadow-DOM bottom drawer (JetPackLogTerminal) alongside JetPackControlBar:
- Hidden by default in Standard Mode: If
developer_mode === false, the terminal remains unmounted/hidden and never subscribes tologs.subscribe(daemon also enforcesDEV_MODE_REQUIRED). - Collapsed Bar + Unread Badge: Starts collapsed into a slim bottom bar displaying an unread
WARN/ERRORcounter badge. - Expanded Controls: Clicking the bar expands live logs with auto-scroll, severity coloring (
INFO,WARN,ERROR,DEBUG,TRACE), source filters (All,Daemon,Worker),"Clear", and"Copy Logs"("Copied!"feedback). - Opt-out or Custom Config: Pass
logTerminal: falseto disable auto-mounting orlogTerminal: { title: 'My Worker Logs', maxEntries: 500 }to customize options, or stream manually viaclient.subscribeLogs(entry => ...)/client.unsubscribeLogs().
6. Localization (createI18n, ?lang=, and onLanguageChanged)
connectAndEnsureApp() automatically resolves the active language (controlBar.language → URL ?lang= → DaemonSettings.language → 'en') and localizes JetPackControlBar and JetPackLogTerminal into 'en' or 'uk' (falling back to 'en' for unsupported tags). Your app can read client.getLanguage(), subscribe with client.onLanguageChanged(...), and localize its own strings with zero-dependency createI18n and resolveLanguage. See the full Translations & i18n Guide.
Next Steps
- Inspect all TypeScript interfaces,
createI18n,JetPackControlBar,JetPackLogTerminal, and low-leveljetpack-wasmbindings in the Frontend API Reference. - Review the exact wire layout in the Binary Framing Protocol.
