Skip to content

Visual Studio Code, rebuilt in Rust

Rust
14.1 KB
Raw Blame

Webviews

A webview is a native web view of the OS that shows an extension's HTML inside the app window. This file covers the native view per OS, how it sits over GPUI's content, the message path between the page, the workbench and the extension host, resource loading with its security boundary, and lifetime. It goes one level under ARCHITECTURE.md, "Terminal, webviews, updates". The code is app/src/webview.rs, the three platform files of app/src/webview/, and the workbench files that own webviews. Upstream is src/vs/workbench/contrib/webview and src/vs/workbench/api/browser/mainThreadWebviews.ts.

What is where

  • app/src/webview.rs: everything the platforms share. app/src/webview.rs::Webview is one webview, app/src/webview.rs::Resources answers its requests and receives its messages, app/src/webview.rs::theme_data builds the styles message, app/src/webview.rs::BRIDGE_SCRIPT and app/src/webview.rs::FIND_SCRIPT are the two scripts the port injects into the host page.
  • app/src/webview/macos.rs, app/src/webview/linux.rs, app/src/webview/windows.rs: one Native each, with the same methods (new, view, hide, evaluate, take_keyboard, release_keyboard, has_keyboard, open_inspector), plus place, supported and ClipView. There is no trait: app/src/webview.rs imports the one Native of the target OS.
  • app/src/webview/color_ids.txt: the ids of upstream's color registry, one per line, that theme_data sends as --vscode-* variables.
  • app/src/workbench/webview_panels.rs: MainThreadWebviews and MainThreadWebviewPanels. It owns app/src/workbench/webview_panels.rs::WebviewPanel, the per-frame bookkeeping (update_webview_panels) and the event handler (handle_webview_event) of every webview but the welcome page's.
  • app/src/workbench/webview_views.rs, app/src/workbench/custom_editors.rs, app/src/workbench/media_preview.rs, app/src/workbench/release_notes.rs: webview views, custom editors and the built-in pages. Each is a WebviewPanel with another scheme or an extra field, so they share the panel code.
  • Four more owners make a Webview of their own: app/src/workbench/notebook_editor.rs (the back layer), app/src/workbench/editor_insets.rs, app/src/workbench/extension_editor.rs and app/src/workbench/welcome_page.rs. Webview::new has five call sites in all.

The native view per OS

OS View Stands in for the service worker Message handler
macOS WKWebView, a subview of GPUI's NSView a WKURLSchemeHandler on https (app/src/webview/macos.rs::SchemeHandler) WKScriptMessageHandler
Linux WebKitGTK view in a GTK window reparented into GPUI's X11 window a TLS proxy on loopback, set as the view's https proxy (app/src/webview/linux.rs::serve) script message handler
Windows WebView2 in a child window of GPUI's HWND a WebResourceRequested handler (app/src/webview/windows.rs::answer) chrome.webview.postMessage

Every platform loads upstream's host page, src/vs/workbench/contrib/webview/browser/pre/index.html, unchanged, with the query webviewElement.ts gives its iframe (app/src/webview.rs::host_page_url). The page runs with disableServiceWorker=true: the native request handler answers what service-worker.js answers upstream. The reason for each seam is in the //! header of its file and in port/notes.md, "Milestone 17: webviews and notebooks".

  • macOS: WebKit refuses a scheme handler for https, so app/src/webview/macos.rs::allow_https_scheme_handler swizzles +[WKWebView handlesURLScheme:] to answer NO for https. It is process-wide and runs once.
  • Linux: WebKitGTK has no way around that refusal, hence the proxy. Its certificate is trusted by the view's own context and only for the two served sites; every other host is tunnelled untouched. GTK has no main loop of its own here: app/src/webview/linux.rs::pump_gtk, started in app/src/main.rs, iterates it from GPUI's loop.
  • Windows: WebView2 makes its controller asynchronously. Until it arrives, app/src/webview/windows.rs::Host holds the frame and visibility the controller takes on.

Invariant: check app/src/webview.rs::supported before Webview::new. It is false off the main thread (every unit test), on Wayland, and on Windows without the WebView2 runtime. All five call sites guard on it; on macOS a Native::new off the main thread panics.

Placing a webview over GPUI

GPUI does not draw a webview and has no child-view API. The owner renders an empty box with a canvas whose prepaint calls place with the box's bounds in window coordinates (app/src/workbench/webview_panels.rs::webview_body). place sets the native frame only when it changed, and shows the view. A webview is created hidden: it shows only when a frame places it.

Invariant: the native view is above GPUI's layer, so GPUI cannot draw over it. While a quick input, the keybindings editor, a context menu or the modal editor part would overlap, the panel is covered: the body stops placing it and update_webview_panels hides it. Electron draws those over its iframe; this difference is a recorded shortcut. A new GPUI overlay that can lie over a webview joins the covered condition.

A webview that must sit inside scrolling GPUI content uses a ClipView (app/src/webview/macos.rs::ClipView and its two siblings): the notebook back layer and editor insets. The clip view shows the webview inside its own bounds only, passes presses to the webview only inside the given hit rectangles, and can cut a hole where a GPUI widget must stay visible and pressable (the notebook find widget). ClipView::new has two call sites.

Keyboard focus is explicit. The host page's did-focus makes the view take the keyboard and blurs GPUI (window.blur); when GPUI focuses one of its own elements again, update_webview_panels calls release_keyboard. The host page forwards each keydown of its frame as did-keydown; all but a lone modifier go through GPUI's keybindings (app/src/workbench/webview_panels.rs::keystroke), deferred, because the keystroke interceptors update the workbench the handler is already updating.

The message path

  1. Page to app. BRIDGE_SCRIPT runs at document start in the top frame, before the host page's own script. It replaces window.postMessage, keeps the MessagePort the host page hands over with webview-ready, and relays each port message to the native handler as { channel, data } JSON.
  2. Resources::receive turns that text into a app/src/webview.rs::WebviewEvent and sends it on an unbounded channel. One task per window reads the channel (app/src/workbench/webview_panels.rs::webview_events) and calls handle_webview_event on the main thread. The welcome page's media webview has a channel and a handler of its own (app/src/workbench/welcome_page.rs::welcome_webview_events, handle_welcome_webview_event).
  3. handle_webview_event routes by the webview's id prefix (extension-editor-, editor-inset-, notebook-), else by panel handle, then by channel. The channels are upstream's FromWebviewMessage of webviewMessages.d.ts, plus the port's webview-ready, find-focus and find-hidden.
  4. App to extension host. onmessage goes out as ExtHostWebviews.$onMessage through app/src/host_sync.rs::send.
  5. Extension host to app. MainThreadWebviews and MainThreadWebviewPanels calls are Path::Forwarded in app/src/main_thread_commands.rs::route and land in handle_webview_request (extension-host.md, "Host calls the port answers").
  6. App to page. Webview::send evaluates globalThis.__vscodeWebviewHost.post(channel, args), which posts on the kept port.

Contract: an extension message crosses as extHostWebviewMessaging.ts serializes it: JSON text with $$vscode_array_buffer_reference$$ objects, the ArrayBuffers beside it as base64. The bridge serializes and deserializes in the page. For a panel Rust passes both parts through and does not parse the message; the built-in pages and editor insets parse its text.

Invariant: Webview::send queues until webview-ready (Webview::did_become_ready), as webviewElement.ts does in its Initializing state. A script evaluated directly before that reaches a page with no port. Messages posted before the first webview of a panel exists wait in the panel (first_load_messages).

The built-in pages (media preview, release notes, image carousel) take onmessage in the workbench and never reach the extension host. A new built-in page adds its arm before the general onmessage arm.

Resources and the security boundary

app/src/webview.rs::Resources::serve is the one function all three request handlers call, and the whole boundary:

  • Host site, https://<hash>.vscode-webview.vscode-cdn.net: files inside pre/ only, 404 for a path with a .. or a drive component. The hash is app/src/webview.rs::parent_origin_hash of a fixed parent origin and the webview's origin, the check index.html makes itself. One origin per extension and view type (webview_origin) keeps the page's storage across loads.
  • Resource site, https://<scheme>+<authority>.vscode-resource.vscode-cdn.net/<path> (webview.ts asWebviewUri): app/src/webview.rs::resource_uri restores the resource, app/src/webview.rs::is_contained checks it against the local resource roots. 401 outside the roots, 404 when the read fails, byte ranges for media.
  • Any other host: serve returns false and the request goes to the network.

Invariant: containment follows upstream's resourceLoading.ts. A file resource is checked lexically (no .. segment, under a root of the same scheme and authority, case-insensitive on Windows), then by its resolved path, so a symlink out of a root answers 401. A resource of an extension file system provider has the lexical check only, and its read goes to the workbench as app/src/webview.rs::ResourceRead, answered through app/src/host_sync.rs::read_file. vscode-remote always answers 401. A new way to read a file for a webview goes through serve.

Invariant: the request handler compares the host itself with app/src/webview.rs::is_subdomain. A URL filter is not a host check: WebView2's * matches /, so https://example.com/.vscode-resource.vscode-cdn.net/a passes the filter (app/src/webview.rs::https_url_parts and its test).

The roots come from the extension host, which already added the defaults (app/src/workbench/webview_panels.rs::local_resource_roots); $setOptions replaces them on the live webview. Scripts and forms are the allowScripts and allowForms options of the content message (update_content), which the unchanged host page turns into its iframe sandbox. The same message carries cspSource; the page reports HTML without a policy as no-csp-found, forwarded as $onMissingCsp.

Three more rules sit outside serve:

  • Plain http loads only from loopback on WebKit (app/src/webview.rs::HTTP_LOOPBACK_ONLY_RULES), which is what Chromium allows in an https page.
  • The Linux proxy answers only connections of its own user (app/src/webview/linux.rs::is_own_connection): any local user can reach a loopback port.
  • Cut, Copy and Paste on WebKit run the view's own editing actions (Webview::clipboard_command). The host page's execCommand would need a clipboard setting that every page in the webview would get.

Lifetime

A panel outlives its webview. WebviewPanel holds the HTML, options and state; WebviewPanel.webview is an Option.

  • Created when the panel first shows, in update_webview_panels, which runs each render.
  • Hidden panel: released (webview = None) unless retainContextWhenHidden, when it is only hidden. The release happens as the editor hides (release_hidden_webview_panels), not at the next frame, so a reveal right after loads the page again. An editor inset keeps its webview while hidden.
  • State: do-update-state stores what vscode.setState gave in the panel, and the next content message hands it back to the reloaded page.
  • Dropping the Native removes the native view, gives the keyboard back and, on Linux and Windows, closes the proxy or the controller. Drop a Webview on the main thread.
  • A theme change sends styles again to the live webviews of panels and editor insets only (restyle_webviews). The welcome page makes its webview again; the notebook back layer and the extension editor get styles only when made.

Traps

  • A unit test never has a native view: supported is false, so tests cover the panel state, the protocol functions and serve, not the page. What the page does is checked by port/tools/webview-check against the reference app.
  • BRIDGE_SCRIPT talks to window.webkit.messageHandlers. Windows wraps it with a shim of that shape for the top frame only (app/src/webview/windows.rs::bridge_script); keep the script free of engine-specific calls.
  • A late did-focus arrives up to 250 ms after the fact, because the host page polls its focus. handle_webview_event sets focused but does not take the keyboard or blur GPUI while the same webview's context menu is open; another focus-stealing overlay needs the same care.
  • The find widget is HTML inside the host page (FIND_SCRIPT), not a GPUI widget, because GPUI cannot draw over the view.
  • A change to unsafe code in the three platform files follows memory-safety.md, which has a row for each.

Check a change

  • port/tools/cargo-test -p app webview::tests: the protocol and the boundary (serves_only_files_inside_pre_dir_and_the_roots, maps_resource_urls_to_resources_inside_the_roots, splits_https_urls_as_nsurl_does).
  • port/tools/cargo-test -p app webview_panels: panels, restore, the context menu, resource reads through the file service.
  • port/tools/cargo-test -p app webview_views and port/tools/cargo-test -p app custom_documents: the other panel kinds.
  • port/tools/studio --lane 'port/tools/webview-check': the fixture extension port/fixtures/extensions/webview-tests in the port and in the reference, one line per check. It covers messages with ArrayBuffers both ways and resource loads in a real view.
  • cargo gc clippy -p app -p exthost --all-targets -- -A clippy::all after a change to unsafe code.