Navigation
ELOWEN · Documentation

Last updated: October 27, 2026

Browse documentation · browser implementation
Developer reference

browser implementation

Problem audiences

Page preparation and live-page reads preserve the core typed instance-condition cause. Browser command deadlines are local outcomes for the user-selected page. Display process exits from SIGTERM, SIGINT or SIGKILL stay local; unexpected exit codes and crash signals remain reportable. VirtualDisplayPool.failure now returns the typed Error, and the registry preserves its message and audience when recycling sessions. Owner log messages, teardown behavior and scheduling are unchanged. This requires the paired core candidate's exported elowen-plugin-shared/errors seam.

Migration entry

The manifest entry exports migrate(db: PluginDb<never>): Promise<void> beside register. The daemon loader always awaits it before registration for this reads: ['db'] plugin; the DB CLI calls the same export without registering tools, routes, timers or services. The export runs only the existing transactional plugin SQL through db.migrate. A failed step rolls back its SQL and ledger entry and prevents registration. Repeated calls skip applied versions. Runtime store construction never invokes migrations. Tests that bypass the loader explicitly await this export before using their fixture.

Asynchronous profile I/O

BrowserPool.profileSize(userId) returns a promise and walks sequentially through filesystem promises, retaining the real-directory check, symlink exclusions and existing 100,000-directory limit. Only ENOENT races while walking or measuring files are skipped; permission and I/O failures propagate to the profile API's existing error response. There is no size cache or new timeout.

BrowserPool.clearProfile(userId) checks active launches, sessions and closings, validates the real directory and renames it synchronously before its first await. It then awaits recursive deletion of only the renamed directory, so a newly launched browser's replacement profile survives. SessionRegistry awaits clear and account deletion; deleteUser removes database records only after profile cleanup succeeds. GET and DELETE profile await the same methods. Filesystem failures retain the existing sanitized API response. No deletion queue is added; interruption may leave the detached directory.

Bounded session cleanup

The host awaits the entry export migrate(db) before registration publishes any service. The store uses the async PluginDb in the explicitly quoted plugin_browser schema. Migration 8 is the baseline that creates the sessions, processes and displays tables. Installed ledgers already record it, so it is never renumbered and later steps start at version 9. Session rows have a generated bigint row_id for bounded retention. Store methods resolve after their SQL completes; generated identity values never appear in HTTP DTOs.

Closed-history retention and account deletion use drainDbRows from elowen-plugin-shared/dbBatches with separate schema, table and identity names. The helper locks matching identities in order and measures UTF-8 id, state and nullable close reason plus 256 bytes of row overhead. Each transaction removes at most 64 rows / 256 KiB, processes one oversized row alone and yields after commit. The partial sessions_expiry index covers closed-history selection. Boot reconciliation retains its 64-row UPDATE batches and uses the same module's yieldDbBatch. Production rows normally contain only a few KiB, without transcripts or images. SessionRegistry awaits each operation before acknowledging completion or proceeding to orphan-process cleanup. Interrupted cleanup can resume by repeating the same predicate. Process and display records are removed only after the account's session drain completes. An empty deletion predicate returns without yielding.

Initial account page

BrowserPool captures Chrome's sole page target at launch only when it is about:blank. The first openPage consumes that target before awaiting CDP, reuses its still-open blank page and installs the same proxy authentication and primary-tab ownership as a newly created page. Concurrent and later opens create distinct pages. A launch with other pages, or an initial page already navigated or closed, is left alone; no live blank-tab scan or cleanup runs. Agent/user-created blank tabs are never reused or closed by this rule. Managed-Project conversations use this same account browser, not the Sandbox desktop's Chrome. Headless Site captures own disposable browsers and have no shared session tabs.

Developer reference

src/apiContract.ts::apiRoutes is the side-effect-free declaration of all 14 Browser routes: nine account/admin routes registered by src/api.ts::registerBrowserApi, plus the five descriptors spread directly from elowen-plugin-shared/desktopApiContract::desktopApiRoutes. Those shared descriptor objects and their canonical schemas are the same objects the host's DesktopRuntime.register uses; Browser maintains no second desktop route list. Each descriptor owns its method, path, access, English summary, canonical Zod inputs, credential policy and response kind; registration adds only its handler. The desktop control event stream declares stream; the other 13 responses declare json. Registration does not launch Chrome or probe dependencies. SSE and one-use WebSocket tickets retain their native transport and live-view/lease checks.

Packaged provides.apiRoutes contains the 14 method/path security projections generated from this object by core's generate-plugin-api-manifests.mjs. The generator uses the same canonical projector as runtime admission; summaries, schemas and handlers are not embedded in the manifest. tests/pluginApiProjectsPurposes.test.ts parses the packaged manifest with the selected core and verifies every actual registration against it.

Account/admin handlers pass the descriptor's exact schemas to lazy req.json and req.parseQuery at their original admission points. Account admission precedes session-query parsing; navigation action validation precedes session ownership, while lease validation follows ownership. The lease field is deliberately staged rather than eagerly narrowed. Unknown body fields pass through, session identifiers are not trimmed, and malformed JSON still reaches Browser's existing HTTP 400 envelope. tests/pluginApiProjectsPurposes.test.ts captures the nine authored registrations and the actual host desktop registrations, verifies all 14 against the pure descriptors and canonical security projector, and checks schema references through core's registration record. It also exercises these ordering/error contracts using core's real raw-body parsers.

Browser tool ownership awaits the host's currentIdentity() before resolving the linked account and private conversation. Both BrowserOpen and existing-session tools await this authorization; shared rooms and delegated child agents retain their existing refusals.

The provider implements the host's BrowserCaptureRequest, BrowserCaptureResult and BrowserCaptureControl types. Its local dispose() stops active captures on plugin shutdown. The account launcher and capture launcher share only Puppeteer loading and common network/background arguments in src/puppeteer.ts. Account sessions stay headed with a persistent profile and private display; captures stay headless with an isolated disposable profile and an origin-pinned proxy. Both retain Chrome's sandbox defaults. Without a registered capture provider, Sites reports capture unavailable; registration allocates no Chrome process and the asynchronous availability probe only loads dependencies.

Browser host waits use withTimeout from elowen-plugin-shared/withTimeout; src/deadline.ts only defines BrowserDeadlineError. Call withTimeout(work, milliseconds, new BrowserDeadlineError(message)) with an existing promise or a callback. A callback runs once after the timer is armed; synchronous throws retain their original identity. The helper clears and unreferences its timer on settlement and rejects on expiry with the exact supplied error. It bounds the wait without cancelling the browser command. Favicon lookup is one consumer: it waits at most five seconds and publishes no icon on failure. BrowserSession, tab reads and tracing use their existing per-command budgets; the operation safety handler recycles Chrome only for its own 45-second deadline, and tracing recycles Chrome when its state becomes unknown. Site capture keeps its separate resolve-on-expiry and abort races. Importing the helper allocates no timer or browser; each call allocates one timer and requires a core package that actually ships this shared export. Closing aborts waiting agent work once with the actual close reason, then abandons tracing, removes listeners, detaches CDP and releases the page.

src/queue.ts::SerialQueue serializes each BrowserSession's operations and each SessionRegistry's creation requests through separate queue instances. Its promise tail continues after a rejection; it introduces no global scheduler or work while idle. src/process-identity.ts::processIdentityMatches(snapshot, startedAtTicks, executablePath, argToken) compares one freshly inspected process with its recorded start tick, executable and exact command-line token. BrowserPool close, registry boot reconciliation and virtual-display orphan cleanup share this predicate. Registry escalation inspects again immediately before delayed SIGKILL, preserving PID-reuse refusal and each caller's reporting policy. These are plugin-local helpers, with no new host export or persistent record shape.

web-src/useBrowserSessions.ts owns the signed-in account read, account/session thumbnail key and request, sessions listing and close mutation for BrowserAccount and BrowserChatDock. useBrowserThumbnail delegates cadence and visibility to host useDesktopStill; the dock additionally requires a known account, collapsed view, no held lease and an open stream. useCloseBrowserSession posts the selected session id and invalidates both sessions and profile after success. Callers retain their error toasts and confirmation state; a refusal invalidates neither cache. Importing the hooks issues no request until a surface mounts.

Session patches use one UPDATE containing only named fields, so disjoint concurrent patches preserve each other. BrowserSession orders persistence through one promise tail. Synchronous controller and viewer-activity notifications enqueue their captured state; failures are logged immediately with the existing plugin.service_failed problem code and remain rejected for the next awaited operation or close. Session close and idle/expiry/recycle callbacks observe rejected cleanup promises. Chrome, its proxy and its display are released even if reading or deleting the process ownership row fails. Startup, shutdown, process/display ownership and orphan reconciliation await their records before continuing. BrowserPool reserves each account's launch before awaiting its old process record, so simultaneous opens share the same launch. Missing and foreign live-session ids both raise BrowserAccessError with status 404 at the registry boundary, which the HTTP API forwards independently of message wording.

Browser UI requires host UI API 55 in both its manifest and registration. Its runtime uses the published ElowenUiRuntime['api'] and ElowenUiRuntime['utils']['interpolate'] types without a local fallback. BrowserAccount uses host interpolation for the running-session count. Without an installed host runtime, the plugin throws instead of rendering a substitute; an unsupported host is rejected by the UI compatibility gate. These runtime declarations do not allocate requests or browser sessions. JSON request serialization belongs to the host API boundary; BrowserChatDock sends navigation as { method: 'POST', json: { leaseId, action } } and close as { method: 'POST' }.

Chat dock, takeover and capture contract

Account Chrome keeps defaultViewport: null; its window fills the private display, with no device-metrics override or CDP screencast. Native page zoom remains user-owned and can persist in the profile. src/capture.ts reads cssVisualViewport for its size budget and captures the native viewport without an explicit clip, preserving its scroll offset and fractional device pixels. Explicit thumbnail, full-page and element clips convert CSS pixels to DIP with cssVisualViewport.zoom; thumbnails include the visible viewport's document offset. Image metadata comes from PNG IHDR or JPEG Start Of Frame dimensions rather than predicting Chrome's fractional-DIP rasterization. Thumbnails cap the encoded width at 480 physical pixels using the current window.devicePixelRatio. Missing scale information fails explicitly.

Accessibility refs, DOM boxes and Input.dispatchMouseEvent stay in CSS pixels; only capture clips cross into DIP. BrowserChatDock delegates fitting to the host DesktopPreview, whose still uses centred object-fit: contain; no plugin transform or second scale is applied. The expanded VNC view remains the native whole-window framebuffer, including browser chrome. The opt-in tests/browserViewport.test.ts launches the production factory on a temporary profile/private display and checks native zoom 80/100/125%, device scale 1/1.25/2, PNG/JPEG edge pixels, encoded dimensions, scrolled capture and ref-based clicks.

The chat dock is host-drawn: the host owns the tile, the enlarged view, keyboard and Escape handling and the space it reserves above the composer. Browser supplies only the session title, the picture, the address, the navigation controls and the Close session action.

At every width the collapsed tile shows a refreshed still rather than a framebuffer connection. useBrowserThumbnail delegates cadence, response validation, account/session cache identity and expiry to the host useDesktopStill hook, so chat and account pictures share it, and polling pauses while the view is expanded, outside the viewport or in a hidden document. The address stays visible inside the enlarged controls, including on a phone, where the enlarged view is watch-only.

A takeover belongs to one connected viewer and is never held at the same time as an agent action: while an agent command is still running the handover stays pending and the pointer and keyboard stay view-only. Remounting a view does not restore a private lease, and the viewer's browser has to keep renewing the lease, which defaults to 120 seconds and is configurable from 30 to 600. Returning control refreshes the page title and address; a failed or timed-out title read keeps the last successful page identity and logs the failure, while a successful empty title stays empty.

browserCapture is the Sites capture control. It is separate from an account's own sessions, limited to one public HTTPS origin, and never exposed to the agent as a tool.

The Status panel probes five dependencies: Chrome, browser control, the virtual display, the network proxy and profile storage. Live-view transport belongs to the host desktop-provider contract and is not a probed dependency; the isolation badge reports the network-proxy outcome, and the per-account profile line describes the storage architecture rather than a health probe. The sandbox and the DevTools connection are verified at first launch, so a green panel does not guarantee that a session starts.

A session is recycled when an operation exceeds the 45-second safety deadline or when a navigation's cancellation cannot be confirmed.

Next: Scheduling Plugin