Visual Studio Code, rebuilt in Rust
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::Webviewis one webview,app/src/webview.rs::Resourcesanswers its requests and receives its messages,app/src/webview.rs::theme_databuilds thestylesmessage,app/src/webview.rs::BRIDGE_SCRIPTandapp/src/webview.rs::FIND_SCRIPTare 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: oneNativeeach, with the same methods (new,view,hide,evaluate,take_keyboard,release_keyboard,has_keyboard,open_inspector), plusplace,supportedandClipView. There is no trait:app/src/webview.rsimports the oneNativeof the target OS.app/src/webview/color_ids.txt: the ids of upstream's color registry, one per line, thattheme_datasends as--vscode-*variables.app/src/workbench/webview_panels.rs:MainThreadWebviewsandMainThreadWebviewPanels. It ownsapp/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 aWebviewPanelwith another scheme or an extra field, so they share the panel code.- Four more owners make a
Webviewof their own:app/src/workbench/notebook_editor.rs(the back layer),app/src/workbench/editor_insets.rs,app/src/workbench/extension_editor.rsandapp/src/workbench/welcome_page.rs.Webview::newhas 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, soapp/src/webview/macos.rs::allow_https_scheme_handlerswizzles+[WKWebView handlesURLScheme:]to answer NO forhttps. 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 inapp/src/main.rs, iterates it from GPUI's loop. - Windows: WebView2 makes its controller asynchronously. Until it arrives,
app/src/webview/windows.rs::Hostholds 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
- Page to app.
BRIDGE_SCRIPTruns at document start in the top frame, before the host page's own script. It replaceswindow.postMessage, keeps theMessagePortthe host page hands over withwebview-ready, and relays each port message to the native handler as{ channel, data }JSON. Resources::receiveturns that text into aapp/src/webview.rs::WebviewEventand sends it on an unbounded channel. One task per window reads the channel (app/src/workbench/webview_panels.rs::webview_events) and callshandle_webview_eventon 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).handle_webview_eventroutes by the webview's id prefix (extension-editor-,editor-inset-,notebook-), else by panel handle, then by channel. The channels are upstream'sFromWebviewMessageofwebviewMessages.d.ts, plus the port'swebview-ready,find-focusandfind-hidden.- App to extension host.
onmessagegoes out asExtHostWebviews.$onMessagethroughapp/src/host_sync.rs::send. - Extension host to app.
MainThreadWebviewsandMainThreadWebviewPanelscalls arePath::Forwardedinapp/src/main_thread_commands.rs::routeand land inhandle_webview_request(extension-host.md, "Host calls the port answers"). - App to page.
Webview::sendevaluatesglobalThis.__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 insidepre/only, 404 for a path with a..or a drive component. The hash isapp/src/webview.rs::parent_origin_hashof a fixed parent origin and the webview's origin, the checkindex.htmlmakes 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.tsasWebviewUri):app/src/webview.rs::resource_urirestores the resource,app/src/webview.rs::is_containedchecks it against the local resource roots. 401 outside the roots, 404 when the read fails, byte ranges for media. - Any other host:
servereturnsfalseand 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
httploads 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'sexecCommandwould 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) unlessretainContextWhenHidden, 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-statestores whatvscode.setStategave in the panel, and the nextcontentmessage hands it back to the reloaded page. - Dropping the
Nativeremoves the native view, gives the keyboard back and, on Linux and Windows, closes the proxy or the controller. Drop aWebviewon the main thread. - A theme change sends
stylesagain 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 getstylesonly when made.
Traps
- A unit test never has a native view:
supportedis false, so tests cover the panel state, the protocol functions andserve, not the page. What the page does is checked byport/tools/webview-checkagainst the reference app. BRIDGE_SCRIPTtalks towindow.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-focusarrives up to 250 ms after the fact, because the host page polls its focus.handle_webview_eventsetsfocusedbut 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
unsafecode 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_viewsandport/tools/cargo-test -p app custom_documents: the other panel kinds.port/tools/studio --lane 'port/tools/webview-check': the fixture extensionport/fixtures/extensions/webview-testsin 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::allafter a change tounsafecode.