Skip to content

Browser live-reload (push page refresh / asset swap on hot reload) #9

Open

Description

@JuroOravec

Summary

Track the opt-in browser-side live-reload: when a watched file changes, push
a refresh (or a targeted asset swap) to the browser so the developer sees the
change without manually reloading the page.

This is the browser half of hot reload. The server half (the file watcher that
invalidates component caches in place) is designed in
docs/design/hot_reload.md and is not part of
this issue.

Why this is separate from the migration

The django-components migration only ports the server-side invalidation seam
(Citry.get_components_for_file, reset_template/reset_files). There is no
client live-reload channel today: the client runtime's MutationObserver only
ingests dependency manifests, and asset URLs are content-hashed for caching, not
for live push. Browser refresh needs net-new design (a dev-only WebSocket or SSE
endpoint plus a small injected client script), so it lives outside the migration
and outside the file-watcher design.

Seam that already exists

  • Extension.urls can mount a dev-only SSE or WebSocket endpoint (the
    contrib adapters already mount Citry.urls).
  • The watcher's on_reload callback in
    docs/design/hot_reload.md is the trigger to fire
    from the server.
  • A tiny injected client script reloads (or swaps the changed CSS) on message.
  • arel is the reference implementation of this pattern for ASGI hosts
    (Starlette/FastAPI): WebSocket + injected script + reload hook.

Decisions to make

  • Full page reload vs targeted CSS/asset swap (CSS swap avoids losing page state).
  • Which hosts first (ASGI is the natural start; WSGI has no push channel without polling).
  • How the dev-only injected script is delivered and gated to development.
  • Integrate/depend on arel for ASGI vs ship a minimal first-party endpoint.

Out of scope

The server-side file watcher and cache invalidation, tracked in
docs/design/hot_reload.md.

Activity

  1. JuroOravec commented on Sep 11, 2026

    @JuroOravec
    MemberAuthor

    Additional prior art from investigating django-components#1714: django-browser-reload is a useful reference for the browser half of this feature.

    Its design is:

    1. Middleware or a template tag injects a small listener script into development HTML responses.
    2. The script connects through a SharedWorker to a server-sent events endpoint backed by StreamingHttpResponse.
    3. Template/static changes publish a reload event without restarting Python.
    4. Python changes that no receiver claims use Django's normal process restart. A random per-process version ID is sent when the event stream reconnects; a changed ID tells the browser to reload.
    5. Periodic pings carry the process version and keep the stream active. The SharedWorker shares one event stream across same-origin tabs, retains only the most recently connected tab's port, and sends reloads to that tab.

    A common development-server design injects a client, keeps an SSE or WebSocket channel open, and refreshes on a change, reconnect, or version event. SharedWorker is an optional connection-sharing optimization. Citry should choose it only after checking browser requirements and whether one connection per tab is actually a problem. SSE is sufficient for one-way notifications and has automatic reconnection; WebSocket is useful if the development channel is expected to become bidirectional. Under WSGI, the streaming response occupies a server thread and does not work with runserver --nothreading; sharing the connection limits that cost across tabs.

    Integration hazard: change handlers must classify by file semantics

    The django-components reproducer exposed a failure mode Citry should test explicitly:

    • django-components registers its component directories as Django template-loader directories so component HTML can be found.
    • django-browser-reload treats every changed file beneath a template directory as handled by browser refresh and returns True from Django's file_changed signal receiver, without filtering by suffix.
    • A component .py file therefore gets classified as a template change. The browser refreshes, but Django suppresses the process restart, so the refreshed page continues executing the old Python class.
    • django-components v0.151.1 returns None for an ordinary component .py, expecting Django's normal Python restart. The other receiver's True vetoes that restart because Django only calls trigger_reload() when no receiver returns a truthy value.

    This is separate from Django's startup snapshot race. This path is sufficient to explain repeated saves remaining stale in the supplied reproduction.

    Design implications for Citry:

    • Carry an explicit change kind through the watcher callback (python, template, css, js, and other asset) rather than inferring behavior from directory membership alone.
    • Python changes must request/permit a host process restart. A browser refresh is not a substitute for re-importing Python modules.
    • Only return a host-framework "handled"/restart-suppression result for file types Citry actually refreshed in-process.
    • Keep browser notification separate from restart ownership: an asset change can notify immediately, while a Python restart can notify through a new process/version token after reconnect.
    • Test multiple change receivers/extensions together. The regression test should place .py and template/assets in the same component directory and verify both the serving PID and rendered output, since a browser refresh or extra HTTP request does not prove Python restarted.
    • Include reconnects, duplicate events, multiple tabs, server shutdown, streaming connection cleanup, and development-only gating in the browser test matrix.

    References:

  2. JuroOravec commented on Sep 11, 2026

    @JuroOravec
    MemberAuthor

    Vite provides useful prior art for transport choice and HMR scope through its HMR API and client-server communication API.

    The basic Citry browser-reload path is one-way. File changes originate on the server, and the browser initially only needs messages such as:

    {"type": "reload"}
    {"type": "css-update", "url": "..."}
    {"type": "server-version", "version": "..."}

    SSE is therefore sufficient for a first implementation. It provides server-to-browser events and automatic reconnection with a smaller protocol surface. In a single-worker development host, a per-process version sent after reconnect can distinguish a Python process restart from an ordinary asset notification. A multi-worker host would need one server-generation identifier shared by its workers so reconnecting to another live worker is not mistaken for a restart.

    Vite uses a WebSocket transport and exposes bidirectional HMR APIs. The server can broadcast custom events or target one client, and browser code can use import.meta.hot.send() to send typed custom events to a plugin. This can support framework integrations, diagnostics, editor/devtools commands, client-specific acknowledgements, and other interactive development features.

    Vite also maintains a browser module graph and applies updates without navigating the page:

    • map one changed file to one or more served modules;
    • propagate invalidation through importers until reaching an import.meta.hot.accept() boundary;
    • load updated module instances at accepted boundaries without navigating the page;
    • preserve selected state through import.meta.hot.data;
    • run dispose() before applying an accepted update and prune() when a module is no longer imported by the page;
    • let a module call invalidate() when it cannot safely accept an update;
    • update CSS independently;
    • report transform/syntax errors through browser error events and an overlay;
    • fall back to a full-page reload when no safe update boundary exists.

    For Citry, this suggests an incremental boundary:

    1. Start with SSE for full-page reload, targeted CSS replacement if justified, and process-version detection after reconnect.
    2. Keep the message envelope transport-neutral so a future WebSocket transport can use the same server-originated events.
    3. Add WebSockets only when Citry has a concrete browser-to-server requirement, such as component diagnostics, devtools commands, active-module reporting, or update acknowledgements.
    4. Treat Vite-style module replacement as a separate HMR capability. It requires dependency/update-boundary tracking plus lifecycle and state-preservation contracts; it should not be implied by the initial browser live-reload feature.

    This also reinforces the earlier django-browser-reload lesson: transport and reload policy are separate. Receiving a browser-refresh event must never imply that a changed Python module was safely applied without a host process restart.

  3. added
    next-sprint
    on Oct 28, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    next-sprint

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions