Core concepts
This page covers the ideas every TanGo app uses: App and Surface, the threading model, IPC, asset serving, lifecycle and app events, and the security model. The Chinese documentation splits them into separate pages with more detail.
App and Surface
The root package github.com/tangoui/tango has two core types. An App is the application: it owns the native event loop and a queue of work for the main thread. A Surface is one window on desktop, or one page on mobile, hosting a system WebView (WKWebView on macOS and iOS, WebView2 on Windows, WebKitGTK 4.1 on Linux, the system WebView on Android).
app := tango.New(tango.Options{
Name: "Notes",
ID: "com.example.notes",
Assets: asset.FS(site, asset.Options{}),
URLSchemes: []string{"notes"},
})
app.OnReady(func() {
s, _ := app.NewSurface(tango.SurfaceOptions{Title: "Notes", Width: 960, Height: 640, Resizable: true})
s.OnClose(func() bool { return !dirty }) // the user closes the window; false keeps it open
})
if err := app.Run(); err != nil { // blocks until the app quits
log.Fatal(err)
}At the bottom, pages and Go exchange raw string messages: window.__tango.post(str) / onMessage(fn) in the page, App.OnMessage / Surface.Send in Go. Everything else builds on that.
System capabilities outside the window live in one package each under sys/ (sys/clipboard, sys/dialog, sys/tray, …). Their first parameter is the *tango.App; they return the package's ErrUnsupported where the platform cannot help, and tango.ErrNotRunning after the app quit.
Go-drawn UI (package ui) opens in its own window with uihost.Open, or on top of / below a WebView in the same window or mobile page with uihost.Attach.
Threading
- Call
App.Runfrom themaingoroutine. On desktop the root package locks it to the process' main thread ininit. - Callbacks (
OnReady,OnMessage,Surface.OnClose, menu and tray clicks, …) run on the main thread. Keep them short. - Everything else is safe from any goroutine; the core hops to the main thread when it needs to.
app.Post(func() { s.SetTitle("done") }) // queue, return at once
n := tango.Await(app, func() int { return len(app.Surfaces()) }) // run there, wait for the result
path := tango.AwaitAsync(app, func(done func(string)) { // start async work there, wait for done
pick(func(p string) { done(p) })
})Called on the main thread itself, Await runs directly and AwaitAsync keeps pumping native events until done is called, so a dialog opened from a menu callback does not deadlock. After Run returns, Post drops work and Await/AwaitAsync return zero values.
Go-drawn windows opened with uihost.Open, attached with uihost.Attach, or hosted by tan dev run the page function and ui.Runner callbacks on the app's main thread. A headless ui.Driver runs on the caller's thread. Dedicated macOS UI threads are currently used only for internal testing.
- To change state the page reads or call
Runnermethods from a background goroutine, user.Post(fn). It runs work in order on the UI thread and requests a frame afterward. Pending work is dropped when the window closes. - Main-thread callbacks such as menus, tray,
uihost.Shortcut,OnMessage, andSurface.OnClosecan also update page state throughr.Post. Runnermethods are UI-thread only, exceptPost,InvalidateandClose, which are safe from any goroutine.- Calls that need the main thread (
uihost.Open,uihost.Attach,uihost.FollowSystemTheme) go throughapp.Postortango.Await, e.g.app.Post(func() { uihost.FollowSystemTheme(r, false); r.Post(func() { r.SetTheme(th) }) }).
Development builds (-tags tango_dev) check the calling thread only for runners bound to a dedicated UI thread during internal testing.
On mobile the native host owns the main thread and Go's main runs on an ordinary goroutine; the rules for your code stay the same. Android cannot nest its main loop, so call functions that wait for the user (dialogs, share, permission requests) from a goroutine there.
IPC: calls, events, streams
Package ipc adds three patterns on top of raw messages: calls, events, and full-duplex streams that carry JSON values and bytes. The page side is @tangoui/runtime (injected as window.tango by runtimejs.Script, or installed from npm).
r := ipc.NewRouter()
app.AddBridgeScript(runtimejs.Script)
app.OnMessage(func(s *tango.Surface, m string) { r.HandleMessage(s, m) })
app.OnBinary(func(s *tango.Surface, gen uint64, p []byte) { r.HandleBinarySession(s, gen, p) }) // fast lanes, see below
bind.Register(r, "Notes", &Notes{}) // exported methods become Notes.Get, Notes.Search, …
r.On("draft-changed", func(c ipc.Conn, data json.RawMessage) { /* page → Go event */ })
r.Emit(s, "sync-progress", map[string]any{"pct": 42}) // Go → page event
r.HandleStream("Logs.Tail", func(ctx context.Context, args json.RawMessage, w ipc.StreamWriter) error {
for line := range follow(ctx) {
if err := w.Write(line); err != nil {
return err // the page cancelled or went away
}
}
return nil
})const note = await tango.call("Notes.Get", 42);
tango.emit("draft-changed", { id: 1 });
tango.on("sync-progress", ({ pct }) => (bar.value = pct));
for await (const line of tango.stream("Logs.Tail")) { if (enough) break; } // break cancels in GoBinding: methods may take a leading
context.Context, then JSON-decodable parameters, and return nothing,T,erroror(T, error).Errors reject with a
TangoErrorcarrying acode:not_found,bad_args,internal,canceledandtransport(frames lost on a broken fast lane, see below), plusforbidden,unsupportedandnot_runningfrom jsapi. Returnipc.NewError(code, msg)to choose one.Back-pressure is counted in bytes: each direction of a stream has a credit window (1 MiB by default,
ipc.DefaultWindowBytes; Go's side is set withRouter.SetStreamWindow), and each frame costs its payload size plus 64 bytes. Credit returns only as the reader consumes frames, so a slow page slows the producer instead of piling up memory. A single frame carries at most 16 MiB (ipc.MaxFrameBytes); a larger write fails withbad_argsand leaves the stream usable.Bidirectional streams:
HandleStreamhandlers only send.r.HandleDuplex(name, func(s *ipc.Stream, args json.RawMessage) error)gets the stream itself: read withs.Receive/ReceiveBytes/ReceiveJSON, write JSON withs.Writeand bytes withs.WriteBytes, concurrently if needed.s.CloseSend()half-closes (end),s.Close()closes gracefully (this side stops receiving too; the peer's writes then fail with "stream closed by peer"),s.CloseWithError(err)fails it (the peer gets the frames sent before it, thenerr; this side's ownReceive*/Write*then return canceled "stream closed"); returning nil from the handler closes, returning an error fails.s.ReadWriter()views the byte frames as anio.ReadWriteCloserforio.Copy. On the page,tango.stream(name)returns aTangoStreamwithsend,sendBytes,end,accepted,bufferedAmount, and Web Streams viewsreadable/writable(file.stream().pipeTo(s.writable)uploads a file at Go's pace);tango.socket(name)wraps it in a WebSocket-like object whoseclose()sendscloseafter the queued sends and fires thecloseevent (1000) without waiting for Go. Streams Go opens withr.OpenStreamare bidirectional too, and must be closed by Go.examples/duplexshows an echo, an upload and a small terminal.In process: Go code in the same process (a Go-drawn UI) uses the same services with
r.Call(ctx, method, args...)andr.Open(ctx, method, args...), with identical semantics but no JSON messages or base64;ipc.ConnFromreportsok=falsethere. Close a stream fromOpen(or cancel itsctx) when done: it belongs to no page, soDropdoes not end it. These calls block; never make them on the UI thread (see Background data and threads).Fast lanes: binary side channels next to the message channel that carry stream byte frames without JSON or base64 (JSON frames, control messages and the handshake stay on the message channel). Each direction is negotiated separately and frames of one stream may be split between a lane and the message channel; the receiver reorders them, so semantics do not change. Lane names:
down:poll/up:post(polling GETs and POSTs under/__tango/lane/on the asset origin;down:polltakes every byte frame,up:post16 KiB up to about 1 MiB) and the platform lanesdown:android/up:android,down:shm/up:shm. A page gets lanes at its handshake only when all four hold:- the app registered at least one
app.OnBinaryhandler (the line above; it runs on the goroutine that received the packet, not the main thread, and the packet is only valid during the call); - the page comes from the asset origin (
tango://app, orhttps://tango.localhoston Windows and Android). A page loaded straight from a dev server (SurfaceOptions.URLset tohttp://localhost:5173and the like) never gets lanes;tan devproxies the dev server throughasset.FromEnv, so its pages are still on the asset origin; - the platform backend reports lanes;
- they are not turned off with
tango.Options{DisableFastLanes: true}orTANGO_IPC_LANES=0(any build; for troubleshooting).
Platform On by default Opt-in lanes macOS up:postdown:polliOS Off up:post(device testing pending)Android down:android,up:android— Windows down:shm,up:shm— Linux Off down:poll,up:postWindows uses one WebView2 SharedBuffer ring in each direction when SharedBuffer is available. Set
TANGO_IPC_LANES_WINDOWS=0,false, oroffto disable both lanes.TANGO_IPC_SHM_BYTESsets each ring's data capacity, which defaults to 4 MiB.Linux can opt in to downstream polling (
down:poll, WebKitGTK 2.36 or later) and upstream POSTs (up:post, 2.40 or later). SetTANGO_IPC_LANES_LINUX=1orallfor both, ordownorupfor one direction. Both directions fell short of the 64 KiB throughput threshold in CI. Seedocs/ipc-bench.md.down:pollis more than a byte-frame lane: it is the core's downstream transport, so once it is on, everySurface.Sendmessage (ipc JSON frames and control messages, call replies, jsapi events, messages read with__tango.onMessage) travels on it in one numbered sequence with the byte frames. The page keeps oneGET /__tango/lane/pollpending and Go ends it with a batch; when polling fails, the page stops polling (for example throttled in the background), or the lane is idle with one small message, messages go byEvalinstead, still numbered, and the page delivers them inSendorder.Surface.Evaljoins the same sequence as a barrier, so it stays in order withSend. It does not needOnBinary.macOS offers
up:postanddown:poll, iOSup:postonly. The earlier streamed downstream lanedown:schemeis gone (WKWebView held back part of a large burst on a streamedtango://response); everydown:pollresponse ends, which avoids that. On macOSup:postis on by default (64 MiB uploads run about 2.73x faster than on the message channel, seedocs/ipc-bench.md);down:pollis off by default: it makes downstream 3x to 11x faster than before (64 KiB frames 306 to 1017 MB/s, 1 KiB frames 45k to 500k/s, 2.3 KB JSON frames 34k to 111k/s) at under 10% more small-message latency, but its 64 KiB and small-frame throughput is still below Wails v3.1.0 (bound by the stream credit window). On iOSup:postis on by default after device testing (3.08x upstream throughput on iPhone 12 Pro). Both readTANGO_IPC_LANES_DARWINonce when a window or page is created (trimmed, any case, every build): on macOS unset, empty or an unlisted value meansup:post,1orallboth lanes,upordownonly that one, and0,falseoroffnone; on iOS0,falseoroffmeans none; unset, empty and any other value meansup:post.TANGO_IPC_LANES=0orDisableFastLanesalways wins. An app on a real iOS device cannot get an environment variable from outside: to opt in, callos.Setenv("TANGO_IPC_LANES_DARWIN", "up")in Go before the first window or page is created (not1: in code shared with macOS,1also turns on the experimentaldown:pollthere). CSP:up:poststarts by POSTing an empty packet and is ready only on its 204, so a page whose Content-Security-Policy does not allowconnect-srcto the asset origin (for exampleconnect-src https://api.example.com, or adefault-srcwithout'self') simply keeps its byte frames on the message channel, with no error; add'self'toconnect-srcto get the lane. Known limitations: iframes cannot obtain the lane token (the scheme handler cannot tell which frame asked, so the token is only handed to the main frame's bridge; measured on macOS, not separately on iOS: lane requests from opaque-origin frames such as sandboxedsrcdocordata:and from a same-origin frame were all refused; a same-origin frame can of course reachparent.tango, which is app code); WebKit does not deliverBlobrequest bodies, soup:postsends anArrayBuffer(iOS rewrites an app's own Blob bodies; on macOS, Blob bodies were not separately measured, so send anArrayBufferor a string); WebKit sends noOriginontango://requests, so TanGo substitutes the main document's origin, and a cross-origin iframe inside an app page passes the asset CSRF check (pre-existing; lanes are still protected by their per-generation token), so do not embed untrusted frames in asset pages; iOS passed the full self-test and upstream fault test on iPhone 12 Pro, and a lane breaking midway is tested on the iOS simulator bybash scripts/smoke.sh ios-lanefault(up:postfails after 3 data packets: the stream that lost a frame fails withtransport, a parallel stream arrives whole, later frames take the message channel;android-lanefaultdoes the same on Android).Android offers
down:androidandup:android: byte frames in both directions travel asArrayBuffers over the page's existingWebMessageListenerchannel, with no minimum frame size. They need WebView 116 or later (older WebViews keep the message channel) and are on by default (on the emulator, 64 KiB frames run about 6.1x faster upstream and 4.4x downstream; the median 64 B round trip is slightly slower, seedocs/ipc-bench.md; no device data yet):TANGO_IPC_LANES_ANDROIDis read once when a page is created (trimmed, any case);0,falseoroffturns them off, unset or any other value leaves them on, andTANGO_IPC_LANES=0orDisableFastLanesalways wins. An Android app cannot get an environment variable from outside: to turn them off, callos.Setenv("TANGO_IPC_LANES_ANDROID", "0")in Go before the first page is created. Every packet carries the page token and the lane generation, so packets of an old page or generation never reach a new one in either direction; a packet Go refuses makes the page dropup:androidat once and later frames take the message channel. Messages from subframes are dropped (measured on the emulator: a same-origin iframe forging packets through its own__tangoAndroidgot none to Go, and an opaque-origin iframe has no such object); a same-origin frame can reachparent.__tangoNative, which is app code. Each packet is copied once across processes and once through JNI. Seedocs/mobile.md.tango.lanes()on the page returns the lanes in use, e.g.{down: "fallback", up: "up:post"}on macOS by default ({down: "down:poll", up: "up:post"}withTANGO_IPC_LANES_DARWIN=1), or"fallback"for a direction without one. A lane that breaks is dropped at once and later frames take the message channel; a frame lost on it is not resent: when a stream misses a frame for 5 s (ipc.GapTimeout,GAP_TIMEOUT_MSin JS) once a reliable lane sequence boundary, later frame, or its end exposes the missing frame (including an open duplex lost tail), the stream fails on both sides with codetransport(ipc.CodeTransport); treat it like a dropped connection and reopen the stream. In development builds (-tags tango_dev) and self-test builds (-tags tango_selftest, whichtan buildkeeps; the iOS simulator self-test uses it)TANGO_IPC_LANE_FAULT=<lane>:<N>(e.g.down:poll:3) makes that lane fail after N data packets sent (downstream) or received (upstream) per page generation (empty packets, such asup:post's start probe, are not counted), to test a lane breaking midway; release builds ignore it.Fast-lane delivery is bound to the document session (lane generation): the lane token is per generation and used by every lane request in it, and a reload or leaving the asset origin retires it. Hand
OnBinary'sgentor.HandleBinarySession(s, gen, p)so packets of a previous document never reach the new one;r.HandleBinaryis only for simple connections that never host a second document, and drops every packet for a*tango.Surface(logging one warning). Feed a surface to oneRouteronly: each handshake starts a new lane generation, so two Routers on one surface would invalidate each other. Reliable streamboundarymessages (sent on the message channel once a lane frame is on its way) expose even a lost final frame of an open duplex; only streams with unresolved receive sequences fail after 5 seconds. For a stalled page (alert(), a long task) the guarantee is: the runtime sends a lane frame's boundary only once the frame actually went out (up:post: when its batch is handed tofetch), and every later message-channel post of that stream (data, end, close) waits for it too, so Go never starts timing a frame still queued in the page; the page's gap timer and theup:postrequest timer, when they fire more than 1 s late, wait one more full timeout, and a second expiry fails as usual. Abort paths (writable abort, a refused chunk,cancel(), a local error) still post their close/error at once, so under a stall longer than 5 s Go may reporttransportinstead of the abort reason. Eachup:postrequest aborts after 4 seconds (below the 5 s gap timeout, so a hung POST fails the lane and later frames fall back before streams fail); retained encoded POST bytes, in flight included, are capped at 8 MiB, and excess frames take the message channel without changing sequence or credit. Lane requests resolve against the document's actual location, independent of HTML<base>, and refuse redirects.- the app registered at least one
Wire protocol: version 2. The runtime and Go shake hands on load and Go rejects any other version ("runtime-js protocol mismatch"), so use the
@tangoui/runtimerelease that matches the Go module. The message format is documented in theipcpackage comment.TypeScript generation:
tan generate bindingsfinds supportedbind.Registercalls in the selected Go package and writes typed clients, mapping Go types the wayencoding/jsonencodes them.
Asset serving
Options.Assets is a plain http.Handler served under the backend's asset origin (tango://app on macOS, iOS and Linux, https://tango.localhost on Windows and Android) — no local port is opened.
Assets: asset.FromEnv(site, asset.Options{SPA: true, Headers: csp})asset.FS serves an fs.FS (usually embed.FS); asset.FromEnv switches to a reverse proxy to the dev server when TANGO_DEV_URL is set, which tan dev does, but only in development builds (-tags tango_dev, added by tan dev); a plain go build / go run . always serves the embedded files. Non-GET/HEAD requests to the asset origin whose Origin is another site get 403 before they reach your handler (tango.Options.AllowCrossOriginAssets turns this off). Compose it with your own handlers freely; service/fileserver mounts a user directory safely (no .., opened through os.Root). Handlers may be called off the main thread. On macOS and iOS the tango:// scheme handler is asynchronous: each request runs your handler on its own goroutine, never on the main thread (so requests can be served concurrently). Large or long-lived responses (big files, server-sent events) therefore do not block the UI, and when WebKit cancels a request, r.Context() is cancelled. A handler that touches main-thread-only state should hand the work to the main thread with app.Post or use a lock; tango.Await works too, but blocks the response until the main thread has run it.
Lifecycle and app events
app.OnLifecycle(func(ev tango.Lifecycle) {
switch ev {
case tango.Started, tango.Foreground, tango.Background, tango.Terminating:
}
})
app.OnQuitRequest(func() bool { return !unsaved }) // only user quits (Cmd+Q, a Quit item)
app.OnOpenURL(func(u string) { route(u) }) // deep links
app.OnOpenFiles(func(paths []string) { open(paths) })App-level notifications arrive through App.OnEvent: open URL, open files, theme changed, displays changed, reopen (macOS Dock click), notification opened, and on mobile safe area, orientation, push and WebView-restored events. The deep link that launched the app is kept until a listener is registered. sys/single forwards a second launch's arguments to the running instance. Options.QuitOnLastClose decides whether closing the last window quits (default: no on macOS, yes on Windows and Linux); windows created with SurfaceOptions{Auxiliary: true} (an update window, a tool palette) do not count.
Register long-lived Go objects with service.Register(app, db, syncer) or expose one to IPC with service.Bind(app, r, "Notes", notes). Startup(ctx) runs in registration order and Shutdown() runs in reverse. Startup failure closes the services that already started, quits the app and is available via service.Err(app).
Security model
TanGo assumes the page is not fully trusted:
- Message origin check — the core accepts messages only from the asset origin and from the origin it last navigated the surface to; everything else is dropped before
OnMessage. Only main-frame messages are delivered. - jsapi allow-list — page access to system capabilities is grouped (
Window,Menu,Infoon by default;ClipboardRead,ClipboardWrite,Dialogs,Notify,OpenURL,OpenPath,AppControl,Hotkeysand the fiveWebcapabilities off by default) and enabled in Go withjsapi.Install(app, r, jsapi.Options{Allow: …}). Disabled capabilities reject withforbidden. Window methods only ever act on the calling window. - Narrowed operations —
shell.OpenURLaccepts onlyhttp,httpsandmailtounless you change it (file:never); page-described menus may only use edit roles; global shortcuts belong to the page that registered them. - WebView policies —
SetNavigationPolicy,SetPermissionPolicy/SetPermissionHandler(camera, microphone, geolocation, …) andSetNewWindowHandlerlet Go decide; by default new windows for the app's own origin open as surfaces,http(s)/mailtogo to the system browser, and anything else is denied. - Production by default — every build without
-tags tango_dev(plaingo build,go run ., goreleaser,tan buildincluding-debug) leaves out the development features (hot reload, automation channel, dev-server proxy) and ignores their environment variables, so another process of the same user cannot turn them on.tan dev,automation.Launchand MCP package launches addtango_devto their development builds. The oldtango_releasetag no longer does anything.
Methods you expose yourself with bind or Handle are reachable from the page too: validate their arguments. Report vulnerabilities privately as described in SECURITY.md.