Repository navigation
webui: in-tab WebLLM relay worker w/ lazy esm.run import - #333
Conversation
User feedback on the standalone-HTML snippet from PR #332: "the html relay code should just be built into that relay tab? but I don't think it should import any remote stuff [...] unless the user clicks the button to start the webllm. like maybe they never use the relay setup at all, wouldn't want to load any third party stuff they never use." Both legit. Reworked the Relay tab: - New "In-browser worker" section directly inside the tab body, between the config grid and the snippet list. Has the same model picker + Worker id input + Connect / Disconnect buttons + live progress bar + status dot + scrolling colour-coded log the standalone page had, styled with the same CSS variables the rest of the relay tab uses so it visually fits in. - WebLLM is loaded via `await import("https://esm.run/@mlc-ai/web-llm")` inside the Connect button's click handler. The static `import { CreateMLCEngine } from ...` at module top is gone -- a user who never opens the Relay tab, or opens it but doesn't click Connect, pays zero third-party bandwidth. Browsers cache the module after the first fetch so subsequent Connects are instant. - Disconnect drops the engine reference (browser GCs the WASM) and closes the EventSource; model weights stay in IndexedDB so the next Connect skips the download. - beforeunload closes the EventSource so the gateway sweeps the worker from /v1/relay/status promptly rather than waiting for the keepalive timeout. - Standalone-HTML snippet ("Browser worker (WebLLM, ESM)") removed from the code-block snippet list -- the in-tab worker covers the same use case and the rendered HTML for the page was ~11KB of dead weight on every webui load. The remaining snippets (CLI flags, env vars, Python, cog-relay) are still useful: those run on different host platforms. - buildBrowserSnippet() helper deleted (~250 LOC). - Outer "Connect a worker" heading renamed to "Connect a worker from another host" to differentiate from the new in-tab option. jsdom smoke verified all of: - in-browser worker UI present - no eager static `import { CreateMLCEngine } from esm.run` anywhere - dynamic `await import(esm.run)` is present (gated behind click) - tab renders with zero runtime errors - model dropdown populated (11 curated entries + placeholder) - Connect enabled / Disconnect disabled at start - code-block snippet count down from 5 to 4 Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]> Claude-Session: https://claude.ai/code/session_01TBcLtmpj7dqA5tyFbGnQon
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 57f4ce7645
ℹ️ About Codex in GitHub
Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".
| who never opens this section never pays the esm.run download | ||
| cost. Browsers cache the module so subsequent Connects are | ||
| instant. */ | ||
| webllm = await import("https://esm.run/@mlc-ai/web-llm"); |
There was a problem hiding this comment.
Sandbox the CDN import outside the gateway origin
When the operator clicks Connect, this cross-origin module is evaluated in the web UI's own origin, not in esm.run's origin. Since the gateway bearer token is stored in this page's localStorage and the same script realm can call the privileged /v1/* APIs, any compromised CDN/package code in this import can exfiltrate the token or mutate gateway state; the previous standalone snippet did not run third-party code inside the authenticated gateway UI. Load WebLLM in a sandboxed iframe/worker with a separate origin or keep the browser worker isolated from the main UI origin.
Useful? React with 👍 / 👎.
| const c = await _relayInbState.engine.chat.completions.create({ | ||
| messages: req.messages, | ||
| temperature: parseFloat(req.options?.temperature ?? "0"), | ||
| max_tokens: req.options?.max_tokens ?? 512, | ||
| }); |
There was a problem hiding this comment.
Pass relay tools into WebLLM completions
For in-tab workers serving an agent request with non-empty req.tools, this completion call drops the relay envelope's tools entirely, even though the gateway serializes them for workers and this code later forwards returned tool_calls. That means the WebLLM worker can never produce structured tool calls for PasClaw tool-using flows, so those requests degrade to text-only behavior or stall waiting for tool dispatch; include req.tools (and any tool-choice option when present) in the chat.completions.create request.
Useful? React with 👍 / 👎.
Two stacked fixes addressing the PR #333 P1 code review and the "each new serve should generate a relay-only token" follow-up. WHY (P1 from review): Loading @mlc-ai/web-llm via dynamic import in the parent page was gated on a button click, which deferred the network fetch -- but did NOT isolate the third-party code from the gateway UI's origin. Once loaded, the module sat in the same script realm as the webui: it could read localStorage["pasclaw.gw_token.v1"], call any /v1/* endpoint with the operator's credentials, and mutate the parent DOM. A compromised CDN / typo-squat / supply-chain push reached the whole authenticated PasClaw surface. WHAT (sandbox): In-browser worker now lives inside a `<iframe sandbox="allow-scripts">` (no allow-same-origin -> opaque null origin). The webllm import and EventSource + dispatch loop run there; the parent UI only renders status / progress / log lines relayed via postMessage. Parent <-> child wire protocol (postMessage): parent -> child : connect{url,token,model,workerId} | disconnect child -> parent: ready | log | status | progress | job-served | connected | disconnected | connection-failed Source identity filter (event.source === iframeEl.contentWindow) not origin string -- null-origin iframes emit "null" but sticking to identity is robust to spec drift. WHAT (scoped token): TGatewayServer.Create generates a fresh FRelayToken on every startup -- 8 Crockford base32 chars in two 4-char groups (A8M9-PXRT, ~40 bits entropy, phone-typable, no I/L/O/U confusables). Dual-token auth at the OnCommandGet gate accepts EITHER the main Cfg.Gateway.Token OR FRelayToken for /v1/relay/* paths (case-insensitive, hyphens stripped before compare so dictated tokens work). Main-token endpoints (/v1/chat /v1/config /v1/skills/...) reject the scoped token -- a compromised in-tab worker can pull jobs but cannot impersonate the operator. New GET /v1/relay/worker-token returns the scoped token as JSON. Gated by the MAIN token via the normal auth check (the dual-token helper deliberately excludes this path) so an attacker who only has the relay token cannot escalate to read it. CORS-stamped. pasclaw serve / pasclaw gateway print the token on startup so external `pasclaw relay` CLIs can use scoped credentials too. WHAT (webui plumbing): setupInBrowserWorker creates the sandboxed iframe on tab init (srcdoc carries the postMessage responder + dynamic-import scaffold; ~3.8 KB inline). inbWorkerConnect first fetches /v1/relay/worker-token using gwFetch (main token), then postMessages the SCOPED token to the iframe -- the main token never crosses the origin boundary. UI hint text updated to surface the trust boundary so operators understand what's isolated and what isn't. Three new bindings (_relayInbIframe / _relayInbReady / _relayInbJobs) declared above the boot block alongside the other relay-tab state, same TDZ pattern PR #324/#326 already established (deep-linked /#relay loads the tab before the relay-impl block runs). VERIFIED: - Static checks: iframe sandbox attr = "allow-scripts" without allow-same-origin; no eager `import {CreateMLCEngine} from esm.run` in the outer page; dynamic import present only inside the srcdoc; UI hint mentions sandbox and relay-scoped token. - jsdom render: zero runtime errors, iframe in DOM, srcdoc 3.8 KB with `await import('https://esm.run/...')` + postMessage logic. - Endpoint smoke (gateway with main token MAINTOKEN): no-auth /v1/relay/worker-token -> 401 relay-token-only worker-token -> 401 main-token /v1/relay/worker-token -> 200 {"token":"KP44-5XZ3"} scoped /v1/relay/status -> 200 scoped /v1/config -> 401 (blast-radius contained) main /v1/config -> 200 lowercase / no-hyphen scoped tokens -> 200 (case-insensitive) Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]> Claude-Session: https://claude.ai/code/session_01TBcLtmpj7dqA5tyFbGnQon
Codex P2 review on PR #333. The sandboxed in-browser worker called engine.chat.completions.create with only messages / temperature / max_tokens -- tools were silently dropped. WebLLM (and any OpenAI-shaped completion API) won't emit structured tool_calls unless you advertise the tools to it, so any agent-driven turn with non-empty req.tools either degraded to text-only output or stalled when the gateway-side tool loop waited for a structured call that never came. Three coordinated fixes so the round-trip works end-to-end: - BuildRelayRequestBody (PasClaw.Providers.Relay.pas) now emits Options.ToolChoice on the wire as `options.tool_choice` when non-empty. Skipped when empty so the envelope stays compact for the common auto-choice case. - DecodeOptions (PasClaw.Cmd.Relay.pas) reads it back into TChatOptions.ToolChoice so the CLI Indy / NetHTTP workers thread it through their local provider too. The CLI workers were already passing Tools through Provider.Chat -- only the in-browser path had the bug -- but adding ToolChoice to the decode side makes the wire symmetric. - The iframe srcdoc's chat.completions.create call now maps req.tools (envelope shape: { name, description, parameters: JSON-string-containing-JSON }) into OpenAI shape ({ type:'function', function: { name, description, parameters: <object> } }) and JSON.parses the parameter-schema string so WebLLM sees the actual schema object it expects. tool_choice is forwarded when req.options carries one. Tests: src/tests/relay_queue_tests.pas gains `tool_choice round-trips through the request envelope` covering non-empty emit + empty omit on BuildRelayRequestBody. 23/23 relay queue tests green. jsdom verify on the rendered webui: srcdoc has req.tools mapping -> yes srcdoc maps to OpenAI type:'function' -> yes srcdoc JSON.parses the schema string -> yes srcdoc threads req.options.tool_choice -> yes tab renders with zero runtime errors -> yes Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]> Claude-Session: https://claude.ai/code/session_01TBcLtmpj7dqA5tyFbGnQon
+ snippets use the scoped token end-to-end Two issues user reported after PR FMXExpress#333 merged: 1. Clicking Connect from the in-tab worker died with "engine init failed: The operation is insecure." That's the fundamental limitation of opaque-origin iframes: sandbox without allow-same-origin gives the iframe an opaque null origin, and opaque origins cannot open IndexedDB. WebLLM caches multi-GB model weights there and refuses to init without it. We were on the wrong side of an inherent browser tradeoff: lose IndexedDB OR lose origin isolation. 2. The relay tab still rendered snippets with the MAIN gateway token. The whole point of the per-process scoped token from the previous commit was to hand external workers a credential that doesn't unlock /v1/chat etc -- but the UI was leaking the main token into every copy-paste block. FIX 1: switch from sandboxed iframe to dedicated Web Worker. - Workers are same-origin, so IndexedDB + WebGPU + SharedArrayBuffer all work. WebLLM can actually start. - Worker scope has no `window` and no `localStorage` -- the isolation property we wanted from the iframe is still here. - No DOM access; communicates only via postMessage. The parent UI hands the worker a token via postMessage at Connect time; that token is the ONLY credential the worker ever sees. - PasClaw uses bearer-token auth (no cookies), so a same-origin fetch from the worker has no implicit credentials. The worker can call /v1/* only with tokens we explicitly pass it, and we only pass the relay-scoped token. Module worker spawned from a Blob: URL with `{type: 'module'}` so `await import('https://esm.run/...')` still works inside; the WebLLM fetch stays gated behind the Connect click. EventSource is exposed in DedicatedWorker scope in every evergreen browser. Hint text in the Relay tab updated: "dedicated Web Worker (no window / localStorage in Worker scope)" instead of the old "opaque-origin sandboxed iframe" copy. FIX 2: snippets render the relay-scoped token, not the main token. - setupRelayTab now eagerly calls GET /v1/relay/worker-token at tab load (gated by main token, so unauth'd gateways return 200 anyway) and caches the result in _relayScopedToken. - relayEffectiveToken returns _relayScopedToken when "show" is on; the placeholder when masked. - syncRelayTokenInput renders the scoped token (or "fetching ..." while the GET is in flight). The input label changed from "Bearer token" to "Relay worker token" with a fresh hint paragraph explaining the scoping. - The placeholder string changed from <PASCLAW_GATEWAY_TOKEN> to <PASCLAW_RELAY_TOKEN> -- when an operator screen-shares the masked snippets, the visible text now names the right env var. - env-vars snippet uses `export PASCLAW_RELAY_TOKEN=...` instead of `PASCLAW_GATEWAY_TOKEN`. Verified rendered output contains no occurrence of the operator's main token. CLI parity: PasClaw.Cmd.Relay now reads PASCLAW_RELAY_TOKEN as the preferred env var (the scoped credential printed at `pasclaw serve` startup), falling back to PASCLAW_GATEWAY_TOKEN for back-compat. Both work; the snippet defaults to the more specific name. Smoke (gateway with main token MAINTOKEN, port 18910): - jsdom render at /#relay: zero runtime errors - server-side GET /v1/relay/worker-token returns HENQ-4WW2 - env-vars snippet body: export PASCLAW_GATEWAY_URL=http://127.0.0.1:18910 export PASCLAW_RELAY_TOKEN=<PASCLAW_RELAY_TOKEN> pasclaw relay - snippet contains "MAINTOKEN": false (main token never leaks) - 23/23 relay queue tests still green Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]> Claude-Session: https://claude.ai/code/session_01TBcLtmpj7dqA5tyFbGnQon
Summary
Reworks the Relay tab per the user's two asks on PR #332:
In-tab worker, not a copy-paste page. New "In-browser worker" section directly inside the Relay tab body (between the config grid and the snippet list) with the same model picker + Worker id input + Connect / Disconnect buttons + live progress bar + status dot + scrolling colour-coded log the standalone page had.
Zero third-party fetch until clicked. WebLLM is loaded via
await import("https://esm.run/@mlc-ai/web-llm")inside the Connect button's click handler. The staticimport { CreateMLCEngine } from ...at module top is gone — a user who never opens the Relay tab, or opens it but doesn't click Connect, pays zero esm.run bandwidth. Browsers cache the module after the first fetch so subsequent Connects are instant.Cleanup:
buildBrowserSnippet()helper deleted (~250 LOC).Lifecycle:
CreateMLCEnginewithinitProgressCallbackdriving the progress bar, then opensEventSourceto/v1/relay/pollwith?worker_id=+?caps=query params (+?token=if a token is configured).beforeunload: closes the EventSource so the gateway sweeps the worker from/v1/relay/statuspromptly.Test plan
make allclean./#relaydeep link, all of:#relay-inb-model,#relay-inb-connect)import { CreateMLCEngine } from esm.runanywhere in the rendered HTMLawait import("https://esm.run/...")present (gated behind click)🤖 Generated with Claude Code
https://claude.ai/code/session_01TBcLtmpj7dqA5tyFbGnQon
Generated by Claude Code