Skip to content

gpyui architecture

gpyui is a published native desktop Python library. The initial source inspection was completed on 2026-10-01; the current API includes 80 controls and the release version is 0.6.1, including Image, expanded window controls, exact macOS Classic themes, richer tables/inputs and command search. The released backend pins GPUI Kit 0.7.1 / GPUI 0.3.8. Version 0.7.0 targets Kit 0.11.0 / GPUI 0.3.14. See upstream-lock.json for the exact pins. See coverage and remaining APIs for the source-reviewed baseline, release distinction and roadmap. The first-milestone analysis below records the bridge's original design decisions.

The data/input milestone retains native TableState and source-index selection, with separate visible indices for sorting/filtering and Python TableRow keys for domain selection across data replacement. Dependent options/selection updates are validated as one batch against the latest bridge schema. CommandPalette retains Kit CommandState, uses the same registered native actions as menus and buttons, and mirrors queries before Python callbacks and action snapshots.

Product goal

gpyui exposes Longbridge's GPUI Kit components through a reusable Python API so developers can write complete native desktop applications entirely in Python, comparable in use to Tkinter and other Python UI toolkits. Rust is the internal implementation of native rendering, component state, text editing and windows; application authors compose controls and implement application behavior in Python.

The four-control milestone proves this bridge. It is the beginning of the toolkit, not its intended final component set. Subsequent work should extend actual GPUI Kit component coverage and make layout, styling, events, state and application lifecycle accessible through Python. Document implemented capabilities separately from planned coverage, and verify each wrapper against pinned sources.

Images (0.6.1)

Image binds the actual GPUI img() exported by Kit. Each retained native image entity runs GPUI's decoder on the background executor and owns one current decoded result. Encoded Python bytes use a temporary composite asset source; files and URLs use native Resource types. A matching Reqwest client enables native HTTP(S). Load/error notifications use the shared asyncio callback queue, with cancellation and revision checks preventing stale delivery. Fit and style updates retain the result. See source evidence and the Python image guide, including the separate requirements for video.

Forms and validation in 0.5.0

Python Form and Field construct Kit's real typed builders. Rust owns grid/label layout, required indicators and descriptions; help and inline errors are rendered through Kit description_fn. Existing native input entities are reused when validation metadata changes. Python validators and save callbacks run through the existing owned asyncio loop and shared Command bridge.

Each Form has one submit Command used by buttons, menus and shortcuts. Validation uses copied raw values and excludes hidden Fields. It guards concurrent work and discards stale async results when active Fields, editors, required flags or values change. Expected ValidationError and OSError failures show retryable feedback; programming errors and cancellation follow the existing lifecycle. Validation never replaces editor text, caret, selection or undo history. See implementation evidence and acceptance and the forms guide.

Window controls and exact macOS Classic (0.6.1)

Application now exposes native creation flags, minimum content dimensions, position and initial state. Queued title/size/focus/minimize/maximize/fullscreen requests stay on Rust’s UI thread. A separate native WindowState and bounds observer enforce fixed windowed dimensions while preserving all retained controls and editing state. Snapshots distinguish requested dimensions from actual native bounds. Platform limitations come from the pinned GPUI backends.

The macos preset now loads Kit’s unchanged Classic Light/Dark JSON, including all source colors and Kit-parsed highlights. Kit default geometry/system typography and upstream shadow=False replace the earlier approximation. Windows renderer hints remain; Classic adds no presentation wrappers. Scalar defaults reset on switching, and default highlighting resets when leaving a highlighted config. See source evidence and acceptance, window controls and themes.

Native themes in 0.4.0 and refinements in 0.5.0

Python exposes immutable Theme descriptions with macOS, Windows/Fluent and shadcn Zinc/Blue light/dark presets, custom colors, radii, typography and shadows. Rust translates a validated description to Kit ThemeConfig and applies it through Theme::update, synchronizing legacy component colors, background and Base tokens. Queued runtime theme changes refresh rendering without remounting controls or setting text values. Theme snapshots expose applied native state independently of the requested Python description. See the source-grounded plan and theme guide for verified APIs and limits.

Platform refinements in 0.5.0 add Rust-owned appearance hints alongside Kit's ThemeConfig: editor surface and checked-switch color. The original Kit Input, Textarea and Select entities render inside presentation-only frames, using their original focus handles. Kit sizing/style hooks give macOS and Windows distinct control geometry. Colors supported by Kit flow through ThemeConfig as before; renderer-specific colors are validated before enqueue and installed before Kit refreshes windows. Switching away resets every hint. Native snapshots report the applied surface/switch/slider colors. Layout composition stays Python-owned.

Commands and menus in 0.3.0

The implementation retains the pinned upstream baseline below. Before adding menus we inspected DropdownMenu, ContextMenu, PopupMenu, AppMenuBar and NativeMenu. The actual NativeMenu conversion is From<gpui::Menu>; its doc comment's from_menu_items method does not exist in the pinned implementation.

The implementation follows these verified steps:

  1. Add Python Command/Menu models separate from controls, with stable IDs and window-lifetime ownership. Register references before validating/committing tree and menu configuration; reject duplicate shortcuts and cross-app reuse.
  2. Represent native activation with a typed GPUI Action carrying the command ID. Bind keys in the window's root context. Kit buttons and popup items enqueue the same command event, including native editing snapshots; Python sync/async handlers continue on the existing asyncio worker.
  3. Build actual Kit menus and retain weak popup entities so updates can rebuild open drawn menus without replacing editors or introducing ownership cycles. GPUI's menu action-context focus restoration remains native. Native menu overlays outside the view also need an application-level action fallback.
  4. Use GPUI's system menus on macOS and Kit AppMenuBar on Windows/Linux. OS popup tracking remains in Kit NativeMenu, including the drawn Linux fallback. Capture assigned native context-menu presses before the input's built-in menu; for drawn menus suppress that input callback for the current right press. Kit restores the default editing-menu callback on the following render.
  5. Test shared enabled/checked state, nested menu routing, dynamic registration, async snapshots and shutdown with actual native interactions and installed release wheels, then document the narrower platform guarantees.

Native command properties use explicit patches. Reconciliation never replays old mutable command values. Button disablement combines local disabled state with shared command enabled state. Source-bound drawn popup callbacks validate that their host remains displayed and the command still belongs to its menu. Commands themselves remain registered for the window lifetime. Menu and popup refresh flags avoid reloading application menus on unrelated label/input edits. OS-native open menus contain a snapshot, but the latest enabled gate is checked again at activation. The public commands guide records bounds, menu-update behavior and remaining command-palette/keymap gaps.

Dynamic composition in 0.2.0

Python roots and container children now support runtime replacement, insertion, removal, reordering and same-app moves. A structural update sends the owned forest, active root IDs and explicit property patches in one queued command. The bridge validates the entire command, including unique ownership, depth, constructor identity and disposed IDs, before enqueueing and committing its schema. Failed enqueue leaves the old native schema intact.

Rust reconciles by stable ID: existing native controls, entities and per-control subscriptions are reused. Only children lists change; mutable tree-description values are never replayed into existing editors. That distinction preserves native edits that have not reached the Python mirror, caret, selection and undo history. It follows Kit's retained Entity<InputState> contract and semantic undo transaction boundaries.

Visibility removes the control from layout without destroying its state. Removal detaches but keeps ownership and bindings, allowing reattachment. Explicit dispose() releases the subtree, native entities/subscriptions, Python bindings and handlers; disposed IDs cannot be reused. Detached nodes count toward the 10,000-control bound. Native focus is blurred when an editing control becomes hidden or detached; moving a displayed control retains its focus. Python ignores disposed events and suppresses handlers for hidden or detached controls.

Open overlays read current children from the retained view, and carousel bounds follow visible children. Property-only updates retain the existing compact batch path. Structural commands serialize the retained forest; large-tree update performance and a smaller structural diff protocol remain future measurement work. There is still one window; themes can change at runtime.

The comparison and first-milestone plan below record the original investigation; this section describes the current runtime contract.

Reproducible upstream baseline

The original investigation compared four repositories. The current backend snapshot and comparison revisions are recorded in upstream-lock.json.

  • GPUI Kit: e97fe438129c5e4ccab504f2e6fafd9a4e396bba (0.11.0).
  • Zed/GPUI: f126950f9d3b62666f97437ae5d4ccac2272c4db.
  • NiceGUI: d0323a34fd87c51323e4fda60f6805d6fe8e329d.
  • Flet: 0ec63ca849386be77831241f21b82a0cc8c13942.

GPUI Kit's workspace manifest pins the gpui-pre-* family to exactly 0.3.14. The downloaded GPUI manifest's [package.metadata.gpui-pre] identifies the Zed revision above as the snapshot source. The matching HTTP client uses the same snapshot. Do not add a second, git-head GPUI dependency: its types would differ from Kit's. Depend on the pinned gpui-kit git revision and use its facade. Cargo.lock pins registry versions, checksums, and git sources; the Rust toolchain and PyO3 versions are explicit. No upstream repository is modified.

The Kit root AGENTS.md has a stale final bullet saying GPUI is a git dependency; the manifest, facade implementation, and release pin checker are authoritative.

Implementation evidence and adopted patterns

Links below identify actual implementations at the inspected revisions, rather than tutorials. The local clones contain the same paths.

Concern NiceGUI implementation Flet implementation gpyui decision
Composition Element construction and context managers, Slot task-specific stacks attach children to the current slot Column.controls stores an explicit ordered control list Support both Column([Label(...), ...]) and with app: with Column(): .... A ContextVar stores immutable stack tuples, preventing shared mutable stacks across tasks. No implicit process-global application.
Control objects Element owns ID, props, events, slots, parent/client references; client indexes elements BaseControl uses dataclass-based controls, stable identity, parent/page, mount/unmount hooks Python controls are stable handles and property mirrors. A mounted tree has unique stable IDs and one owner per control. Rust owns the native representations and retained entities. Initial milestone freezes topology after mounting.
State binding binding.py uses BindableProperty setters, propagation graphs with visited nodes, and polling for active links to arbitrary attributes use_state replaces state on inequality and schedules the owning component; observable state attaches lifecycle-owned subscriptions An explicit State observable and bind_text/bind_value; changes propagate on setters/events, with equality guards. No arbitrary attribute polling or full React-style hook/reconciliation system in this milestone. Binding subscriptions can be disposed.
Updates Outbox replaces pending updates by element ID and drains them asynchronously Session computes ObjectPatch diffs and coalesces scheduled controls in a set; ObjectPatch tracks dataclass changes Coalesce changes by (control ID, property) per asyncio turn, with explicit app.update() and app.batch() boundaries. One validated JSON batch crosses PyO3; Rust applies it in one foreground update and notifies the root once. Full tree diffing is unnecessary for a fixed tree.
Event handlers events.handle_event supports zero/one argument, awaitable results, parent-slot context and centralized exceptions BaseControl._trigger_event supports zero/one argument, sync/async and generator handlers; Session.after_event automatically updates unless disabled/explicitly updated Resolve zero/one argument signatures once. Native callbacks only enqueue data. Python schedules tracked callback tasks on one owned asyncio loop, catches and reports failures, and flushes properties even while a coroutine awaits. Generator handlers are deferred.
asyncio and threads background_tasks retains tasks, handles exceptions and tears them down Current BaseControl calls synchronous handlers directly on its asyncio loop (do not assume the historical Flet thread-per-handler behavior). app.py owns asyncio/server lifecycle and connection executors GPUI main thread and Python asyncio worker thread. Rust releases the GIL while running the platform loop. An async-channel wakes a GPUI foreground task; Python receives queued events via a blocking extension call in asyncio.to_thread, also without the GIL. Sync handlers must stay short; use asyncio.to_thread for blocking work.
Lifecycle nicegui.py uses ASGI lifespan; ui_run starts uvicorn; native mode uses a webview process app.py creates socket/Dart/web connections, starts main per session, closes connections on shutdown One native app run per process, main-thread entry, single window in milestone. Window close/app.close() ends native run, signals the event pump, cancels and gathers callback tasks, closes the asyncio loop, joins the worker, releases retained subscriptions. No web transport.

Verified native seam

  • Kit facade and open_window: application, init, open_window return the window and application entity; the helper installs Base Root. Component initialization registers window state.
  • hello_world: Button is a lightweight builder, re-created during Rust render, with stable ID.
  • input example: retained Entity<InputState> and retained Subscription handles; rendering uses Input::new(&state) instead of creating an editor every frame.
  • editing state: InputEvent::Change, value(), default_value(), set_value(). Programmatic set_value emits no Change and clears undo history; gpyui documents this distinction and never re-sends native edits to Rust through the value setter.
  • GPUI Context: spawn_in schedules a main-thread future with WeakEntity and AsyncWindowContext; update_in provides short-lived mutable contexts. Retain its Task on the root so close cancels it. Never move entities/windows across the Python boundary or call Python from render.
  • GPUI Application: native platform.run owns the event loop; quit and window-close subscriptions belong to the application. Main-thread platform initialization is required.
sequenceDiagram
    participant P as Python asyncio worker
    participant Q as PyO3 bridge queues
    participant R as Rust GPUI main thread
    R->>Q: Native input change / button activation
    Q->>P: Ordered events with input value snapshots
    P->>P: Sync handler or tracked coroutine
    P->>Q: Coalesced property batch
    Q->>R: Wake foreground task
    R->>R: Validate whole batch, update entities, notify
    P->>Q: Snapshot barrier
    R->>Q: Applied native state snapshot
    Q->>P: Resolve awaiting snapshot

Implementation plan and acceptance gates

  1. Reinitialize with the requested uv/maturin command (the earlier uv_build scaffold is preserved in /tmp/glint-initial-uv-project), then rename to gpyui.
  2. Clone all four repositories, read applicable instructions, match Kit/GPUI snapshots and record immutable revisions. Complete this document before the bridge implementation; cargo check --locked validates actual compatibility.
  3. Implement Column, Label, TextInput, Button, Application and explicit State; both context composition and explicit children use the same tree.
  4. Implement Rust-owned tree/editor/window, validated property commands, channel-driven foreground updates, ordered native events, snapshot barriers, close and error signaling. Release the GIL around native run and waits.
  5. Build the extension with maturin/uv; test composition ownership, state binding, invalid batches, callback failures, awaitable handlers and lifecycle.
  6. Open a real native X11 window under Xvfb and Mesa software Vulkan. Type into the real Input, activate the Kit button using pointer and keyboard, and assert the Python-derived label through a native snapshot and rendered screenshot. Close normally and during an awaiting callback. Keep evidence and limitations in validation.md; never substitute mocked rendering for a native run.

Original first-milestone scope

The original first milestone supported a static column tree with mutable labels, input values/placeholders, button text/disabled state. It deferred dynamic topology, multiwindow, arbitrary styling, timers API, async run() embedded in another main-thread loop, Python render callbacks, or packaging claim. Python .value is the last received native mirror; click events include current Rust input snapshots to make the normal read-on-click workflow coherent. await app.snapshot() is a foreground barrier, not a guarantee that a GPU frame has already been presented.

The channel protocol uses JSON for inspectability, not because IPC is necessary. Batches and events stay in-process. Queues are bounded and reject overload explicitly rather than blocking the UI or silently losing activations. Prototype performance, high-rate input coalescing, topology reconciliation and finer entity notification boundaries before expanding the API. GPU rendering releases the GIL, but CPU-bound pure Python still competes for it with other Python tasks.

Linux/X11 has full native interaction tests. The wheel workflow also builds Linux ARM64, Windows x64/ARM64 and macOS Intel/Apple Silicon. Windows and macOS use the pinned upstream platform backends and have native window smoke tests, with OS mouse/keyboard interaction still to validate. Upstream native libraries, GPU/display drivers, assets, and dependency licenses require review before distributing wheels. The package is now published on PyPI as gpyui.

Expanded Kit catalog: verified implementation

The second pass expands the same bridge to 71 controls. It keeps the pinned Kit and GPUI revisions; no alternate widget implementation or second GPUI version was introduced. Component coverage is the complete implemented inventory and remaining catalog work.

The following upstream contracts were inspected before writing their wrappers:

  • SliderState, SelectState and ComboboxState are retained entities with native event subscriptions. The wrappers mount each entity once, read it for snapshots and render builders referencing it.
  • TableState and TableDelegate retain native selection and scrolling. Python supplies string columns/rows; Rust owns the delegate. Assigning rows refreshes the native table.
  • TreeState, ResizableState and native input/calendar/color entities follow that same ownership rule. Tree selection maps to stable Python item IDs; resize events carry native sizes.
  • WindowExt provides dialog, sheet and notification operations through the installed Root. Python open/close commands execute on the foreground task; native dismissal emits a change event back to Python. Overlay content is the existing Python control tree rendered in Rust, with one dialog and one sheet per window.
  • TextView renders Markdown/HTML natively. Editor keeps an InputState editing buffer. Python never supplies a per-frame render callback.
  • Chart builders consume Rust-owned point data. Python can replace datasets through the same coalesced property queue. Plot rendering and hover behavior stay native.

A Kit node extends the original typed tree with a whitelisted component kind, validated property map, children and style. Both Python and Rust check contracts; Rust validates an entire update batch before enqueuing it. Component parameters that define native construction (for example slider range, select items and OTP length) are immutable after construction. Collection properties are copied on assignment/read to avoid mutations that bypass the queue.

Lightweight controlled builders immediately update Rust state on interaction and notify the view, then queue their Python event. Stateful builders update their retained native entities. Event snapshots now include all value-bearing controls, so the existing activation-order guarantee also applies to the broader catalog. Python updates mirrors/bindings before starting a callback, yields to start it, and only then processes subsequent queued events. Async callbacks remain tracked by the original owned worker loop and cancellation lifecycle.

Layout styles use pixel dimensions and Kit semantic theme colors. Layout styles are applied to the layout node itself, so gaps/alignment affect its children. Leaf styles wrap the actual Kit component. Explicit sizes do not shrink, while flexible panes can shrink within the window. Themes can be chosen at startup or switched on the callback loop.

The workspace and gallery are public Python API examples, not Rust-specific demos. The workspace simplifies the reference trading terminal to a watchlist, one chart, a market tape, an order form and a paper-order table. A seeded asyncio stream batches simulated quotes and trades every 650 ms; its callback is cancelled on native close. A native button invokes an async Python handler that appends an order, updates status and shows a Kit notification. It makes no network trades.

Current limits: single window and basic builder options. Virtualized list delegates, typed schemas, docking, multiwindow and additional plot families remain explicit implementation work. Acceptance gates for these next steps are recorded in the coverage guide.