Skip to content
Hrushiekesh Reddy Kanjula
A central glowing state object coordinating Python backend and JavaScript frontend

Taming a 1,200-Line Python Function: State Management in Async Desktop Apps

Python and JavaScript each held their own copy of the UI state, so I moved all of it into one Python object and pushed snapshots to the frontend.

Published
March 2, 2026
Author
Hrushiekesh Reddy Kanjula
Read time
~3 min
Category
engineering

Centralized state management between Python and JavaScript

In the assembly hub, the component rotation approval loop was a single function, 1,200 lines long. It handled user interactions, state transitions, database reads, machine API calls and WebSocket callbacks, all in one block. It grew that way one edge case at a time.

The root problem was state. Python and JavaScript each kept their own copy of it, and the two drifted apart. This post covers how I fixed that and what it made possible.

How the state fragmented

In a normal web app, state lives in one place: the frontend. useState, Redux and Zustand all work because the browser is the only runtime.

Eel apps have two runtimes. A Python process and a Chrome window talk over a WebSocket. State can sit in Python (memory, database), in JavaScript (DOM, variables), or split across both with no clear source of truth.

The rotation approval workflow was split. A Python variable tracked the "currently selected" component. A JavaScript variable tracked the same thing for rendering. Navigating forward updated the Python one. Pressing undo updated the JavaScript one. After three interactions they disagreed. The UI highlighted component #47 while the backend thought we were on #52. The bugs only showed up under specific click sequences at 3pm on a Thursday.

State fragmentation between Python backend and JavaScript frontend

One source of truth in Python

The fix is simple. All state lives in Python. The JavaScript frontend only renders. It receives state snapshots and never owns state.

dataclasses keeps this clean:

from dataclasses import dataclass, field
from typing import Optional, List
 
@dataclass
class GUIState:
    components: List[dict] = field(default_factory=list)
    current_index: int = 0
    is_approved: dict = field(default_factory=dict)
    active_machine: Optional[str] = None
    
    @property
    def current_component(self) -> Optional[dict]:
        if not self.components:
            return None
        return self.components[self.current_index]

That is one object with every piece of UI state declared and typed. There are no nonlocal variables scattered through nested functions and no global mutable dicts. Navigating forward is state.current_index += 1. It is one line, traceable and testable.

Push from Python to JavaScript

With one state object, sync becomes a push. When state changes in Python, push the relevant slice to JavaScript.

@eel.expose
def approve_current_component():
    state.is_approved[state.current_component['ref']] = True
    state.current_index += 1
    # Push updated state to the frontend
    eel.update_ui_state({
        'component': state.current_component,
        'progress': f"{state.current_index}/{len(state.components)}",
        'approved_count': sum(state.is_approved.values())
    })()

The JavaScript side is a dumb renderer:

eel.expose(update_ui_state);
function update_ui_state(stateSnapshot) {
    renderComponent(stateSnapshot.component);
    updateProgressBar(stateSnapshot.progress);
    updateApprovedCounter(stateSnapshot.approved_count);
}

There is no logic and no state in the frontend. When something breaks, I debug Python: one language, one runtime, one place to look.

Push-based state sync from Python to JavaScript via Eel WebSocket

Breaking up the 1,200-line function

A 1,200-line function is scary because you cannot see its boundaries. You do not know what it touches or what touches it. With an explicit GUIState, every function's dependencies are visible. Functions that only need state.current_component can be pulled out cleanly. Functions that modify state.is_approved are easy to find and audit.

The rotation loop became eight functions averaging 40 lines each. Each has one job and a clear input and output. Testing went from "impossible" to "straightforward": build a GUIState with test data and check the output.

Async callbacks and the lock

Eel's WebSocket layer is async, but the Python functions it calls run in the main thread. A background telemetry scheduler can change state while the UI is mid-interaction. That needs a threading strategy.

I put a lock on the state object:

import threading
 
state = GUIState()
state_lock = threading.Lock()
 
def safe_update_state(fn):
    """Decorator that wraps state mutations in a lock."""
    def wrapper(*args, **kwargs):
        with state_lock:
            result = fn(*args, **kwargs)
            eel.update_ui_state(state.to_snapshot())()
            return result
    return wrapper

Background threads take the lock before changing state. That stops a UI callback from reading state halfway through an update. It also makes the concurrency model explicit. Any function that touches state is decorated. Any function without the decorator is read-only.

Threading lock pattern for safe concurrent state mutations

What it enabled

Some features were nearly impossible in the monolith.

  • Undo/redo: a state history stack. Push on every mutation, pop on undo.
  • Crash recovery: serialize GUIState to JSON and reload it on startup.
  • Multi-step workflows: each step is a state transition with a clear trigger and outcome.

The rotation approval workflow went from "don't touch it" to three new features shipped in the next sprint. For a desktop app with a Python backend and web frontend, decide the state architecture first. Everything else builds on it.

Hire me