cmux/Sources/Panels/ReactGrab.swift
Lawrence Chen dd54927cb9
Add React Grab inject button to browser toolbar (#2373)
* Add React Grab inject button to browser toolbar

Adds a toolbar button (cursor click icon) that injects the react-grab
script (unpkg.com/react-grab/dist/index.global.js) into the current
page. Hover over React elements and Cmd+C to copy component context
(file, component name, line number) for AI agents.

Button highlights when active, resets on navigation.

* Auto-activate selection mode on React Grab inject

First click: injects the script and auto-activates selection mode via
the react-grab:init event. Subsequent clicks toggle selection mode
on/off via window.__REACT_GRAB__.toggle().

* Bridge React Grab state back to Swift via WKScriptMessageHandler

Register a cmux-bridge plugin after injecting react-grab that posts
state changes back to Swift via webkit.messageHandlers. The button
now highlights accent color only when selection mode is actually
active (not just when the script is loaded), and deactivates when
the user exits selection mode via Escape or the react-grab toolbar.

* Fetch react-grab script via URLSession to bypass CSP

Sites like vercel.com block loading external scripts via CSP headers.
Fetch the script with URLSession (not subject to page CSP), cache it,
and inject inline via evaluateJavaScript. Also guard against duplicate
injection on repeated clicks.

* Prefetch react-grab script on first browser panel init

Kick off a low-priority background fetch of the react-grab script
when the first BrowserPanel is created. The script is cached
statically so clicking the button is instant.

* Eliminate react-grab button and callback lag

Three changes:
1. Fire-and-forget: use evaluateJavaScript with completionHandler
   instead of await, so button taps return immediately.
2. Single JS payload: combine bootstrap listener + script source
   into one evaluateJavaScript call (one IPC round-trip, not two).
3. Dedupe state callbacks: only post webkit message when isActive
   actually changes, not on every hover/drag state update.

* Fix duplicate state callback on react-grab toggle

toggleReactGrab was sending an explicit postMessage AND the plugin's
onStateChange hook was firing too, causing two @Published updates per
toggle. Remove the explicit postMessage since the plugin hook handles
it. Also add dlog instrumentation for debugging.

* Add Cmd+Shift+G shortcut for React Grab (configurable)

- Add toggleReactGrab to KeyboardShortcutSettings with Cmd+Shift+G default
- Add View menu item with customizable shortcut
- Add command palette entry (searchable as "react grab" or "inspect element")
- Simplify button to use toggleOrInjectReactGrab, remove local state tracking

* Fix Codex review findings: pin version, verify hash, fix retry and state

1. Pin react-grab to exact version (0.1.29) with SHA-256 integrity
   check. Script is verified before evaluation to prevent supply-chain
   attacks via compromised CDN responses.
2. Clear prefetchTask on failure so subsequent attempts retry the
   download instead of reusing a permanently failed task.
3. Remove premature isReactGrabActive=true. State is now only set
   by the onStateChange message handler callback after confirmed
   initialization, or explicitly reset on evaluation error.

* Extract React Grab into own file, make version configurable

Move all react-grab logic (settings, script loader, message handler,
BrowserPanel extension) into Sources/Panels/ReactGrab.swift.

Add a "React Grab Version" text field in Settings > Browser that lets
the user pin which npm version is fetched. Only versions with a known
SHA-256 integrity hash in ReactGrabSettings.knownHashes are accepted.
The cache invalidates when the configured version changes.

---------

Co-authored-by: Lawrence Chen <lawrencecchen@users.noreply.github.com>
2026-03-30 18:00:45 -07:00

205 lines
6.7 KiB
Swift

import CryptoKit
import Foundation
import WebKit
#if DEBUG
import Bonsplit
#endif
// MARK: - Settings
enum ReactGrabSettings {
static let versionKey = "reactGrabVersion"
static let defaultVersion = "0.1.29"
/// Known versions and their SHA-256 integrity hashes.
/// Add new entries when bumping the default or to allow user-selected versions.
static let knownHashes: [String: String] = [
"0.1.29": "4a1e71090e8ad8bb6049de80ccccdc0f5bb147b9f8fb88886d871612ac7ca04b",
]
static func scriptURL(for version: String) -> URL {
URL(string: "https://unpkg.com/react-grab@\(version)/dist/index.global.js")!
}
static var configuredVersion: String {
let stored = UserDefaults.standard.string(forKey: versionKey)?.trimmingCharacters(in: .whitespacesAndNewlines) ?? ""
return stored.isEmpty ? defaultVersion : stored
}
}
// MARK: - Script Loader
/// Fetches, integrity-checks, and caches the react-grab script.
/// Shared across all BrowserPanel instances.
enum ReactGrabScriptLoader {
private static var cachedScript: String?
private static var cachedVersion: String?
private static var prefetchTask: Task<String?, Never>?
static func prefetch() {
let version = ReactGrabSettings.configuredVersion
// Invalidate cache if version changed.
if cachedVersion != version {
cachedScript = nil
cachedVersion = nil
}
guard cachedScript == nil else { return }
guard prefetchTask == nil else { return }
prefetchTask = Task.detached(priority: .low) {
let result = await doFetch(version: version)
await MainActor.run { prefetchTask = nil }
return result
}
}
static func fetch() async -> String? {
let version = ReactGrabSettings.configuredVersion
if cachedVersion == version, let cached = cachedScript { return cached }
prefetch()
return await prefetchTask?.value
}
private static func doFetch(version: String) async -> String? {
let url = ReactGrabSettings.scriptURL(for: version)
do {
let (data, _) = try await URLSession.shared.data(from: url)
if let expectedHash = ReactGrabSettings.knownHashes[version] {
let hash = SHA256.hash(data: data)
let hex = hash.compactMap { String(format: "%02x", $0) }.joined()
guard hex == expectedHash else {
NSLog("ReactGrab: integrity mismatch for v%@ (got %@)", version, hex)
return nil
}
}
guard let script = String(data: data, encoding: .utf8) else { return nil }
await MainActor.run {
cachedScript = script
cachedVersion = version
}
return script
} catch {
NSLog("ReactGrab: fetch failed for v%@: %@", version, error.localizedDescription)
return nil
}
}
}
// MARK: - WKScriptMessageHandler
private let reactGrabMessageHandlerName = "cmuxReactGrab"
class ReactGrabMessageHandler: NSObject, WKScriptMessageHandler {
private let onStateChange: @MainActor (Bool) -> Void
init(onStateChange: @escaping @MainActor (Bool) -> Void) {
self.onStateChange = onStateChange
}
func userContentController(
_ userContentController: WKUserContentController,
didReceive message: WKScriptMessage
) {
guard let body = message.body as? [String: Any],
let isActive = body["isActive"] as? Bool else { return }
#if DEBUG
dlog("reactGrab.messageHandler isActive=\(isActive)")
#endif
Task { @MainActor in
#if DEBUG
dlog("reactGrab.messageHandler.mainActor isActive=\(isActive)")
#endif
onStateChange(isActive)
}
}
}
// MARK: - BrowserPanel extension
extension BrowserPanel {
func setupReactGrabMessageHandler(for webView: WKWebView) {
let handler = ReactGrabMessageHandler { [weak self] isActive in
self?.isReactGrabActive = isActive
}
reactGrabMessageHandler = handler
webView.configuration.userContentController.add(handler, name: reactGrabMessageHandlerName)
}
func injectReactGrab() async {
#if DEBUG
dlog("reactGrab.inject.start")
#endif
guard let scriptSource = await ReactGrabScriptLoader.fetch() else {
#if DEBUG
dlog("reactGrab.inject.fetchFailed")
#endif
return
}
#if DEBUG
dlog("reactGrab.inject.fetched len=\(scriptSource.count)")
#endif
let handlerName = reactGrabMessageHandlerName
let combined = """
(function() {
if (window.__REACT_GRAB__) { window.__REACT_GRAB__.activate(); return; }
window.addEventListener('react-grab:init', function(e) {
var api = e.detail;
if (!api) return;
api.activate();
var lastActive;
api.registerPlugin({
name: 'cmux-bridge',
hooks: {
onStateChange: function(state) {
if (state.isActive === lastActive) return;
lastActive = state.isActive;
var h = window.webkit && window.webkit.messageHandlers && window.webkit.messageHandlers.\(handlerName);
if (h) h.postMessage({ isActive: state.isActive });
}
}
});
}, { once: true });
})();
\(scriptSource)
"""
#if DEBUG
dlog("reactGrab.inject.evalJS len=\(combined.count)")
#endif
webView.evaluateJavaScript(combined) { [weak self] _, error in
#if DEBUG
dlog("reactGrab.inject.evalJS.done error=\(error?.localizedDescription ?? "none")")
#endif
if let error {
NSLog("ReactGrab: injection failed: %@", error.localizedDescription)
Task { @MainActor in self?.isReactGrabActive = false }
}
}
#if DEBUG
dlog("reactGrab.inject.end")
#endif
}
func toggleReactGrab() {
#if DEBUG
dlog("reactGrab.toggle.start")
#endif
let script = "window.__REACT_GRAB__?.toggle()"
webView.evaluateJavaScript(script, completionHandler: nil)
#if DEBUG
dlog("reactGrab.toggle.end")
#endif
}
func toggleOrInjectReactGrab() async {
if isReactGrabActive {
toggleReactGrab()
} else {
await injectReactGrab()
}
}
func resetReactGrabState() {
isReactGrabActive = false
}
}