Skip to content

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

Closed

Description

@AlexAlves87

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

Activity

  1. github-actions commented on Apr 21, 2026

    @github-actions
    Contributor

    🤖 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

    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
    
  2. added
    enhancement
    on Apr 21, 2026
  3. shanselman commented on Apr 28, 2026

    @shanselman
    Collaborator

    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.

  4. shanselman commented on May 1, 2026

    @shanselman
    Collaborator

    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:

    • Add shared { type, payload } WebBridgeMessage contract
    • Add WebChatWindow SPA → native bridge via WebMessageReceived
    • 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 Add first-pass Windows Voice Mode #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.

  5. AlexAlves87 commented on May 1, 2026

    @AlexAlves87
    ContributorAuthor

    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.

  6. AlexAlves87 commented on May 7, 2026

    @AlexAlves87
    ContributorAuthor
  7. shanselman commented on May 7, 2026

    @shanselman
    Collaborator

    Status update after the latest triage:

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

  8. shanselman commented on May 18, 2026

    @shanselman
    Collaborator

    Closing this as completed enough for the original architecture proposal.

    What landed:

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

  9. locked as resolved and limited conversation to collaborators on May 29, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    enhancement

    Type

    No type

    Fields

    Priority

    None yet

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions