openclaw-windows-node icon indicating copy to clipboard operation
openclaw-windows-node copied to clipboard

[Proposal] Add a formal WebView2 bridge for native ↔ SPA communication

Open AlexAlves87 opened this issue 7 months ago • 7 comments

Right now WebChatWindow and CanvasWindow both load gateway content in WebView2, but there's no formal communication channel between the native C# side and the embedded SPA. The two halves run disconnected, which shows up in a few places already:

Surface Current situation
WebChatWindow No bridge at all. Native code has no way to signal UI state to the SPA (recording indicator, draft text, activity spinner)
CanvasWindow One-way native→web channel via ExecuteScriptAsync with 11 heuristic fallbacks. No web→native channel
Voice PR #120 (NichUK) Works around the gap with DOM scraping (querySelector, MutationObserver, descriptor hacks). The author describes it as fragile
Screen record PR #159 No way to show a recording indicator in the SPA while the app is capturing
QuickSendDialog Can send messages over WebSocket but can't coordinate UI state with the embedded chat

The fix

WebView2 ships a proper bidirectional bridge that doesn't touch the DOM at all:

Native → SPA

// Inject bootstrap before any page scripts run
await webView.CoreWebView2.AddScriptToExecuteOnDocumentCreatedAsync(BridgeInitScript);

// Send a message at any point
webView.CoreWebView2.PostWebMessageAsJson(JsonSerializer.Serialize(msg));

SPA → Native

webView.CoreWebView2.WebMessageReceived += (_, e) => {
    var msg = JsonSerializer.Deserialize<BridgeMessage>(e.WebMessageAsJson);
    HandleBridgeMessage(msg);
};

Gateway SPA side

// Receive from native
window.chrome.webview.addEventListener('message', e => {
    const msg = e.data; // { type, payload }
    // dispatch by type
});

// Send to native
window.chrome.webview.postMessage({ type: 'ready' });

Minimal message contract to start

{ "type": "recording-start", "payload": {} }
{ "type": "recording-stop",  "payload": {} }
{ "type": "voice-start",     "payload": {} }
{ "type": "voice-stop",      "payload": {} }
{ "type": "draft-text",      "payload": { "text": "..." } }
{ "type": "ready",           "payload": {} }

Scope

This touches two repos:

  1. This repo — wire the bridge in WebChatWindow.xaml.cs and CanvasWindow.xaml.cs
  2. Gateway — expose the window.chrome.webview listener in the SPA

The existing WebSocket transport (chat.send) stays as-is — it handles chat messages. The bridge is purely for UI state coordination.

Happy to put together a PR for the Windows side once there's alignment on the gateway contract.

Related

  • #120 (NichUK, Voice Mode) — the DOM scraping approach there would be cleanly replaced by this
  • #159 (screen recording) — needs a recording-active indicator in the chat view

AlexAlves87 avatar Apr 20 '26 18:04 AlexAlves87

🤖 This is an automated response from Repo Assist.

Great proposal, @AlexAlves87 — the gap you've described is real and the WebView2 PostWebMessageAsJson / WebMessageReceived API is exactly the right fix.

A few notes from looking at the existing code:

Current state

Window Inbound (SPA→native) Outbound (native→SPA)
WebChatWindow ❌ none ❌ none
CanvasWindow ❌ none ⚠️ ExecuteScriptAsync with 11 heuristic fallbacks (the fragile pattern you described)

window.chrome.webview is automatically available in any WebView2-hosted page — no bootstrap injection needed on the native side. That keeps the wiring minimal.

Impact on open PRs

  • #120 Voice Mode — NichUK's MutationObserver/querySelector hacks would be cleanly replaced by voice-start/voice-stop bridge messages
  • #159 Screen recording — recording indicator in the SPA would land via recording-start/recording-stop

PR

I've opened a draft PR ([#aw_pr191br]) that wires the full bidirectional bridge on the Windows side of WebChatWindow:

  • CoreWebView2.WebMessageReceived → fires a BridgeMessageReceived event on the window (SPA→native)
  • PostBridgeMessage(string type, object? payload) method (native→SPA via PostWebMessageAsJson)
  • WebBridgeMessage record in OpenClaw.Shared with TryParse/ToJson and the well-known type constants from your proposal
  • Handler stored and cleaned up in OnWindowClosed — no leak

Callers in App.xaml.cs can subscribe to BridgeMessageReceived and call PostBridgeMessage once the gateway SPA side exposes the listener.

The SPA-side change (adding window.chrome.webview.addEventListener('message', ...) to the gateway) is out of scope for this repo — that's the remaining piece to close the loop.

Generated by 🌈 Repo Assist, see workflow run. Learn more.

To install this agentic workflow, run

gh aw add githubnext/agentics/workflows/repo-assist.md@97143ac59cb3a13ef2a77581f929f06719c7402a

github-actions[bot] avatar Apr 21 '26 01:04 github-actions[bot]

Implemented the Windows WebChat side of this proposal in #192 / c7630fa.

Credit to @AlexAlves87 for the original WebView2 native ↔ SPA bridge proposal, the { type, payload } message-contract shape, and the parity rationale around avoiding DOM scraping for voice, recording indicators, draft text, and future UI-state coordination.

The merged implementation follows the core direction from this issue and adds Windows-side hardening around origin validation, dispatcher marshaling for WebView2 calls, closed-window guards, sanitized bridge logging, and payload JSON validation.

shanselman avatar Apr 28 '26 03:04 shanselman

Thanks again for writing this up, @AlexAlves87. This proposal has been useful architecture guidance, and the first Windows-side slice landed in #192 / c7630fa.

Current status after #192:

  • [x] Add shared { type, payload } WebBridgeMessage contract
  • [x] Add WebChatWindow SPA → native bridge via WebMessageReceived
  • [x] Add WebChatWindow native → SPA bridge via PostWebMessageAsJson
  • [ ] Add equivalent bridge surface to CanvasWindow, replacing fragile ExecuteScriptAsync message paths where appropriate
  • [ ] Add/verify gateway SPA-side window.chrome.webview.addEventListener('message', ...)
  • [ ] Wire concrete producers/consumers for recording, voice, and draft-text messages as those features land

I don’t think we should close this as fully completed yet unless we intentionally narrow it to “WebChat bridge only.” The issue’s original scope also called out CanvasWindow and gateway/SPA-side listener work, and #192 deliberately left those as follow-ups.

Suggested next steps:

  1. Keep this open as the tracking issue for the remaining bridge work.
  2. Split the next Windows PR to focus only on CanvasWindow bridge parity.
  3. Track the gateway SPA listener separately if it needs to land in the gateway repo.
  4. Let #120 / future voice-mode PRs build on this bridge rather than using DOM scraping.

That keeps the original architectural direction intact while letting us continue landing the work in smaller reviewable slices.

shanselman avatar May 01 '26 19:05 shanselman

Thanks for the detailed status breakdown, @shanselman. I'll take the CanvasWindow bridge parity as the next slice, same pattern as WebChatWindow, replacing the ExecuteScriptAsync paths where appropriate.

AlexAlves87 avatar May 01 '26 20:05 AlexAlves87

  • [x] Add shared { type, payload } WebBridgeMessage contract
  • [x] Add WebChatWindow SPA → native bridge via WebMessageReceived
  • [x] Add WebChatWindow native → SPA bridge via PostWebMessageAsJson
  • [x] Add equivalent bridge surface to CanvasWindow — closed by #259
  • [ ] Add/verify gateway SPA-side window.chrome.webview.addEventListener('message', ...) — in progress at openclaw/openclaw#69633
  • [ ] Wire concrete producers/consumers for recording, voice, and draft-text — pending #69633

AlexAlves87 avatar May 07 '26 16:05 AlexAlves87

Status update after the latest triage:

  • Windows WebChat bridge slice is already landed via #192 / c7630fa.
  • Windows Canvas bridge parity is now landed via #259.
  • Remaining work is still gateway-side SPA listener support (window.chrome.webview.addEventListener('message', ...), tracked in openclaw/openclaw#69633) plus concrete producers/consumers for recording, voice, and draft-text messages.

Keeping this issue open as the tracker for those remaining bridge integration pieces.

shanselman avatar May 07 '26 22:05 shanselman

Closing this as completed enough for the original architecture proposal.

What landed:

  • Windows WebChat bridge via #192 / c7630fa
  • Canvas bridge parity via #259
  • Upstream SPA-side WebView2 bridge listener support in openclaw/openclaw#69633

Future work should be tracked as feature-specific producer/consumer issues, not by keeping this broad bridge proposal open indefinitely.

shanselman avatar May 18 '26 00:05 shanselman