Architecture¶
CascadeUI is a state-management and UI framework built on top of discord.py. It replaces ad-hoc view logic (scattered attribute mutation, manual message edits, hand-rolled navigation stacks) with a centralized store, dispatched actions, and reducer-driven updates. The architecture borrows from the Redux family (unidirectional data flow, pure reducers, middleware pipeline) and adapts the pattern to Discord's component model.
This document describes the load-bearing choices behind the library and explains how the pieces fit together. It is written for developers evaluating the library for their own bot and for contributors who want the architectural "why" before reading the code. The Code Map shows which module holds each piece.
For day-to-day usage, start with
Your First Panel
and How CascadeUI Thinks.
Familiarity with discord.py's View, LayoutView, Interaction, and
WebhookMessage primitives is assumed.
Unidirectional Data Flow¶
Every dispatched action, from a click's callback or from the library,
follows the same path. The middleware chain passes it to the reducer, each
middleware in the order it was given to setup_middleware(). The store
keeps the reducer's new state and notifies its subscribers. A view hears
the actions listed in its subscribed_actions, and one whose selector
reports a change, or that has no selector, calls on_state_changed(),
which runs build_ui() and then refresh() to edit its message.
The library holds the parts of that path where concurrency bugs start.
Reducers run one at a time, and a reducer registered with
@cascade_reducer gets a copy of the state to change and return. A
dispatch made from inside a reducer raises instead of deadlocking.
A view renders one state change at a time and folds the notifications
that arrive meanwhile into one render of the newest state, so two clicks
landing together do not race two edits of one message. The rest is
convention: a callback changes state by dispatching (or through
set_scoped()) rather than by writing to store.state, and a reducer
does no I/O.
See How CascadeUI Thinks for the pipeline in full detail.
The Five Pillars¶
Every view-layer feature belongs to exactly one of five domains, and each answers one question about a panel's life:
| Pillar | Question answered | Surface |
|---|---|---|
| Access Control | Who can interact? | owner_only, allowed_users, on_unauthorized |
| Instance Constraints | How many exist? What happens at the limit? | instance_limit, instance_scope, instance_policy, replace_policy, protect_attached, participant_limit |
| View Lifecycle | What happens on timeout, error, or exit? | timeout, exit_policy, on_timeout, on_error, auto_defer, enable_undo |
| Session Membership | Which views share data? | session_id, shared_data, attach_child, session_continuity |
| Navigation | What view came before? | push, pop, replace, auto_back_button |
The pillars are independently tunable. A view with owner_only = True can
still have instance_limit = None. A view with instance_limit = 1 can
still allow multiple users through allowed_users. No attribute straddles
two pillars.
See The Five Pillars for the full attribute tables and orthogonality examples.
The discord.py Boundary¶
CascadeUI wraps discord.py rather than replacing it. The library adds a state layer, a lifecycle layer, and a pattern layer. Everything below the component interface remains discord.py.
Inherited from discord.py (unchanged):
- Component classes (
Button,Select,Modal,TextInput) ViewandLayoutViewbase classesInteraction,WebhookMessage, and the REST adapter- Gateway events, intents, and command registration
Client/Bot/commands.Coginfrastructure
The library changes none of these classes. On a bot it is given, it changes that one object:
- Its
close()andconnect(), so the bot's views are released and persistence finishes its writes and closes before the program ends. - Its view store, so a click on an id the panel has since redrawn is acknowledged instead of failing, and Discord's echo of an older edit does not reach a library view.
- Its listeners, gaining four that close a view when its message, channel, or thread is deleted.
Added by CascadeUI:
Modaland the five input wrappers. Each input carries its own validators, and the modal collects them and has its own backstop that acknowledges a slow submission.- The
is_done()-aware responder helpers (respond(),respond_safe(),open_modal()) - Centralized
StateStorewith pub/sub subscriptions and a middleware pipeline - Per-view state integration (
session_id, the navigation stack,shared_data,enable_undo) - Class attributes that set access control, instance limits, lifecycle, and capacity
_send_pipeline, the send with its three-tier rollback on failure- Seven pre-built patterns, each in V1 and V2 where both exist: Menu, Form, Wizard, Tabs, Paginated, Leaderboard, and Roles (deprecated, removed in 5.0.0)
PersistenceBackendProtocol with capability flags and opt-in per-slot routing- Component convenience wrappers (
StatefulButton,StatefulSelect), V2 builders (card,action_section,key_value,alert), and decorators (with_loading_state,with_confirmation,with_cooldown) - Auto-defer safety net, interaction serialization, and refresh throttling
Everything CascadeUI adds can be incrementally adopted. A bot can
install the library, apply StatefulView to a single panel, and leave
the rest of its codebase on raw discord.py.
Decision Log¶
The load-bearing architectural choices behind the library, with the alternatives considered and the reasons for the final decision.
1. Redux-inspired state flow over hand-rolled observers¶
Decision: Centralized store, pure reducers, middleware pipeline.
Alternatives considered: Per-view observer callbacks, event emitters,
or direct attribute mutation with explicit refresh() calls.
Reason: Observer patterns scale poorly once multiple views share state: they produce notification storms and ordering ambiguity. A store with middleware serializes mutations through a single path, which makes debugging (logging middleware), persistence (persistence middleware), and undo (undo middleware) composable rather than cross-cutting. Pure reducers make unit testing state transitions mechanical and eliminate an entire class of race conditions where two callbacks mutate the same attribute concurrently.
2. Opt-in persistence per slot¶
Decision: Persistence is off by default. Slots participate by
declaring persistent_slots = ("slot_name",) on the view class or by
calling access_slot(..., persistent=True).
Alternatives considered: Opt-out (persist everything by default), or all-or-nothing (a middleware-wide flag).
Reason: Opt-out is the wrong polarity for a library. Ephemeral UI state (a paginator's page, a form's answers before Submit) should never hit disk, and making users remember to mark data non-persistent leaks state by default. All-or-nothing middleware flags force a choice between fully ephemeral and fully persisted, which is too coarse for real applications that mix both.
3. PersistenceBackend as Protocol with capability flags¶
Decision: Backends implement a Python Protocol and declare their
capabilities via a Capability flag enum (KV, RELATIONAL,
TTL_INDEX, SCHEMA_META, RAW_SQL, OPEN_ROWS).
Alternatives considered: An abstract base class forcing a SQL-shaped interface, or hard-coded SQLite integration.
Reason: A Protocol does not force inheritance, which makes adapting
existing storage libraries (Redis, Postgres, DynamoDB) a matter of
implementing the methods. Capability flags prevent the middleware from
assuming SQL semantics on a KV-only backend, or vice versa.
InMemoryBackend ships as the reference implementation, and the shared
backend tests run against it beside SQLite and PostgreSQL. It implements
every Protocol method (its raw SQL methods raise NotImplementedError,
since it declares no RAW_SQL), so downstream backend authors have a
working contract to match.
4. V1 and V2 component systems are peers, not a migration¶
Decision: Every pattern ships V1 and V2 variants, except Leaderboard and Roles, which are V2-only. V1 is not deprecated in favor of V2.
Alternatives considered: A V2-only library with a compatibility shim for V1, or a V1-only one with a slow V2 port.
Reason: V1 (View + embeds) and V2 (LayoutView + Containers) are
both first-class Discord component models, not successive versions of
one system. V1 is denser for embed-heavy UIs (a table of figures in one
embed, dashboards with many fields). V2 is better for component-first
UIs (interactive cards, sectioned layouts, media galleries). Forcing
migration would make the library useful only for one shape of bot.
5. Single _StatefulMixin instead of duplicated V1 and V2 bases¶
Decision: All view-agnostic logic lives in _StatefulMixin, which is
composed from one mixin per concern (decision 17).
StatefulView and StatefulLayoutView are thin subclasses that supply
their version-specific send() signature and component layout overrides.
Alternatives considered: Separate StatefulView and
StatefulLayoutView hierarchies with independent copies of access
control, lifecycle, session logic, and navigation.
Reason: Duplication would guarantee drift between the two versions as the library evolves, and it would push responsibility for feature parity onto every future change. The mixin holds every policy attribute, hook, and lifecycle seam, so a new feature is added once and both versions inherit it.
6. Acting-view fast path for interaction refresh¶
Decision: The subscriber whose view owns the current interaction
edits the message through interaction.response.edit_message,
collapsing the acknowledgement and the UI edit into a single HTTP
request.
Alternatives considered: Always defer and then edit through the channel endpoint (two HTTP calls), or always edit through the webhook endpoint.
Reason: The two-call path adds a round-trip to every click, which consumes rate-limit budget and widens the window where a second click lands mid-edit. The fast path removes the extra call for the common case (one click, one refresh, one edit). Every other render edits the message itself: another view's, one made after the click was already answered, and one whose fast-path request failed. That edit goes through the channel endpoint, or, for a panel reached only through an interaction token (an ephemeral one, or a public one the send could not read back through its channel), through the newest interaction that updated it.
Three failures are handled apart. A 429 arms the view's backoff and sends nothing. A refused body (50035) raises, since the channel edit would carry the same body. A request that stalls is not repeated at once, since a second attempt would spend the click's three seconds, and the render is sent again once the click is acknowledged.
The fast path is scoped with a contextvars variable set around the
interaction's callback, so only the acting subscriber takes it.
7. Scoped state as an organization pattern, not a persistence tier¶
Decision: Scoped data (get_scoped, set_scoped,
dispatch_scoped) lives under state["application"]["scoped"].
Scoping is a key-routing convention, not a separate persistence
namespace.
Alternatives considered: Dedicated scoped top-level namespace
with its own persistence configuration.
Reason: A separate namespace would force a choice between "scoped"
and "application" when the distinction is about routing (per-user vs
per-guild vs global), not about durability. Keeping scoped under
application means the persistence opt-in (persistent_slots =
("scoped",) or a named scoped slot) uses the same mechanism as any
other slot.
8. Three-tier rollback in _send_pipeline¶
Decision: send() cleans up progressively more state as each
success stage is passed (instance-limit check, participant
registration, Discord HTTP). A failure at stage N reverses stages 1
through N-1.
Alternatives considered: Best-effort cleanup with logging, or no rollback (user code handles partial failures).
Reason: Library code that registers state before talking to Discord must reverse those registrations if Discord rejects the send. Leaving half-registered views in the state store corrupts downstream reads. The three-tier model mirrors the acquisition order so every partial-failure path has an exact counterpart. The test suite exercises each tier against a mock Discord client.
9. Armed ephemeral freeze before the 15-minute cliff¶
Decision: An ephemeral view with its refresh handoff on replaces its
panel with a Continue Session button refresh_warning_seconds (90 seconds) before
the 15-minute token of the newest interaction that updated it runs out,
and ignores state-driven rebuilds from then on. A click on the button runs
on_load() and redraws the same view in place through that click's own
interaction, which becomes the panel's token. The handoff is on when auto_refresh_ephemeral is
True, or when it is left at None and the view's timeout is None or
longer than 900 seconds.
Alternatives considered: Let the view expire silently at 15 minutes, or reuse the webhook token (Discord does not allow it).
Reason: Discord's webhook tokens expire 15 minutes after the originating interaction. A long-running ephemeral view (a settings panel, a multi-step wizard) hits that limit with no fallback. Freezing the UI 13.5 minutes in keeps the Continue Session button on screen, so the user can go on without losing state. Without the freeze, a state notification in the last 90 seconds would rebuild the component tree and discard the button before the user reached it.
10. Class-attribute validation at __init_subclass__¶
Decision: Policy enums, numeric ranges, and boolean attributes are validated when the subclass is defined, not when the view runs.
Alternatives considered: Validation at __init__, or none (trust
user code).
Reason: A typo in instance_policy = "rejct" should fail at module
import, not forty clicks into a game when a user triggers the limit.
Validating at subclass-definition time produces clear errors at the
right call site with zero runtime cost.
11. Navigation as one transaction on the message¶
Decision: A push() or pop() hands the message from one view to the
next, or leaves it where it was. Only the navigation edits the message
while it runs. The source stays subscribed, holding its renders, and is
torn down only once the destination's edit lands. A failed edit discards
the destination and leaves the source as live as it was.
Alternatives considered: Tear the source down before the edit, or unsubscribe the source for the duration and re-subscribe it on failure.
Reason: Tearing the source down first meant a failed edit (a missed
acknowledgement, an expired token, a transient 5xx) left the message showing a view
whose handlers were already gone, so every later click was silently
dropped. Unsubscribing it for the duration needed a stand-in to catch the
state changes that arrived meanwhile, and the stand-in raced the commit.
Keeping the source subscribed and settling the outcome in one synchronous
step makes navigation all-or-nothing. replace() is a one-way transition:
it closes its source through exit(), so exit_policy, attached views,
and a persistent registration are handled as in any other close.
12. Duplicate custom_id detection over auto-uniqueness¶
Decision: Two components in one view that share a custom_id are
refused at the view's send, refresh, or navigation edit, and two inputs
in one modal that share a label are refused when the modal is built. The
library never rewrites an id the caller chose.
Alternatives considered: Make ids unique by appending a per-instance suffix, or leave it to Discord's HTTP 400 at send.
Reason: Persistent view reattachment matches the exact custom_id
Discord stored on the original message, so a suffix minted fresh on
restart dead-ends the button. Refusing instead surfaces the collision at
the send that would carry it, rather than as Discord's 400 (or, for
modal inputs, a silent value overwrite).
The ids the library generates name what a button does (its callback and label) rather than where it sits, and skip any id already on the tree. A modal input's generated id comes from its label, and one whose id another label already took gets a short code of its own label added. So only caller-supplied ids reach the refusal, where a collision is always a mistake. Naming by behavior also means a click sent from an older render runs the action its user saw, not whatever now occupies that position.
13. Pre-flight placement validation over Discord's HTTP 400¶
Decision: V2 component trees are checked against Discord's placement and size rules before they ship, at three seams: the initial send, every refresh, and each navigation edit. V1 trees get the checks that apply to them at the same seams: repeated ids and option values, select bounds, a button with neither a label nor an emoji, and text lengths.
Alternatives considered: Let Discord reject the payload and surface the 400, or validate once at send.
Reason: A 400 names the request, not the node, so a caller reads "Invalid Form Body" and reverse-engineers which of forty components was illegal. The validator names the offending node, its path, and the fix. All three seams matter because a tree that was legal at send can be made illegal by a rebuild, and checking only the first render would catch the mistakes that are easiest to catch anyway.
14. setup_middleware as the single install seam¶
Decision: Middleware installs through one awaited call,
setup_middleware(), which runs each middleware's initialize(store) in
order. The bot's setup_hook makes that call. Nothing stops a cog from
making it too, but none should.
Alternatives considered: Per-middleware install functions, a constructor-time registry, or letting each cog install what it needs.
Reason: Ordering is load-bearing and initialization is asynchronous:
backends connect, migrations apply, and rehydration blocks before the
first view renders. One awaited seam makes both facts visible at a single
call site the bot author owns. The call belongs to the bot rather than to
a cog, since a cog that changed the store's middleware chain would change
behavior for every other cog in the process without their authors
knowing. A restarted bot's setup_hook makes the call again, and each
middleware takes the place of the one of its kind already installed, so
the chain comes out as a fresh process builds it.
15. Two throttles, split by the question they answer¶
Decision: refresh_cooldown_ms paces the re-renders the library
starts and exempts edits made in answer to a click. with_cooldown guards
one control, per clicker by default (scope="user", with "guild",
"user_guild", and "global" for wider ones).
Alternatives considered: A single view-wide throttle governing every edit, or one policy attribute selecting between the two behaviors.
Reason: One throttle cannot answer both questions. Pacing a background re-render is a per-view concern, and stopping button-mashing a per-user one. A view-wide throttle asked to do the second slows every viewer of a shared panel for one person's clicking, and taxes the interaction it was never meant to govern. Splitting them lets each tool do the job its name claims, and is what makes the interaction exemption safe: without a working per-control guard, exempting clicks would leave no spam control at all.
16. get_nav_state() for what reconstruction cannot replay¶
Decision: pop() rebuilds a view from its constructor kwargs and
re-runs on_load(). Anything else that should survive is named by the
view through get_nav_state() / restore_nav_state().
Alternatives considered: Hold the parent instance and restore it, or
change the captured _init_kwargs so a selection replays as a kwarg.
Reason: Holding the instance keeps its subscriptions, tasks, and
message references alive behind a screen nobody is looking at, which is
the leak the navigation stack exists to avoid. Changing captured kwargs
works until a value is not JSON-serializable, at which point the registry
row is declined and a persistent view silently fails to reattach.
restore_nav_state() runs before on_load(), so a preload reads the
restored selection rather than fetching twice to correct itself.
17. One module per concern behind _StatefulMixin¶
Decision: _StatefulMixin inherits one mixin per concern, each in its
own private module under cascadeui/views/. Pillars 1 and 2 share
_access.py, pillars 4 and 5 have a module each, and the view lifecycle
(pillar 3) is split by phase. The Code Map
lists each module, what it owns, and the order Python looks names up in.
Alternatives considered: Keep one module, or split by V1 and V2.
Reason: One module had grown to about 8,000 lines and 245 methods, and its section headers no longer said what sat under them, so reviewing one part meant reading the others around it. A module per concern lets a change to sending or closing be read as one file. Splitting by component version was ruled out by decision 5.
Every name base.py defined before the split can still be imported from it,
though, like every module behind the package root, it is internal (see the
Stability Policy).
Each module logs under its own name (cascadeui.views._refresh, and so on),
so a level set on cascadeui.views covers them all.
When CascadeUI Fits¶
CascadeUI is designed for bots that ship stateful, interactive UI as a first-class concern. The library earns its complexity when:
- Multiple views share state and react to each other (a settings hub and its screens, a game's public board and its private fleet panels).
- Persistence is required (ticket desks and dashboards that survive restarts).
- Patterns repeat across views (forms with validation, paginated lists).
- Interaction timing and rate-limit behavior matter (rapid clicking, long-running ephemeral panels).
When CascadeUI Is Overkill¶
- Single-view bots with no shared state. A command that sends an embed and exits does not need a state store. Raw discord.py is the right choice.
- Purely message-based bots. CascadeUI is about components and views. Bots that send only text or embeds without interactive elements will not use most of the library.
- Multi-tenant plugin isolation. Reducers are not sandboxed, and middleware has full state access. Applications that need per-plugin isolation build that layer above CascadeUI.
Composition Model¶
The library is built in layers. Each row names what a layer holds and what it uses. Views and the store meet where a view subscribes to the store and dispatches into it.
| Layer | Holds | Uses |
|---|---|---|
| Patterns | Menu, Form, Wizard, Tabs, Paginated, Leaderboard, Roles (deprecated) | The view classes |
| Components | StatefulButton, StatefulSelect, the V2 builders, the wrappers |
discord.py's items, and the store for a stateful component's dispatch |
| View classes | StatefulView, StatefulLayoutView, and their persistent forms, each supplying its version's send() and layout |
_StatefulMixin, with discord.py's View or LayoutView |
_StatefulMixin |
Everything a view does in either version: access, instance limits, sending, rendering, closing, sessions, navigation | The store |
StateStore |
State, reducers, subscriptions, batching, @computed, the active-view registry |
Its middleware chain |
| Middleware | Logging, undo, persistence, and your own | A backend, for PersistenceMiddleware |
PersistenceBackend |
InMemoryBackend, SQLiteBackend, PostgresBackend, or your own |
Its database driver, or nothing for InMemoryBackend |
Each layer is replaceable:
- Patterns can be subclassed or replaced with custom implementations.
StatefulViewandStatefulLayoutViewcan be extended with new mixins or bypassed entirely, and raw discord.py views work beside CascadeUI views in the same bot.StateStoreis a singleton, but tests build fresh instances, and the module-level@computedregistry re-seeds each new store.PersistenceBackendaccepts any Protocol-conforming implementation. Swapping SQLite for Postgres, or for a backend the library does not ship, requires no changes above the backend layer.
Further Reading¶
- How CascadeUI Thinks: data flow, the state tree, sessions and navigation
- How Discord Interactions Work: the interaction lifecycle
- The Five Pillars: attribute tables, orthogonality examples
- Patterns: Menu, Form, Wizard, Tabs, Paginated, Leaderboard, Roles
- State: reducers,
subscribers, scoped state,
@computed - Persistence: backend Protocol, opt-in slots, schema migrators
- Performance: profiling, selectors that cut renders, timing settings
- Code Map: which module owns each concern, the path a click takes, the tests
- Changelog: per-release diffs
- Contributing: design philosophy, API grammar, what to discuss before a pull request