Extracted from prototypes/yetano-webview (AP1): packages assets, document, bridge and window (macOS Cocoa/WKWebView via cgo, Windows Win32/WebView2 pure Go). No local HTTP listener or port: assets go through the WebView's resource handler, app routes through the native message binding. Own go.mod and gui/vX.Y.Z tags keep cgo and the WebView dependencies out of the main core module. Adds backend-free tests for the window's dispatch/destroy guards and a yet-gui migration guide. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
8.4 KiB
yetano.dev/yetano/core/gui
The native WebView host shared by Yetano desktop programs: a native window
whose WebView shows embedded HTML/CSS/JS/WASM and sends the page's
fetch/XMLHttpRequest to Go handlers. No local web server, no port, no
localhost listener -- not in the program, not as a fallback. Every request
goes either through the WebView's native resource handler (custom scheme /
request interception) or through the native message binding.
Extracted from the AP1 prototype prototypes/yetano-webview (meta-repo
docs/yetano-ui/AP1-GO-WEBVIEW-PROTOTYP.md), which remains its native
selftest bench; its README holds the measured evidence per platform.
Separate module
module yetano.dev/yetano/core/gui tags: gui/v0.1.0, gui/v0.2.0, ...
This directory is its own Go module, nested in the core repository, so the
main yetano.dev/yetano/core module keeps its single dependency
(gopkg.in/yaml.v3) and stays free of cgo. Its dependencies:
golang.org/x/net/html (tokenizer), golang.org/x/sys/windows,
github.com/jchv/go-webview2/pkg/edge (Windows only, MIT; loads
Microsoft's embedded WebView2Loader via go-winloader, ISC). Go 1.26.
GOPRIVATE=teruna.dev,yetano.dev,yalsh.dev go get yetano.dev/yetano/core/gui@gui/v0.1.0
Tags carry the gui/ prefix (Go's rule for a module in a subdirectory);
the main module's vX.Y.Z tags do not version this one. Never move a tag.
API
| Package | What |
|---|---|
gui/assets |
NewResolver(sources...) over NewFSSource (embed.FS), NewDirSource (os.Root), NewZipFileSource/NewZipBytesSource; first source that has a file wins, a read error does not fall through. ValidatePath (checked, never cleaned), Join, DetectMIME. |
gui/document |
Prepare(ctx, res, entry, html, Options{Link}): rewrites assets: / relative references in HTML and CSS (img, srcset, script, link, style, CSS url()/@import). Link mode -> /assets/... URLs, validated against the resolver; inline mode -> typed data: URLs (entry <= 1.5 MiB). |
gui/bridge |
NewRouter(res), Router.Handle("POST /rpc/x", h), Router.SetDocument, Router.ServeNative (for the window's resource handler), Router.HTML (Go-rendered fragments through document). NewSession(router, Options) speaks protocol v1 with the page (hello/ready, req/res, chunk/end streams, abort, generations). InitScript(PageConfig) is the page side (bridge.js). |
gui/window |
New(Options{Title, Width, Height, Debug, DataPath, OnMessage, Resource}), Init, Navigate, Run, Dispatch, Eval, Terminate, Destroy, BaseURL, Snapshot (macOS), SetAppearance, SetAppIcon, AccentColor. |
Wiring
res, _ := assets.NewResolver(assets.NewFSSource("embed", webFS))
router := bridge.NewRouter(res)
router.SetDocument("index.html", true) // entry served via the resource handler
router.Handle("POST /rpc/add", addHandler)
sess := bridge.NewSession(router, bridge.Options{})
var origin string // requests only arrive after Navigate
w, err := window.New(window.Options{
Title: "app", DataPath: webview2Dir, // Windows: from core/paths, see below
OnMessage: func(msg string) { sess.Post(json.RawMessage(msg)) },
Resource: func(ctx context.Context, r *window.ResourceRequest, rw window.ResourceWriter) {
router.ServeNative(ctx, origin, r.Method, r.URL, r.Header, r.Body, rw)
},
})
if err != nil { sess.Close(); return err }
origin = w.BaseURL()
sess.Attach(w)
w.Init(bridge.InitScript(bridge.PageConfig{Transport: "native", Origin: origin, External: "reject"}))
w.Navigate(origin + "/")
w.Run() // main goroutine
sess.Close() // first: lock, cancel calls, bounded wait
w.Destroy() // then: native window, on the UI thread
The WebView2 user-data folder (DataPath) belongs under the program's
core/paths cache or data directory (%LOCALAPPDATA%, never roaming).
Invariants
- No listener, no ports, no localhost. After a transport change,
re-check the running process (
lsof -nP -a -p PID -i,netstat -ano). - Paths are checked, not cleaned (
assets.ValidatePath):..,., empty segments,\,:, NUL, absolute paths -> 400.assets.Joinlets trusted CSS use..inside the root; never for paths from the page. - Exactly one end per call/stream; every end that does not come from Go
is reported to Go (
abort). Calls of an old document generation fail withErrStale, their answers are dropped (Go and JS side). - Close order:
Session.Close()->Window.Destroy()on the UI thread.Closenever waits for the UI thread. - Threads:
window.New/Init/Navigate/Run/Destroyonly on the main goroutine (packagewindowlocks it ininit).Evalonly inside aDispatched function.DispatchafterDestroyis a no-op. - Routes are registered before the document starts (
Router.FreezeinNewSession); duplicates are errors; handler panics become a 500. - Transport
native: entry and/assets/via the resource handler, app routes via the bridge (WebView2 buffers intercepted responses until EOF, so streaming only works over the bridge on Windows).
Measured platform pitfalls
| Pitfall | Handled in |
|---|---|
WKWebView silently ignores location.reload() of a data: document |
transport inline: reload via a Go route that navigates again |
WebKit hands Blob/FormData bodies to WKURLSchemeHandler empty |
bridge.js needsSerialize |
WebKit tasks must not be touched after stopURLSchemeTask |
darwin.m onTask looks them up in tasks |
WebView2 reads intercepted response streams to EOF; E_PENDING fails the request |
app routes stream over the bridge |
| WebView2 has no cancel for intercepted requests | goStream.onDrop cancels the ctx when the stream is released |
A stale WM_QUIT makes the next pkg/edge.Embed crash |
settle() before create and after Destroy |
PostThreadMessage is lost during move/resize |
Dispatch via PostMessage to the window |
Platforms
| Platform | Backend | Origin | Status |
|---|---|---|---|
| macOS | window/darwin.m: NSWindow + WKWebView, cgo |
yetano://app |
natively verified (prototype selftest, yet-gui) |
| Windows | window/window_windows.go: Win32 + WebView2 via pkg/edge, pure Go |
https://yetano.invalid |
natively verified (Windows 11 amd64) |
| Linux/FreeBSD | -- | -- | builds; window.New returns ErrUnsupported (see TODO) |
Tests
go vet ./... && GOOS=windows go vet ./... && go test -race ./...
Unit tests cover everything backend-free: resolver/path rules/MIME
(assets), HTML/CSS rewriting (document), router and the bridge protocol
against a fake UI (bridge), dispatch/destroy guards (window). Real
browser behavior is tested by the prototype's in-window selftest
(make selftest, make selftest-windows in prototypes/yetano-webview)
and yet-gui's (make gui-selftest).
TODO
- Linux/FreeBSD backend: WebKitGTK,
webkit_web_context_register_uri_scheme(aGInputStream, so real streaming) +WebKitUserContentManagerfor the message binding; own cgo host likedarwin.m. - Windows: own environment creation instead of
pkg/edge.Embed(customyetano://appscheme, fixed-version runtime, nolog.Fatalon COM errors, explicitController.Close);SnapshotviaCapturePreview. - Bridge: back-pressure for streams, streaming uploads, XHR progress.
- AP2 (Lua/HTML templating) hooks in before
document.Prepare.
The full list with background lives in the prototype's TODO.md.
Migrating yet-gui (yet/gui/internal -> core/gui)
yet/gui/internal/{assets,document,bridge,window} is a byte-identical copy
(apart from the import path) of what is now in this module.
cd yet/gui && GOPRIVATE=teruna.dev,yetano.dev,yalsh.dev go get yetano.dev/yetano/core/gui@gui/v0.1.0- Replace the imports
yetano.dev/yetano/yet/gui/internal/<pkg>withyetano.dev/yetano/core/gui/<pkg>(gofmt -rorsed); the API is unchanged, no call site changes. git rm -r gui/internal/{assets,document,bridge,window} gui/internal/README.md,go mod tidy.make gui-check,make gui-selftest(macOS) andmake gui-selftest-windows-- the in-window selftests are the proof, a cross-build is not.- Drop the "keep both copies in sync" notes (yet
docs/gui.md, the prototype'sAGENTS.mdalready points here).
A host fix from then on is a core/gui change plus a new gui/vX.Y.Z tag,
picked up by go get in every consumer.