Changelog¶
All notable changes to CascadeUI are documented here. The format follows Keep a Changelog.
CascadeUI follows Semantic Versioning starting at 3.0.0. Earlier 1.x and 2.x releases were pre-stable; their entries are preserved below for historical reference but are not the supported baseline. From 4.0.0 on, the stability policy defines what is public and how a public name is retired.
[4.0.0] - 2026-12-04¶
Security¶
- A click on a control the view just removed no longer runs without its
checks.
remove_item()detaches a control at once, while discord.py routes clicks to it until the edit lands, and such a click ran the control's callback with no view: the view's checks and the control's ownowner_onlywere skipped, so a public panel's owner-only button ran for anyone who clicked it between the removal and the edit, and an ERROR was logged. The click is now dropped, or taken by the control with the samecustom_idnow in its place. A callback called directly on a control no view holds still runs, with a WARNING.
Breaking¶
Most bots meet a few of these. Buttons drop a person's second click while
their first is still running, unless the button sets allow_double_click=True.
A select pick its callback leaves unanswered is answered with the view's
current render, so a callback that only stores a pick now draws it.
on_error() runs before the click is acknowledged, so an override that
replied only through interaction.followup.send() answers first or uses
respond(). Two changes alter a result without raising: regex() matches the
whole value, and RetryConfig(max_retries=N) retries N times. Most of the rest
refuse, where the mistake is made, input that 3.14.2 accepted and then misread
or failed on later, and a value of the wrong kind raises TypeError where it
raised ValueError. The two methods deprecated in 3.14 are gone (see Removed),
and the roles pattern is deprecated (see Deprecated). The entries below are
grouped by subject.
- A user's second click on a button is dropped while their first click on
it is still running and has had no reply, edit, or modal. It asked for
what the first was already doing: an Update button clicked twice on a
one-at-a-time review screen updated the next item, one nobody had seen, or
raised an
IndexErrorpast the end of the list. The dropped click is answered with the view's current render. Another user's click runs, and so does a click after the user clicked another control or after Discord accepted the first click's reply, edit, or modal, including one the library sent after the acknowledgement (respond(),send(),refresh()). Discord accepts a reply a moment before the screen shows it, so a click sent in that moment still runs. A reply sent withinteraction.followup.send()directly is not counted, so reply throughrespond(). A select's pick always runs. For a button where every quick click counts (a counter, a stepper), passallow_double_click=TruetoStatefulButton,action_section, orbutton_row, or set it on any button; the library's page turns set it. ADynamicPersistentButtonfollows the same rule per message unless its class setsallow_double_click = True. - A select pick its callback leaves unanswered is answered with the view's
current render, in the same one request. A callback that neither rendered
nor replied (an
if values:guard on a cleared pick, a pick refused without a word) left a bare acknowledgement, and the client kept showing the pick over a screen built from the old choice. A callback that only stores a pick for a later step (pick a target, then click Fire) now sees the select go back to its placeholder: draw the pick in the callback by marking the chosen optiondefaultand callingrefresh(), asv2_battleship.pydoes. When that answer, or the render a reply throughrespond()sends first, shows the select still offering the value picked and marking none, a WARNING (once per view class) names the select and the fix (selected=for achoice_row()dropdown). The same answer reaches a pick whose callback raises (ahead ofon_error()'s reply, unless the raise cut a rebuild short) or opens a modal whose submission renders nothing. When the library acknowledged the pick first (ack_first, or a callback slower thanauto_defer_delay), the callback's change is drawn with an edit of the message instead. A pick answered throughrespond()gets the render first and the reply as a followup, one request more. So does a pick a control's ownowner_onlyor a modal's validators refuse, and one whose callback sends a panel withsend(): that panel posts as a followup, so keep the messagesend()returns, sinceinteraction.original_response()reads the picked panel. A reply made while the callback is part way through changing the panel goes out alone, and the callback's own render shows the result. A pick the view'sowner_onlyorallowed_usersrefuses gets the refusal alone, as discord.py'sinteraction_checkdoes, and a reply throughinteraction.response.send_message()still takes the answer itself. The answer leavesrefresh_degradedas it was. It needsserialize_interactions, and underauto_defer = Falsea pick on your own select stays yours to answer. on_error()runs before the click is acknowledged, as discord.py runs it. A callback or check that raised was acknowledged first, so an override that answered throughinteraction.responseraisedInteractionResponded: the person saw no error message, and the exception escaped the click. The override now runs first, so it may answer throughinteraction.responseuntil the click's timer answers,auto_defer_delayafter the click arrived; withauto_deferon, whatever it leaves unanswered is acknowledged after it returns. An answer throughinteraction.responsethat comes after that is replaced by the default error reply, with a warning namingrespond(). The override also runs in the click's turn, so withserialize_interactionson the view's next click waits for it: do slow work, such as a message to the bot owner, in a task. An override that replied throughinteraction.followup.send()alone relied on the earlier acknowledgement: answer the interaction first, or reply throughrespond(), which works either way.- A screen pushed from a panel with no owner has no owner either. A panel
posted to a channel has no owner, and the screen it pushed took whoever
clicked as its owner: with the default
owner_onlyeveryone else was refused on the public message until that person went Back, and Back left the panel itself owned by them. Navigation now keeps such a chain without an owner, as it keeps an owned chain's owner. A screen about the person who clicked names them:await self.push(MyStats, interaction, user_id=interaction.user.id). push()andpop()raise Discord's error when it refuses the new screen's contents (code 50035, such as an embed description past 4096 characters), after the current view has taken the message back, asrefresh()raises it. They returned the discarded view with a warning, so the person who clicked saw nothing happen; from a click the error now reacheson_error()and they get its reply. A push or pop made from a task of your own raises there.- A send whose context returns no message raises
RuntimeError. Acontextwhosesend()returned nothing left a registered view with no message, andsend()returnedNone, which reads as refused. Code that readsNonefromsend()as a refusal now gets the error for such a context. Adiscord.Webhookis asked for the message it posts, so it no longer returns nothing. - A reload the throttle holds back entirely returns
RenderOutcome.POSTPONED, notDEFERRED.on_load()has not run yet and runs, with the render, at the window boundary.DEFERREDfromreload()now meanson_load()ran and only its edit waits, except on an ephemeral view armed for its refresh handoff, whose reload runs noon_load()at all. Code that compares a reload toDEFERREDor"deferred", or counts every outcome outside a list as success, needsPOSTPONEDadded where it should match. - A persistent view refuses a timeout. A number passed as a persistent
view's
timeout=or set in its class body was silently replaced withNone, and one assigned toview.timeoutstarted a timeout that froze the panel for everyone until a restart. Each now raisesValueErrornaming the class;Noneand0are accepted. A panel whose stored arguments carry atimeoutrestores without it. - On a class that sets
timeoutin its body,MyView.timeoutis the property, not the number. The class-body value is now the constructor's default, so an assignment after the send reaches the view's timer. Read the timeout from an instance (view.timeout). StatefulButtonandStatefulSelectrefuse anowner_onlythat is not a bool. The gate read onlyTrue, soowner_only=1or"true"left the control open to every user with nothing raised. It now raisesTypeErrornaming the keyword when the control is built, asowner_only = 1in a view class now does when the class is defined (see the next entry).allow_double_clicktakes the same check.- A value of the wrong type raises
TypeError, notValueError. View class attributes andset_class_attribute()(owner_only = 1,instance_limit = "3",edit_timeout = "5"), theauto_defer_delayof aModaland aDynamicPersistentButton,FormField,WizardStep,RoleCategory, the page and cache sizes offrom_data(),from_cursor(), andrefresh_pages()and the totals of the last two (total=,new_total=),PaginatedRegion's page size,key, andjump_threshold,choice_row(button_threshold=),Collapsible's label and key, thelabelsoftoggle_button()andtoggle_section(),tab_overflow_policy,PersistenceMiddleware'srestore_concurrency=andprune_unreachable_after_days=,prune_unreachable(older_than_days=),alert(level=), thescopeandmessageofwith_cooldown(), thescopeofdispatch_scoped(), and a value of an enum attribute such asinstance_policyraisedValueErrorfor a value of the wrong kind, while the components andtimeoutalready raisedTypeError. A value of the right kind that is out of range or empty still raisesValueError; an emptyscoped_slottherefore raisesValueErrorwhere it raisedTypeError, and empty text given where pairs belong (key_value(""),button_row(""),tab_nav("")) raisesTypeErrorwhere it raisedValueErrorfor being empty. The messages for view class attributes are unchanged; those ofalert(),with_cooldown(), anddispatch_scoped()now name the values they take and the type given. Code catchingValueErrorfrom these needsTypeErrortoo. view.user_idandview.guild_idrefuse a value that is not an id. One assigned after the view was built was stored as given, so underowner_onlya string user id refused the owner's own clicks. It now raisesTypeErrorat the assignment, as theuser_id=andguild_id=arguments already did. AMemberor aGuildassigned there stands for its id (see Fixed).- A value a plain mixin gives a view class is checked when the class is
defined, as one in the class body is. Only the class body was checked, so
owner_only = 1orinstance_policy = "rejct"on a mixin was accepted. A mixin listed before the view base (class Panel(Defaults, StatefulLayoutView)) gives the class its values; one listed after it gives only what the library leaves unset (theme,build_ui()) andsubscribed_actions, which a view reads past the library's default. Both are checked. A pattern's own checks (tab_overflow_policy,step_indicator_label, the leaderboard's and the roles panel's attributes and hooks,kwargs_schema_version, andPaginatedRegion's) read the mixin too. Asession_class_keyon a mixin raisesValueError: it pinned nothing, since each class pins its own. - A view whose
__init__never reaches the library's raisesTypeErrorwhen it is built, naming the__init__that returns without callingsuper().__init__(). Such a view had none of the library's setup: one calling discord.py's own__init__directly failed its first click with anAttributeError(the callback never ran), and one calling neither failed at its first use. - A class that replaces one of the library's private methods with one the
library cannot call raises
TypeErrorwhen it is defined. The check covers anasync defwhere the library calls a plain method, a value where it calls a method, a method where it reads a value, a signature that takes neither the method's required arguments alone nor all of its arguments, and a plain method that cannot be called on the class where the library declares a classmethod, in the class body of a subclass (or a plain mixin) of a view, component, modal, composite, middleware, persistence backend,PersistenceManager,StateStore,EmojiGrid,DevToolsCog, or testing stub. Such a class worked until the library reached the name: a status panel's ownasync def _disarm(self, ...), a name 4.0.0 added, made every send raise from inside the library. The message names the class, the name, and the base; renaming the method is the fix. Any other replacement warns instead (seePrivateNameWarningunder Added). - Assigning
boton a view takes adiscord.ClientorNone. Every view now has thebotproperty (see Added), soself.bot = ...stores the client the library acts through and raisesTypeErrorfor anything else, as does a manualon_bind()call on aPersistentLeaderboardLayoutView, which stored whatever it was given. The property keeps its value in_bot, which the library reads as the view's client without the check, so_botis the library's on every view: a view that kept anything else under either name needs another name for it, and one that kept its bot in_botreads and assigns it throughself.botinstead. A test double passes when it is adiscord.Client:cascadeui.testing.stub_client(), or aMagicMockwith adiscord.Clientclass as itsspec(MagicMock(spec=commands.Bot)); a bareMagicMock()or aSimpleNamespaceraises. - A callable a view or pattern calls on a click is refused where it is
passed when it cannot take what it will be given (
TypeError). One on a tab, step, page, category, or field nobody had reached constructed without complaint and raised on the click that first reached it. The check covers a tab builder, a wizard step'sbuilderorvalidator, and aPaginatedLayoutViewpage given as a callable, that cannot be called with no arguments; a menu category'srebuildor a class'snav_rebuildthat cannot take the view it renders; and a validator on aFormField, a form field dict, or a modal input that cannot take(value, field, all_values). Validators passed bare instead of in a list, or as a str, are refused too, naming the field; each raised Python's own message, at Submit or when the modal input was built. An async page callable is refused, since a page is drawn synchronously:refresh_data()refuses one where it is called, and a page assigned inon_load()when it is drawn. Astaticmethodnamed in a class body is checked as the function it holds. A callable whose signature cannot be read is accepted. Modal.submit()refuses a choice value no option has. A radio group, checkbox group, or select takes its options' values ("yes", notTrue): a list of them for a select or a checkbox group, even a single-pick one, and one value for a radio group. Anything else raisesTypeErrororValueErrornaming the input and its options, as does a list that names an option twice, or names more options than the control'smax_values. Such a value was read as no answer, or stored, so a test passed against a submission Discord never sends.- An override of a hook the library runs after an event is refused when
its class is defined if it cannot take the hook's arguments (
TypeErrornaming the hook and the signature to write):on_page_changed,on_tab_switched,on_step_entered,on_step_exited,on_validation_failed,on_field_changed,on_replaced,on_session_ended,on_state_changed,on_message_delete,on_message_gone, and the composites'on_page_changedandon_toggle. The library goes on past one of these hooks that raises, so an override with the wrong signature raisedTypeErroron every event, was logged, and never ran; a view whoseon_message_deletecould not run was never torn down and kept its instance slot. Anon_validation_failed(self, step_index, error)written beforeinteractionwas added is the likeliest case. - An
async defoverride of a hook a pattern calls while it builds or draws is refused when its class is defined (TypeErrornaming the hook): every pattern'sbuild_extra_items(), the menu'sbuild_header(),build_footer(),build_category_item(),build_menu_card(),build_category_button(), and V1build_embed(), a tab view'sbuild_tab_rows(), the wizard'sbuild_progress_header(), the V1 paginator'spage_kwargs(), and the roles panel'sbuild_category_card(). Nothing awaits them, so an asyncbuild_extra_items()added nothing and logged only Python's "never awaited" warning, and the rest raised when the view was built or first drawn, two of them with anAttributeErrornaming neither the hook nor the fix. The leaderboard'sbuild_header()andbuild_footer(), which it awaits, still take either. - A
refresh_warning_secondsofNoneis refused when the class is defined. It passed the check and then made every ephemeral send raiseTypeError, so only a class that never sent an ephemeral panel worked. - A callable the store or persistence calls later is refused where it is
registered when it cannot take what it will be given (
TypeError): asubscribe()callback that cannot take(state, action)or aselectorthat cannot take(state), anon()hook that cannot take(action, state), a@cascade_reducerfunction that cannot take(action, state), a@computedselector or function that cannot take the state or the selected value, a middleware that cannot take(action, state, next_fn), a view'sstate_selectorthat cannot take the state (checked when the class is defined), and aregister_hook()callback that cannot take the hook's arguments. Each raised on every action, read, or flush that reached it: a reducer's change was logged and skipped, a middleware stopped every dispatch, and a view whose selector failed was notified on every action. The same check covers a migrator passed toregister_migrator(),register_kwargs_migrator(), ormigrators=that cannot take(backend)or(kwargs), which failed the start it ran in or every row it migrated; aPostgresBackend.set_invalidation_callback()callback that cannot take(namespace, key), whose every notification was logged as a malformed payload; and aslot_propertywhosekey=cannot take the instance, which logged one WARNING and read its default from then on. A callable whose signature cannot be read is accepted.register_hook()also refuses a name other thanon_flushandon_error(ValueError), where a misspelled one was stored and never called, andsubscribe(action_filter=)refuses a str or a mapping: a str matched action types by substring outside a batch and raised inside one. - A component callback that cannot be called is refused when the component
is built (
TypeError):callback=on aStatefulButton,StatefulSelect,ToggleButton, orModal, the callbacks the builders take (action_section,button_row,toggle_section,choice_row,cycle_button,toggle_button,confirm_section), andwith_confirmation(on_cancel=). Each was accepted and failed on the click that reached it.button_grid()'scell_factoryandaccess_slot()'sdefault_factoryare refused at the call too: the first failed inside the builder with Python's own message, the second only once a key was missing.with_confirmation()also refuses anon_cancelthat cannot take the No click's interaction, asconfirm_sectionandConfirmationButtonsalready did: it raised inside the prompt after the prompt read "Cancelled." A method called by mistake (callback=self.on_click(),builder=self.build_step()) is named wherever the library refuses one, with a Fix line saying to drop the(), and the coroutine it made is closed, so no "was never awaited" warning follows. - An action type must be a non-empty string wherever one is taken.
@cascade_reducer()andstore.on()raiseTypeErrorfor a type that is not a str andValueErrorfor"", naming the call; each registered a reducer or hook that no dispatch could reach, with nothing said.subscribe(action_filter=)and a view'ssubscribed_actionsalready refused an entry that is not a str and now refuse""too.dispatch()refused both already. @cascade_reducerreturns the decorated function unchanged, as@computeddoes. It returned the store's async wrapper, so calling a plaindefreducer by name gave back a coroutine. Code that awaits a decorated reducer drops theawaitfor a plaindef, or dispatches the action to run it the way the store does, on a copy of the state.- An
async@computedfunction is refused when it is decorated (TypeError), as an async selector already was. A read returns the value at once: the first read's coroutine could be awaited once, and the next read with the same state handed back the same coroutine, which raisedcannot reuse already awaited coroutine. A plain function that returns a coroutine raisesTypeErrorat the read, naming the value. - A
@computedfunction cannot take a name another function registered (ValueErrornaming both).store.computedholds one value per name, and the second replaced the first with nothing said: the first cog's panel showed the second cog's value, and a function namedtotal_views, or another of the inspector's names, took over the inspector's Overview. The same function decorated again, as a reloaded cog does, still replaces its registration. The inspector's own values now carry the library's prefix (cascadeui_total_views,cascadeui_total_sessions,cascadeui_application_keys,cascadeui_state_size_bytes), so a bot's owntotal_viewskeeps its name; code that read the inspector's value under the old name reads it under the new one. - A
slot_propertycannot be assigned.view.wins = 5raisesAttributeError, as assigning a read-only@propertydoes, andset_class_attribute("wins", 5)raisesValueError, as it does for a property. Either one put the value in front of the store's, and the view read it from then on whatever the store held.set_class_attribute()now refuses any descriptor, not only a property, classmethod, or staticmethod. access_slot(state, name, key)refuses a key ofNonewithTypeError, before anything is written.Nonemeant "no key", so an id that came in asNone(aguild_idin a DM) wrote beside the real entries at the slot's root, skippeddefault_factory, and every read of that entry found nothing. Leave the key out to get the whole slot.- A scoped-state id must be a Discord id.
StateStore.scope_key()and every call built on it (get_scoped(),get_scoped_from(),set_scoped(),merge_scoped(),iter_scoped()'s filters,dispatch_scoped(), andcheck_instance_available()) raiseTypeErrorfor an id that is not anint, a string of digits, or an object with anint.idsuch as a Member. A name,True, or42.0built a key no other call reached ("user:42.0"beside"user:42"):iter_scoped()skipped it andcheck_instance_available()answered that a panel could open. A string of digits stands for its number, so"042"and42read one slice; data written under a zero-padded id before this release stays under that key. merge_scoped()andSCOPED_UPDATEraise for an unknown scope or a missing id, with the messageget_scoped()gives. They returned the state unchanged and said nothing, so a typo in a reducer wrote nothing; inside a reducer the store logs the error at ERROR, naming the action.iter_scoped()checks its arguments when it is called. An unknown scope raisesValueErrorat the call rather than when the result is looped over, and a filter the scope's key does not hold (guild_id=for"user", or a misspelled name) raisesTypeError; it was ignored, and every entry was yielded.set_scoped()takes a dict. Any other value raisesTypeError; it was stored, and every laterdispatch_scoped()to the key failed in the reducer.- A session's row has no
historylist.replace()added an entry to it and nothing read it, so a long-lived session grew it with every replace.NAVIGATION_REPLACEstill goes out to listeners and changes no state, and its reducer,cascadeui.state.reducers.reduce_navigation_replace, is gone. undo()andredo()raiseRuntimeErrorwhenUndoMiddlewareis not installed, namingsetup_middleware(UndoMiddleware()). A view withenable_undo = Truerecorded nothing without it, and its Undo button did nothing and logged nothing.- A middleware that returns without passing on one of the library's own
records, or passes it on under another type, raises
RuntimeError, naming the middleware, the action, and the fix:SESSION_CREATED,VIEW_CREATED,VIEW_UPDATED,VIEW_DESTROYED,PERSISTENT_VIEW_REGISTERED,PERSISTENT_VIEW_UNREGISTERED,REGISTRY_PRUNED, andINSPECTOR_PURGED_STALE. A rate limiter that stopped every second action from a view stopped these too, with nothing said: a closed view kept its row and its instance slot for good, a sent view had no row and no undo history, and a panel missing from the registry was not restored after a restart. Registering a view in a send raises the error; the steps a send takes once Discord has answered, and a close, log it at ERROR and go on, as they do when a middleware raises (a close keeps the view registered). Stopping the bot's own actions works as before. - After a bot closes,
setup_middleware()replaces each middleware it installed before with the new one of its kind. A middleware's kind is its class, or for a function its code, so a closure a factory builds again is the same kind; the first new one of a kind takes the first one's place, the second the second's. While one bot runs, a second of a kind is added beside the first, so two cogs that each install their own both run. Before, a new instance of an installed class was set aside at DEBUG, so a call passing two instances of one class ran only the first, and a function middleware a restart'ssetup_hookbuilt again ran twice on every action. A middleware that keeps state of its own starts fresh when a call passes a new instance; pass the same object to keep it and its place.UndoMiddleware,PersistenceMiddleware, andLoggingMiddlewareare one per store and always take the installed one's place, soLoggingMiddleware(level="DEBUG")aftersetup_logging()logs at DEBUG, where it kept INFO;PersistenceMiddlewarestill takes the new instance's bot. has_middleware()'s parameter ismiddleware, since it takes a function as well as a class. A call passingmiddleware_cls=by keyword raisesTypeError; a call passing it by position works as before.- A persistent panel's
send()raises when a button itsseed_initial_state()builds has nocustom_id. The check ran before the hook, so the button went out with an id generated anew in each process and stopped answering after a restart. Give it acustom_id, as one built in__init__oron_load()already needs. - A schema migrator that would never run is refused where it is
registered. The migration walks only
cascadeui_persistent_viewsandcascadeui_application_slots, one step at a time up to each table's version in the release, and the library registers every step it takes. A migrator for another table, or from a version outside that range, was accepted and never ran, as were both examples in the Migrations guide.@register_migratornow raisesValueErrornaming why, and so doesPersistenceMiddleware(migrators=...)for such a step, a step the library already takes (which it kept and logged a WARNING for), and a key that is not a(table, from_version)pair or a non-empty"schema"or"kwargs"value that is not a dict (TypeError). A change to what a panel stores goes throughregister_kwargs_migrator(), which, withmigrators={"kwargs": ...}, now refuses a key no saved row looks up: afrom_versionthat is not anintof 1 or more, or a class name that is not a non-emptystr. Such a migrator was accepted and never ran, and the next start logged that no migrator was registered. register_slot_policy()refuses a saved slot withttl_dayswhen the backend cannot expire rows.ApplicationPersistence(slots=...)already raisedPersistenceConfigErrorfor such a policy on a backend withoutCapability.TTL_INDEX; registered later, it was accepted, every start loaded the row back after it expired, and the daily sweep calledrow_delete_where_lt(), which such a backend need not define. It now raises the same error before recording anything.- A
DynamicPersistentButtonthat discord.py would route wrong is refused in your own code. discord.py checks a button's id against its template only at the start, then sends a click to every class whose template matches the whole id. A button built with an id its template matches only at the start never answered a click; the build now raisesValueError, as does assigning such an id tocustom_id. A button whose id anotherDynamicPersistentButtonclass's template also matches ran both classes' handlers on every click; the build raisesValueErrornaming both, and so does a roles panel built while a class matchingroles:ids is defined. Neither check runs on a buttonfrom_custom_id()builds for a click, so buttons already posted keep working. A class using the defaultfrom_custom_id()whose template has a group__init__does not take, or whose__init__needs a keyword no group supplies, raisesTypeErrorwhen it is defined: every click on it failed, with the error logged. - A select no pick can satisfy is refused before the send or edit.
discord.py stores
min_valuesandmax_valuesunchecked, so a select whose minimum is above its maximum, or above the options it offers, reached Discord. Every send, refresh, and navigation edit now raisesValueErrornaming the select, for V1 and V2 views and withvalidate_placement = False, and so does a user, role, channel, or mentionable select whosedefault_valuesnumber fewer than itsmin_values.StatefulSelect,Dropdown,RoleSelect,ChannelSelect,UserSelect, andMentionableSelectcheck their bounds when they are built:TypeErrorfor one that is not an int (a bool included),ValueErrorfor one out of range or a minimum above the maximum. The modal inputs do the same when built: aTextInputwhosemin_lengthis above itsmax_length, and aCheckboxGrouporFileUploadwhosemin_valuesis above itsmax_values, or above aCheckboxGroup's options, raiseValueError. - Arguments that were accepted and then misread are refused where they are
passed. A str given as a paginated view's
pages=, aPaginatedRegion'sitems,cycle_button(values=)orlabels=, orToggleGroup(options=)made one page, item, value, label, or toggle per character; each now raisesTypeError(a str given tofrom_data()orrefresh_data()is still paged in slices). Anemoji_gridaxis label given as a str other than"alpha"or"numeric"labelled one row or column per character, so a mistyped"Alpha"drewA,l,p; it raisesValueError, and custom labels go in a list.emoji_gridraisesTypeErrorforrowsorcolsgiven as a bool, asbutton_griddoes (Truedrew one row), and names the axis and the label when a custom label is not a str, where the error came fromstr.joinand named neither.ToggleGroupraisesValueErrorfor no options or adefaultthat is not one of them (no toggle showed as chosen) andTypeErrorfor an option that is not a str (AttributeErrorbefore).PaginationControlsrefuses a page count or page that is not an int (a float showed "Page 1/2.5"), V1ProgressBara total, width, or glyph its render cannot use (it failed at render, or drew "50" for the fill, and a NaN or a width of zero or less drew an empty bar),with_cooldown()asecondsthat is not a non-negative number (a str raised at every click, and a negative or NaN one held nothing back), and every builder takingcustom_id, andModal, one that is not a str (confirm_sectionshipped "5_confirm", and a modal opened while its submission was discarded as unknown);Modalalso refuses one over 100 characters, as the builders did. - A single-select
choice_rowrefuses a callableselectedthat is no option's value (TypeError). It selected nothing and said nothing; a callable selection is read withmulti=True(see Added). A class is still taken as a value. - A wizard, tab view, or menu given nothing to show raises when it is
built, naming
steps=,tabs=, orcategories=(TypeErrorwhen none is passed or the value is the wrong type,""and0included;ValueErrorfor an empty one). A wizard with no steps sent a lone Finish button, a menu with no categories sent its Exit button alone, and a tab view with no tabs raisedIndexErrorfrom inside its first send. Asteps,schema,tabs, orcategoriesset in the class body, which none of them reads, gets a message saying to pass it when the view is built. - A tab view refuses a
build_tab_rows()that leaves a tab without a button or lays out a button that is not a tab (ValueErrornaming the hook and the tab or button, when the view is built). A tab left out of every row was sent with no button to open it, and another button placed in a tab row was sent beside the tabs. A button of the view's own belongs inbuild_extra_items(). - A V1
PaginatedViewpage that cannot be shown raisesTypeErrorwhen the view is built, naming the page, andrefresh_data()refuses one and keeps the pages it had. A page is anEmbed, a str, or a dict givingembed,embeds, orcontent. Any other page, aNonepage (a formatter that returns nothing makes one), a dict giving none of the three, and a dict giving bothembedandembedsshowed nothing or part of the page, and the previous page's content stayed on screen under the new page number. Anembedthat is not anEmbed,embedsthat is not a list or tuple of them, more than ten embeds, and text past Discord's 2000-character cap (bothValueError) are refused too; discord.py read them only when the page was shown, and its errors (Discord's 400, for the text) named no page. A dict's other keys are left alone. A subclass with a page type of its own overridespage_kwargs(), and its pages are not checked. Afrom_cursor()formatter that returnsNoneraisesTypeErrorwhen its page loads, on both versions: the page was taken as not loaded yet, so it showed nothing (V2: "Loading...") and was fetched again on every render. - A
PaginatedLayoutViewpage that cannot be drawn raisesTypeErrornaming its place inpages. A dict (a V1 page), a number, a generator (read once, where a page is drawn each time it is shown), or a list holding something that is neither a component nor text is refused when the view is built; each constructed and then raised discord.py'sexpected Item not tuple, naming no page, on the page turn that reached it. Text past the 4000 characters one text display holds, as a page or as an entry in a page's list, raisesValueErrornaming that place; Discord refused it on the page turn. A page callable that returnsNoneraises when its page is drawn. Afrom_data()orrefresh_data()formatter that returnsNoneraises naming the page, as afrom_cursor()formatter's does: on V2 the page showed "Loading..." with nothing to replace it. A page that does not fit Discord's 40 components beside its buttons and thebuild_extra_items()items raisesValueErrornaming the page and both counts when the view is built and inrefresh_data(); it raised on the page turn that reached it. - A form field given as a dict takes the checks a
FormFielddoes. A dict with noidwas accepted, and two such fields both stored their values underNone, one overwriting the other. A missingid, or anid,label, ortypethat is not text, now raisesTypeErrornaming the field's place infields, and an emptyidor an unknowntyperaisesValueError. A dict with nolabeltakes itsid. A select field'soptionsthat are not a list of dicts, in either form, raisedAttributeErrornaming nothing; they raiseTypeErrornaming the field and the option. - A key a letter or two off one the library reads raises
TypeErrorin a wizard step or form field dict, a form select option, aDropdown,CheckboxGroup, orRadioGroupoption, a menu category, a theme's styles, or a V1 page dict, naming the key it was probably meant to be ("validate"for"validator","requried"for"required","descripton"for"description","accent_color"for"accent_colour","contnet"for"content"). The key was ignored: the step ran no check, the field was optional, an option stored its label as its value, the category showed no description, cards took the default accent, and the page showed without its text.WizardStepandFormFieldalready refused the same mistake. A key of your own, further from the read keys, is kept, and so is a theme key that extends a read one ("primary_color_dark"). - A form refuses a field it would store or show wrong. Two fields
sharing an
idkept one value between them, the second overwriting the first; they now raiseValueErrornaming both places infields. A select option with no textlabel, or avaluethat is not text, raisesTypeError(ValueErrorwhen empty): Discord refused the first when the form was sent, and returns a pick as text, so a number never matched. Adefaultthe field could never hold showed as set, passedrequired, and reachedon_submit: a select default naming no option, a boolean default other thanTrueorFalse, and a typed default the field refuses as input ("abc"on an integer field) now raise, naming the field. A typed default is stored as typed input is ("7"becomes7, adatetime.dateits ISO text), and a multi-select default of one value becomes a one-item list. - A form's
set_field_error()refuses an id the form does not have. The error showed nowhere and still kept the form open after Submit; it now raisesValueErrornaming the form's field ids. A message that is not a str raisesTypeErrorbefore anything is stored: it was stored, and that render and every later one raised Python's own error until the field's errors were cleared. regex()matches the whole value. It matched from the start only, soregex(r"\d+")passed"12abc". A pattern written to check how a value begins now refuses every value that goes on: end it with.*, as inregex(r"https?://.*"), and give a pattern of lookaheads alone something to match (r"(?=.*\d).+"). A bytes pattern raisesTypeErrorwhen the validator is built.- The validator factories check their arguments when they are built.
min_lengthandmax_lengthtake an int of 0 or more, andmin_valueandmax_valuea finite number, each raisingTypeErrororValueErrornaming the factory.min_length("3")raised from inside the submission, andmin_value("13")refused every value as "Must be a number >= 13".choices()refuses a str (choices("abc")accepted"ab") and reads its values once, so a generator no longer runs out after the first check. validate_fields()refuses a field with no"id", raisingValueErrornaming its position and label. It skipped the field, so a required field whose key was mistyped went unchecked.- Pairs that repeat a key are refused where the key must name one entry.
Given as
(key, value)pairs, the second replaced the first, so a tab or a theme style went missing with nothing raised. Thetabs=ofTabViewandTabLayoutViewandTheme(styles=)now raiseValueErrornaming the key, and so does atab_navactivenaming a label two tabs share.button_row,tab_nav, andkey_valuekeep every pair (see Fixed), aschoice_rowalways has. Themechecks its name, its styles, and its separator spacing. The name must be a non-empty str:Theme({...})with the name left out built a theme of default colours named by the mapping, andregister_theme()then failed with "cannot use 'dict' as a dict key". Styles that are not a mapping or pairs raise even when falsy (0and""were read as no styles), andseparator_spacingmust be"small"or"large":"Large"rendered small. The colour errors name the theme.set_default_theme()raises for a name no theme has, naming the registered ones, and takes aThemetoo, registering it. It returnedFalseand kept the old default, for a typo and for aThemepassed by mistake alike; it still returnsTrue. Its parameter istheme, so a call passingname=by keyword raisesTypeError.register_theme()refuses anything but aThemewithTypeError, where a name raisedAttributeError.- Two role categories of one panel whose names give the same slug are
refused (
"Colors"and"colors"), withValueErrorwhen the class is defined. A role button finds its category by slug, so every click on the first category's buttons reached the second and was refused. Akeyon one keeps both names (see Added). - A roles panel with no categories raises
ValueErrorwhen built. It posted its title alone, with nothing to click. - A roles panel's
on_role_*hooks written as plain methods are refused when the class is defined (TypeError, naming the hook). A role button has no panel instance, so the library calls these hooks on the class, and such a hook changed the member's role and then raised. The fiveformat_*hooks are refused the same way while the class keeps the library'sbuild_category_card(); written as plain methods, they already failed when the panel was built. - A role button with neither a label nor an emoji is refused when its card
is built (
ValueError, naming the role and category), and aRoleCategorydescription that is not text raisesTypeError. The button showed the category's slug instead, and the description was sent as given. - A misspelled
setup_logging()preset raisesValueError, naming the presets, as a misspelledlevel=already did.colors="oceann"ortemplate="minimall"drew every line with the default colours or layout. Both are checked before the earlier logging setup is taken down, so a refused call leaves it in place. A value that is neither a preset name nor aColorSchemeorFormatTemplateraisesTypeError, andColoredStreamFormatterandFileFormattercheck theirs the same way. Amax_filesthat is not an int raisesTypeErrorbefore anything is taken down too:Truekept one file, and a string orNoneraised Python's ownTypeErroronce the earlier setup was gone, leaving no logging at all. RetryConfig(max_retries=N)retries N times, sowith_retrymakes up to N + 1 calls. It made N calls, one retry fewer than the name says, and withmax_retries=0it never called the function at all, raisingRuntimeError("Unexpected error in retry logic"). To keep the old count, lowermax_retriesby one.RetryConfigchecks its arguments when it is built. It raisesTypeErrorfor a count that is not an int, a wait that is not a number (a bool is neither), or anything inexceptions_to_retrythat is not anExceptionsubclass (retryingCancelledErrorwould swallow a cancel). It raisesValueErrorfor a negative count, a negative, infinite, or NaN wait, or an emptyexceptions_to_retry. A NaN or infinite wait reachedasyncio.sleep(), a string inexceptions_to_retryraised only once the function failed, and an empty tuple retried nothing. One class or a list of them is kept as a tuple.with_error_boundary()andwith_retry()refuse an argument of the wrong type withTypeError: a name that is not a str, a config that is not aRetryConfig.with_error_boundary(5)used5as its log label, andwith_retry(5)raisedAttributeErrorat the first call. Either decorator written without its parentheses is refused where it is applied, with the fix; the decorated function used to fail when called, withdecorator() missing 1 required positional argument. Either one applied to something that cannot be called (a function called too soon,with_retry()(fetch())) is refused there too:with_retry()retried the call that could never work, about seven seconds of WARNINGs under the default config, before raising.safe_execute()raisesTypeErrorfor something it cannot await, such as a coroutine function passed without calling it (safe_execute(fetch)), naming the fix. It logged an error and returned the fallback, so the call never ran and the caller could not tell it from a call that failed.slugify()andis_emoji()raiseTypeErrorfor a value that is not text, naming the function. A number raisedAttributeErrorfrom inside the helper.is_emoji(None)still reads as empty and returnsFalse.
Added¶
- A stability policy for 4.x. The new Stability Policy page defines which names are public, what minor and patch releases may change, and how a public name is deprecated before it is removed.
PrivateNameWarning, issued when a class defines a name that starts with an underscore and replaces one its CascadeUI or discord.py base uses privately, in a shape the library could still call. Any 4.x release can change such a name, so the clash shows at import rather than on a click. A suite that replaces one on purpose filters the category. A discord.py name always warns, and one replaced in a shape discord.py cannot call (anasync defwhere it does not await) is named as not working with the discord.py installed.get_files()supplies the files a view'sattachment://references name. The library calls it on every send and on every edit that ships the view:refresh(),reload(), a renderrefresh_cooldown_msheld back, a push or pop, the final edit of a timeout orexit(). An edit uploads only when a reference is new to the message or a file's contents changed. In a V2 panel the files it returns that the panel does not show go up too, while the request has room under Discord's ten, so a paged panel's turns upload nothing. Only the code callingsend()orrefresh()could pass files before, so an image drawn inon_load()could not reach the edit areload()made. An edit now warns, as a send does, when it leaves a reference without a file: on any view when arefresh(attachments=[...])list leaves it out, and on a view withget_files()when the message was never given that file.v2_attachments.py's/attach_swapuses it.respond()andrespond_safe()return the message the reply posted, orNonewhen Discord returned none, so a reply can be edited or deleted later. So doModal.respond()andDynamicPersistentButton.respond().interaction.original_response()reads whatever answered the interaction first, which after a deferral is the panel itself.- Every view has a
botproperty, thediscord.Clientit was given: one assigned before or aftersuper().__init__(), a leaderboard'sbot=, or, on a persistent view, the client the library binds at every send and restore beforeon_bind()runs, so anon_bind()override no longer needs to store the bot itself. It was the leaderboard's alone. It isNoneuntil the view is given a client, on every class. - A listened-for action type that looks misspelled logs a WARNING naming
the type it is close to, or the one it matches but for case. It applies to
a view's
subscribed_actions, asubscribe()filter, andstore.on(), for a type no reducer or hook handles, that is not the library's own, and that nothing has dispatched. A listener whose type is never dispatched hears nothing, and nothing said so:subscribed_actions = {"COUNT_ADED"}left a panel that never redrew, andstore.on("vote_cast", ...)never fired for a customVOTE_CAST(only the library's own actions have lower-case names). store.computedis a read-only mapping:get(),keys(),items(),len(), and iteration over the names, beside[]andin.get()andinlook the name up without computing, so aKeyErrorraised inside a compute function reaches the caller instead of reading as a missing name.dispatch_scoped()takes a function of the slice's current value.dispatch_scoped(lambda current: {"count": current.get("count", 0) + 1})runs the function inside the reducer, so a value computed from the current one counts every write before it. Read first and written after an await, two panels clicked at once counted one click.dispatch_scoped_as()andmerge_scoped()take the same; the function gets a copy of the value, and anasyncfunction or one that cannot take the value raisesTypeErrorat the call. The hello world, Battleship, and Tic-Tac-Toe examples use it.PersistenceManager.reattach_removed_messagesnames the message each removed registration was on. It maps each key intotal_reattach_summary["removed"]to themessage_idandchannel_idof the row the reattach pass verified and deleted, the same mapREGISTRY_PRUNEDcarries inmessages. Code that clears its own records after startup can check a key reused across posts against the message its record stores, so a newer post under the key is not cleared for an older one.prune_unreachable()returns the same map for the rows it prunes, under a newmessageskey; code comparing its whole result for equality needs the key.PostgresBackend(listener_dsn=...)gives the listening connection a connection string of its own. Behind PgBouncer in transaction mode the writes work and the notifications behind the invalidation callback and the read-back of other processes' saved slots never arrive, sinceLISTENneeds a session of its own;listener_dsnpoints that one connection straight at PostgreSQL. A backend persistence saves slots to, or one with a callback set, sends itself one test notification when it opens and logs a WARNING naminglistener_dsn=when it does not come back within two seconds.- The pattern hooks are public:
build_extra_items(),build_category_item(),build_category_button(),build_tab_rows(),build_progress_header(),freeze_components(), the V1 paginator'spage_kwargs(page), and the menu'sbuild_menu_card(items), which wraps the category rows in one card. The guides have taught most of them under private names. WizardView,FormView, andFormLayoutViewtakebuild_extra_items()like the other patterns, for a control beside the pattern's own (a Help button, a link). A form had no such hook, andFormLayoutViewrebuilds its tree on every field change, so a control a subclass added in__init__was gone after the first one.v2_form.pyadds a Cancel button with it.nav_inside_containerandnav_divideronWizardLayoutView, as onPaginatedLayoutView: Back, the step counter, and Next go inside the step's card, with a divider above them undernav_divider. Items frombuild_extra_items()and the Exit button stay below the card.fields_in_modalonFormViewandFormLayoutViewanswers every field in the Edit modal: a text box for typed fields, a radio group for aselectof 2 to 10 options, a checkbox group for amulti_selectof up to 10 (a dropdown past either), and a Yes/No choice for aboolean, which an optional field may leave blank, so a question left alone stays unanswered as it does on the panel. The panel lists the answers with one Edit and one Submit button. A form with more than five fields, all a modal holds, two fields sharing a label, or a dropdown past 25 options raisesValueErrorwhen built.- A wizard has
answers, a dict for what its steps collect, carried with the current step acrosspop()as a form'svaluesare.pop()rebuilds the wizard, so answers kept on the instance were gone after Back from a help screen while the step came back. A dict the subclass assigns toanswersbeforesuper().__init__()is kept. - A menu's
on_category_selected()can keep the menu on screen by returningFalse. The category does not open, and the click is acknowledged unless the hook replied throughrespond()to say why. Raising was the only way to refuse a category, and the person then goton_error()'s reply instead of the hook's own. Any other return,Noneincluded, opens the category as before. - A paginator's
jump_threshold = Nonenever shows the first, last, and go-to buttons, onPaginatedView,PaginatedLayoutView, andPaginatedRegion. A large number only moved the point where they appeared, andNoneon a paginated view passed the class check and then raisedTypeErrorat its first render. LeaderboardLayoutView.build_subtitle(page)sets the line above the ranked rows, per page.None(the default) keeps the H3 heading built fromsubtitle, or a gap when it is unset. A string renders as given ("-# Updated hourly"), and""renders no line and no gap. Any other return raisesTypeErrornaming the hook.v2_leaderboard.pyuses"".LeaderboardLayoutView.banner_descriptiongives the banner alt text, as a class attribute or thebanner_description=keyword.None(the default) uses adiscord.Filebanner's owndescription, which a persistent board saves with its row. Text over 1024 characters, or a value that is not text, raises when the class is defined or the board is built.button_rowandtab_navtakeRowButtonentries, and achoice_rowChoicetakes akey. ARowButtonsets its own emoji,disabled,owner_only, andkey, and inbutton_rowits style (a tab's style still followsactive, andtab_navrefuses one). The key builds thecustom_id({custom_id}_{key}), and aChoice.keyis also its dropdown option's value. In a persistent view, which keeps a row's ids across restarts, a keyed entry keeps its id when another is removed or the row is reordered; numbered by position, the next entry took the removed one's id, and a click or pick on a copy of the message drawn before the change reached the wrong one. The mapping forms still number by position. ARowButtonwith no label shows its emoji alone, andtab_nav'sactivenames a tab by its key or its label.RoleSelect,ChannelSelect,UserSelect,MentionableSelect, andaction_section()takeowner_only, asStatefulButtonandStatefulSelectdo, so one of them on a panel open to everyone can be kept for its owner. The four selects refused the keyword, andaction_section()had no way to pass it on.- A multi-select
choice_rowtakesselectedas a callable (selected=lambda: self.picked), read at build and again at every toggle, so a toggle merges into the selection the host holds. A class is not read this way, so anEnumclass still stands for its members. Before, a host that renders through state handedon_selecta selection missing the toggle whenever a backgroundreload()held its render back. - A multi-select
choice_rowtakesmin_values, the fewest picks it accepts. The dropdown passes it to Discord, and the buttons disable an active option the selection cannot lose. A pick or toggle that would leave fewer values anyway (from a copy of the message drawn before the minimum changed, behind another toggle, or a dropdown pick of options sharing a value) runs nothing and is answered with the view's current render. A minimum above the number of distinct option values raisesValueError. cycle_buttontakesselected, the value the button shows when it is built, aschoice_rowtakesselectedandtoggle_buttontakesactive. A view that rebuilds the button passes the value it holds, where it had to pass that value's position throughstart=, and a rebuild that passed neither went back to the first value. Aselectedthat is not one of the values raisesValueError.EmojiGrid.fill_rect()takes a flat cell index for either corner, asgrid[key] = valuedoes. It took only(row, col)tuples, and an index failed with "cannot unpack non-iterable int object".PaginationControlsandConfirmationButtonstakecustom_id, the base of their buttons' ids, so aPersistentViewcan carry them. It refused both, since their buttons had only generated ids and neither class took one.MAX_MEDIA_DESCRIPTION_CHARACTERS, exported from the package root, is Discord's cap on the alt text of a thumbnail or gallery item (1024), the number the placement check refuses past. discord.py's docstrings give 256.- A
RoleCategorytakeskey, the part of its buttons' ids that names the category. Made from the name, it changed with the name, so renaming a category left every button on a panel already posted answering that the panel was out of date until it was posted again. A key keeps the ids whatever the name says, and lets two names that make the same id ("Games!"and"games") share a panel. It holds lowercase letters, digits,_, and-. A category whose button ids would run past Discord's 100 characters is refused when it is built, naming how long a key may be; it was refused only when the panel was sent. - A
RoleCategorytakes its roles as(label, role_id)pairs or any mapping, asTheme(styles=)and the tab views take theirs, and draws its buttons in the order given. It took only adict: a list of pairs or aUserDictraisedTypeError. Pairs that repeat a label raiseValueErrornaming it, and the category keeps its own copy, so a later change to the caller's dict no longer reaches a panel already defined. cascadeui.testing.stub_interaction()keeps each send's keywords insends, besidereplies, so a test can read the files, view, orephemerala reply carried, and each acknowledgement's indefers.cascadeui.testing.StubMessageandstub_message(). Each reply through the stub posts aStubMessage, adiscord.Messagethat records every edit reaching it, so a view sent through the stub is sent as in production and its later renders are recorded on its message.stub_message()gives one to a view built without a send.cascadeui.testing.flush_notifications()waits for the state notifications other views are running in the background, so a test that dispatches from one view can check what another view did.cascadeui.testing.build_as_restored()builds a persistent panel the way a restart's restore builds it, with no Discord connection: the restore's own draw frombuild_ui()and custom_id check, thenon_bind(), in its order, so a test reads the tree a restarted panel routes clicks to.cascadeui.testing.stub_interaction()can answer a hybrid command'sContext. It has a real interaction'sexpires_atandis_expired(), and reads discord.py'sMISSINGas a keyword left out. Acommands.Contextgiven one asinteraction=then sends through it, as a hybrid command does when run as a slash command.- The documentation is rewritten and reorganized. It has Learn pages
(installation to a first panel, and a page for readers coming from
discord.py), a Guide with diagrams and animations of each part, How-to
recipes, the Reference, and a Contribute section. New reference pages cover
the utilities and the library's errors, and the site carries this changelog.
The grids example adds
/daily_chest, a pick board whose cells open on click. A new example,v2_player.py, is a music player card its own timer redraws.
Changed¶
- A
StatefulViewsent or navigated to with no content shows what itsbuild_ui()returns.await view.send()posted a V1 view's controls over an empty body while every redraw took its embed frombuild_ui(); it now sends that dict'scontent,embed, andembeds, ornav_rebuild's whenbuild_ui()gives none, as the V1 patterns already send their own render. The dict'sallowed_mentionsgo with its content, as on every redraw, unlesssend()is given its own. A keyrefresh()would refuse in thebuild_ui()dict raises at the send, where it was dropped until the first redraw raised on it. A push or pop onto a V1 view with nonav_rebuildedits with itsbuild_ui()dict, where the message kept the previous screen's embed. Text passed tosend()shows above thebuild_ui()embed, and anembed=orembeds=passed to it takes the place of that dict's embeds; only a send given none of them asksnav_rebuild, and one given both asks neither hook. - A V1 pattern sent with
content=shows its own render under the text.PaginatedView,TabView,WizardView,FormView, andMenuViewsent their page, tab, step, form, or hub card only whensend()was given none ofcontent,embed, andembeds, sosend(content="Results:")posted the text alone until a click redrew the panel. The text now goes out with the view's embed; anembed=orembeds=passed tosend()still takes the place of the view's, andembeds=[]sends the text alone. A paginator's later pages show that text again whenever a page sets none of its own. - A
StatefulLayoutViewthat nothing has drawn yet is drawn from itsbuild_ui(). A view whose__init__andon_load()never calledbuild_ui()was refused atsend()as having no top-level components, with a Fix line telling the developer to makebuild_ui()add one. The send now runs it afteron_load()andseed_initial_state(), so it draws from what the seed wrote, and so do a push or pop onto such a view and the restore of such a persistent panel, which otherwise came back with nothing for its clicks to reach. A view that draws itself first is not drawn again, and one with nobuild_ui()is still refused. - The Continue button brings the panel back in place. A click on it puts
back the panel the button replaced, runs
on_load()and the state render, and answers the click with the redraw: the same view on the same message, keeping its navigation, session, participants, attached views, and every attribute, with fifteen more minutes from the click. It built a new view from the constructor's arguments, posted it as a new message, and deleted the old one, so anything set on the view after it was built was lost.get_nav_state()andrestore_nav_state()now servepop()alone: the Continue read them to carry a selection to the new view, and a view that wrote them for the Continue keeps its place as attributes, which the Continue keeps. A resume that fails keeps the Continue button, so another click tries again, andon_reopen_failure()replies privately withreopen_failure_message, whose default now reads "Could not refresh this view. Try again, or reopen it from the original command." It no longer closes the panel or sendssession_ended_message. - The Continue button appears 13.5 minutes after the panel was last used, not after its send. A click answered by updating the panel, or a modal submitted from it, gives the panel fifteen more minutes, so a panel in use is never replaced. A reply does not count, since it does not touch the panel. A panel that declines the button and has a timeout is timed out 90 seconds before its newest interaction runs out, when its own timeout would come later, so the close still disables its controls on screen.
- An
instance_limitunderinstance_scope = "user_guild", the default, applies in DMs. A person's DMs count as one place, so a second panel there is refused or replaces the first, as in a server. It counted nothing outside a server before, andcheck_instance_available()agrees with the send. A"guild"limit still has nothing to count in a DM, and the send logs a warning once per class naming@commands.guild_only(). - A deleted message no longer costs a check of every live view. The cleanup that closes the views on a deleted message walked every live view for each delete Discord sent, and most deletes are chat messages no panel is on: 2 to 3 ms per delete at 10,000 live views. Views are now found by the message they are on, so a single or bulk delete costs the same at any number of views. A deleted channel or thread still checks every view.
- Log records from the view classes name the module that writes them.
The
cascadeui.views.baselogger is split into one per module (cascadeui.views._refresh,cascadeui.views._closing, and so on). A level or filter set oncascadeui.views.basenow reaches only the construction code; set it oncascadeui.viewsto cover them all. - The auto-defer log lines for a click name the control as well as the
view. A line reads
Auto-defer backstop acked for FleetPanel (FleetPanel.place_ship) after ..., so on a view with several controls it points at the slow one. The name is the handler the click ran, else the control's label, placeholder, orcustom_id. The same name appears when the acknowledgement the library sends after a callback fails, including the one aToggleButtonwith no callback sends itself, and when the answer to a click on a control the view no longer holds fails. Awith_confirmationprompt's line names the button it wraps. - The error a state render logs names the view's class. A render that
raised on a task of its own logged
Error notifying subscriber 163828c1-..., the view's id alone; the line now readsError notifying subscriber 163828c1-... (Scoreboard): .... - The inspector's Performance tab shows the bot's own clicks. It and
Export Report left out every
COMPONENT_INTERACTIONdispatch, which everyStatefulButtonclick makes, to hide the inspector's own; they now leave out only the inspector's, read from asourcefield each dispatch and subscriber sample carries. A subscriber reads as its view's class and the start of its id (FleetPanel f3f5d7f0) rather than the id alone, both in the tab and in the export, and the Dispatch card has a Hooks row, as the export did. /cascadeui persistentlists the bot's own persistent classes and counts the library's after them, where it listed the library's four on every bot. With none of the bot's own, it says so.dispatch()raises its exceptions without logging them first. It logged each at ERROR with a traceback before raising, so a caller that caught one and handled it (a refused action type, a dispatch refused inside a reducer, a middleware's own error) still left an error in the log. One nobody catches is reported where it ends up, as any exception is: a click'son_error(), for one.- A
subscribe()selector's first value is taken when subscribing. The callback runs only once the selected value changes from it; the first matching action used to call it even with nothing changed. A selector that raises while subscribing is reported at the next dispatch, as before. A view still redraws on its first notification after its send. - Subscribers a selector skips are counted on one DEBUG line per action. The store logged a line for each one, so with 1,000 listening panels every write cost 1,000 log calls, and at DEBUG it wrote 1,000 records (a write took 15.9 ms at DEBUG against 2.3 ms). The line naming how many subscribers were notified now ends with how many were skipped, and counts the view that dispatched.
- An undo or redo is heard by the view whose history it is and by the
subscribers that hear an action it takes back. Every subscriber heard
every UNDO and REDO, whatever its filter, so a view with no
state_selectorrebuilt on each undo anywhere in the bot: 1,000 panels in other servers cost 1,000 rebuilds for one undo. A view that never heard an action does not hear it undone; one that lists the action does, in a batch too. - The action a middleware passes on is the action. Its type picks the
reducer, and subscribers, hooks, undo, persistence, and
store.historyall get it. The reducer was chosen from the dispatched type and everything after it got the dispatched action, so a clamped payload reached the reducer alone and a renamed type ran no reducer. An action a middleware builds with only atypekeeps the dispatch'ssourceandtimestamp, and itspayloadis{}; something that is not a dict with a strtype, ornext_fn(state, action)with the arguments swapped, raisesTypeErrornaming the middleware. A stopped action stays in history as it was dispatched. has_middleware()takes a function or a method, found by its code, so a closure a factory builds again is found too. Afunctools.partialcounts as the function it wraps, on either side. It raisedisinstance()'s ownTypeError.- A V1 view with no room for a component names the view and its rows.
discord.py's
could not find open space for item,item would not fit at row N, and, for a 26th component,maximum number of children exceededare re-raised fromadd_item()as aValueErrornaming the view, the component, and how many of five slots each row uses, the way a V2 view already reports the 40-component cap. Code matching discord.py's wording needs the new message. - The 40-component refusal suggests only the trims the tree offers:
folding adjacent text, dropping a divider, flattening a Section, using
fewer rows of buttons or selects, or compacting a
PaginatedRegionpager, each only where the tree has one. Fewer rows comes first when the item that did not fit is itself a row, as in a grid. A tab view is told to pass fewertabs=, which is how its tab rows are trimmed. It suggested the same list every time, so a tab view with too many tabs was told to compact a pager it did not have. When the items frombuild_extra_items()do not fit, on the hook's own run or when a page, tab, or step change puts them back, the refusal names the hook, what it sits beside, and how many components each takes; it named neither the hook nor the page. - Both progress bars round halves up and fill only when done.
progress_bar()andrender_progress()rounded half to even and the V1ProgressBarrounded down, so 5 of 8 read 62% on both, 13 of 16 drew the V2 bar of 11 of 16, and 199 of 200 drew a full V2 bar at 100%. Both round the cells and the percentage halves up, on the numbers as written, so 5 of 8 reads 63% and 0.285 of 1 reads 29%, and show a full bar and 100% only at the maximum. gallery(),image_section(), andfile_attachment()take adiscord.File's own description and spoiler. They read only the file'sattachment://reference, so its description never became the image's alt text and a file sent withspoiler=Trueshowed unblurred. A description or spoiler given to the builder still wins, and thespoilerdefault ofimage_section()andfile_attachment()is nowNone(the file's own, else unblurred).divider()andgap()follow the view's theme wherever they were built, as acard()follows it for its accent: one built withlarge=Nonetakes the view'sseparator_spacingat every send, refresh, and navigation edit. One built outside a view, in a page list made ahead, was small under a theme asking for large spacing, and a theme changed at runtime left them as built.large=TrueorFalsestays as given.- Registering a theme under the default theme's name makes it the
default, so re-registering
"default"with new colours restyles every view that sets no theme. The default stayed on the old object. prune_unreachable()reports a deletion that failed part way instead of raising. It logs a warning and lists the rows deleted before the failure underprunedandmessages(andgonefor a 404), the rows still stored underkept, and a failure deleting the gone rows no longer skips the aged ones. It used to raise after restoring the recovered panels, so the rows it had deleted were reported only byREGISTRY_PRUNED, and nowhere when that dispatch was what failed.prune_unreachable(older_than_days=)takes a fraction of a day, asprune_application()does, where a float raisedValueError. NaN and infinity still raiseValueError.PersistenceMiddleware(prune_unreachable_after_days=)takes a fraction of a day too, such as1.5, where a float raisedTypeError. It stays at one day or more, since the daily sweep deletes unattended: a value under one day raisesValueError, and so do NaN and infinity, which raisedTypeError.REGISTRY_PRUNEDis dispatched only when a row was deleted. A prune of keys none of which were stored, or of an empty list, dispatched it withdeleted=0and no keys, so a hook that pruned related keys for each pruned key received empty actions in a loop until Python's recursion limit.prune_registry()still returns 0.prune_application()follows the same rule forAPPLICATION_SLOTS_PRUNED, as the daily TTL sweep already did.- A click a
DynamicPersistentButton'sinteraction_check()refuses is answered. discord.py leaves it unanswered, and the person saw "This interaction failed". The button now calls itson_unauthorized(interaction), whose default replies with the class'sunauthorized_message, named and worded as on views ("You cannot interact with this.";Noneacknowledges with no reply), unless the check answered the click itself. An override that sends nothing, or raises (logged with its traceback), leaves the click acknowledged. A check that raises is logged at ERROR with its traceback and the click acknowledged; discord.py dropped the exception. The click's acknowledgement timer now starts before the check, so a slow check no longer spends the 3 seconds before the timer begins.interaction_check()and an override offrom_custom_id()may be plaindefs, ason_click()already could: discord.py awaits both, so a plaindefrefused every click or failed it. - An empty leaderboard lays out like one with entries. Its masthead
(
banner,title, and the divider) and any rawbuild_footercomponent sit inside the empty-state card instead of above and below it, and the default empty-state card takescard_coloras the rankings card does. Anon_leaderboard_emptyoverride that returns one card keeps that card's accent andid, raw components or a string are wrapped in acard_colorcard, and any other return keeps the old layout, aContainersubclass included, so its owninteraction_checkstill applies. A board showing no entries looks different after the upgrade. - A section-mode leaderboard takes more than five rows a page. The class
definition refused a
leaderboard_per_pageabove 5, though eight rows fit beside the default frame, andset_class_attribute()andleaderboard_per_page = Nonereached the same rows unchecked. A page that does not fit Discord's 40 components raises when it builds, naming the rows and their share, whether a bot is bound, the rest of the page (build_header,build_footer, the masthead), and the fix. It suggests loweringleaderboard_top_nonly when one page holds every entry, where it suggested it on every board. - A
PersistentLeaderboardLayoutViewgiven no client has abotofNone, as every other view does. Itsbotanswered the botPersistenceMiddlewareholds, soself.bot is Nonemeant "not bound yet" on every view but this one. The board still draws avatars through the bot persistence holds. FormLayoutViewdraws the form as one card. The title comes first, with a form-level message under it, then each group under its heading: the group's text, number, and date answers beside an Edit button that opens only that group's fields, aselectof up to five short options as a row of buttons with the pick highlighted, abooleanas an On/Off toggle, and Submit at the bottom. It drew a card of answer lines, with each select as a dropdown, each boolean as a Yes and a No button, and the Edit and Submit buttons on rows of their own below it. A group's Edit modal holds five fields, so a grouped form takes more than five typed fields in all, where it raised. A form whose card would pass Discord's 40 components draws its selects as dropdowns, and past that a denser card: each dropdown under its label (named in its group's answers when the labels do not fit), eachbooleanas one button showing its answer, three to a row, and each group's Edit button beside Submit, so every form the old layout drew is still drawn; one too big for any card raises naming the form.values, the hooks, and validation are unchanged. An option button'scustom_idcarries its option'svalue, so a persistent form's posted button keeps its answer when the options are reordered, and the first group's Edit button keeps theform_edit_textid the one Edit button had. What a card takes depends on the fields, never on answers or errors, so a form that builds keeps its card. A test that clicked a V2 form's select or its Yes and No buttons clicks the option button with that label, or the toggle (form:toggle:<id>), instead.WizardLayoutViewdraws each step as one card. The progress header (the step's name over its bar) comes first, then a divider and the step: a step that returns one card keeps that card's color, and components with no card join the header's card. It drew the header and the step as two cards. A step that returns a card beside other items, two cards, or aContainersubclass keeps the old layout, as does abuild_progress_header()that returns anything but one card, a header card built withdiscord.ui.Containeror given a color, spoiler, oridabove a step card, a step card marked as a spoiler, and a step that fits 40 components only apart. A test that read the bar as the header card's last child reads its second.- An optional
CheckboxGrouporFileUploadleft empty skips its validators, as a blank optional text input does, and so does an emptymulti_selectform field; a required one still runs them. An empty pick was not blank, so a validator ran on no answer, andchoices()refused it, making the optional input required. - A tab view and a wizard redraw on a state change they receive, as the
paginator and the form do: the open tab's or step's builder runs again.
They sent the tree as it stood, so a change the view subscribed to showed
only after the next click. Neither
on_tab_switchednoron_step_enteredruns, since nothing moved, and a subclass's ownon_state_changedstill replaces the redraw. - A click on the tab already open draws it again without calling
on_tab_switched, and so doesswitch_tab()naming it: the hook runs when the open tab moves to another. The tab's builder still runs. - A jump to the page already shown redraws without calling
on_page_changed, on the paginators and onPaginatedRegion:set_page()orshow_page()with the current index, or a go-to number past the end while on the last page. An override that counted turns or prefetched did the work again for a turn that did not happen. - A V2 wizard's default progress header names the step. The current
step's
nameshows as a heading above the bar; a step dict whose name is not text keeps the bar alone. A step whose content opens with its own title now shows the name twice: remove that title, or overridebuild_progress_header(). - A pager arrow given an emoji shows the emoji alone, on
PaginatedView,PaginatedLayoutView, andPaginatedRegion. Withprev_button_emoji(or the first, next, or last one) set and the label left at its default, the default arrow showed beside the emoji, and a label ofNoneor""fell back to the arrow, so no arrow could show an emoji alone (a server's custom emoji cannot be a label). Any other label stays beside the emoji. A wizard's Back, Next, or Finish label set to""beside its emoji shows the emoji alone;""drew the default word.Nonekeeps the word beside the emoji. - A
PaginatedLayoutViewpage given as text is drawn as acard(), in the theme's accent color, as are its "Loading..." and "No pages." placeholders. They were drawn in a plain container with no accent bar. For the plain look, give the page asContainer(TextDisplay(text)). ATabLayoutViewtab or aWizardLayoutViewstep whose builder returns text is drawn the same way; it showed the text alone with no box. Text inside a returned list stays plain. - With
nav_inside_container, a page of components with no card of its own is wrapped in a card in the theme's accent, as a text page is. It was wrapped in a plain container with no accent bar, so one paginator's pages looked different by what they held. For the plain look, give the page as aContainerof its own.
Deprecated¶
- The roles pattern:
RolesLayoutView,PersistentRolesLayoutView, andRoleCategory. Every other pattern is a way of showing or moving through things, and a role panel changes the server: it grants and removes roles, needs the Manage Roles permission, and depends on Discord's role order, which belongs to the bot rather than to the interface. It keeps working through 4.x, and a panel class defined on it warns with aDeprecationWarning. It is removed in 5.0.0. To keep a role panel, build it from aPersistentLayoutViewwhose buttons add or remove the role in their callback; aDynamicPersistentButtonkeeps such a button working after a restart. The persistence example shows that shape: its role panel is now a help desk (/v2desk,/v2desk_move) whose topic buttons are one dynamic button class. _build_extra_items(),_build_category_item(),_build_category_button(),_build_tab_rows(),_build_progress_header(), and_freeze_components()are now their public names, the menu's_build_category_card()isbuild_menu_card(), and a V1 paginator's_extract_page()ispage_kwargs(). An override of an old name keeps working, called through the new name, and warns with aDeprecationWarningwhen its class is defined;super()under the old name still reaches the library's version, and a call to an old name warns and runs it. The old names are removed in 5.0.0.
Removed¶
_build_refresh_button()and_safe_defer(), deprecated since 3.14.0 and 3.14.1. Usebuild_refresh_button()andsafe_defer(). A view class, or a mixin it lists, that still defines an old name without the new one raisesTypeErrorwhen it is defined: the library calls only the new names, so the override would never run.build_reopen_view(). The Continue button no longer builds a new view; it resumes the same one on its own message. A view class, or a mixin it lists, that still definesbuild_reopen_view()raisesTypeErrorwhen it is defined, naming the fix: the work moves intoon_load(), which runs at every Continue, where the view can load fresh data for the redraw or callexit()to end the panel.- Methods only the library calls are private.
create_discord_component()on the five modal inputs,create_discord_components()onCompositeComponent,PersistenceManager.reattach_persistent_views()andreseed_registry_mirror(),PersistenceMiddleware.flush_all()andclose(), andUndoMiddleware.finalize_batch()are private. A class that still defines one raisesTypeErrorwhen it is defined; pass inputs toModal(inputs=[...]), add a composite's components withadd_component(), callreattach()to run the restore again, callstore.persistence_manager.flush_all()orclose(), which keep their names, and drop afinalize_batch()override, since a batch's exit writes its own undo entry.add_entry()andadd_undo_record()on the objectstore.batch()returns are private too: only the store andUndoMiddlewarecalled them.
Fixed¶
- A click queued behind a callback that rebuilt the view is judged against
the control the view now holds. When the rebuild disabled that control, or
sent a render without it, the click is dropped and answered with the current
render, as a click on a disabled control already was. The check read
disabledoff the object discord.py routed the click to, which a rebuild leaves enabled and routable until its edit lands. A one-shot action ran twice, and a button whose callback reads what the panel shows acted on the screen that replaced the one clicked (a Lock on one page locked the next page's pick). - A control the view disabled stays disabled when Discord reports an older
edit late. discord.py copies each edit of a message it tracks back onto
the view's items, so an older edit reported after a newer one re-enabled a
control the view had since disabled, and a queued click on it ran. Library
views keep their items as the view set them, and a view's own method named
_refreshis no longer called with each report (a synchronous one ended the bot's gateway connection). The inspector no longer logs acoroutine ... was never awaitedwarning on each such report. - A message left on an older render by a late edit is redrawn on the next
click. A wizard's step buttons, and any button whose label counts
something, change id when the view renders, so every control on such a
screen named an id the view no longer had: each click was only
acknowledged, and a wizard stayed on a step it had left. When Discord's copy
of the message still shows the clicked control, the view's current render
now follows the acknowledgement: once for a burst of such clicks, and after
a
refresh_cooldown_mswindow like any render of the view's own. It needsserialize_interactions. - A click's render and the view's other renders land in the order they were made. A click is answered with a render through its own request (the callback's render, or the view's current render for a click on a disabled control or one whose render was skipped as unchanged), while the view's other renders go through the channel, and whichever came back last stayed on screen until the view rendered again: a render made while the click's request was on its way could land before it, and one already on its way when the click came could land after it. Other renders of the view now wait for the click's request to come back (past 30 seconds they go on, with a warning), and the click's render first waits for the view's edits already on their way, within the time its own request was given, so the click is acknowledged no later than before.
- A wizard nav button whose meaning changed since it was drawn is redrawn,
not run. Next and Finish shared one id, so a Next drawn while a later step
showed ran
on_finish()once that step's condition hid it, and a Back with no earlier step left returned silently and stayed enabled. Such a click is now dropped and answered with the step drawn again; Finish has an id of its own (wizard_finish:N). - A click the library drops records no
COMPONENT_INTERACTION. A click dropped inside its control's callback was recorded as a click that never ran: the second of two clicks on a toggle or a confirm prompt sent while the first ran (another user's toggle, or a Cancel), a second Submit, Finish, or Continue, a single-select dropdown's re-pick of its active option, and a wizard Back or Next drawn for a step the wizard had left. Those last two now log their drop at DEBUG, as every other drop does. COMPONENT_INTERACTIONnames the id the clicked control carries. It named the id discord.py drew when the control was built, which a view replaces before the send, so the record matched no id a hook or selector could read, and a control rebuilt on each render added a store entry per click for the life of the view.- Renders the library sends again wait for a render another task is
building. The answer to a click on a disabled control, a stalled click's
render sent again, and the redraw after a push whose edit timed out all
sent the tree as it stood, so while an async
build_ui()oron_load()had cleared it and was still filling it, the message showed a panel with no controls. They now ship once that build ends, with the contentnav_rebuildnames at that point, including when the view'son_state_changed()renders nothing. The redraw after a failed push still skips arefresh_cooldown_mswindow. A V1 view withoutnav_rebuildsends these through its ownon_state_changed(), so its embed changes with its buttons, and when that renders nothing the dict itsbuild_ui()returns goes with them, as a close coming first already sent. - A view closed right after a dispatch shows the change before it closes.
A dispatch reaches every view but the one that made it on a task of its
own, so an
exit(),exit_children(), timeout, orreplace()made right after it reached the view first, declined its render, and left the screen from before the change, although the views guide advised dispatching a final action beforeexit_children(). A close now waits, for up to 30 seconds, for the state changes dispatched before it to render, including the re-run of a render already in progress. A child whose message the close deletes is edited once first; a view whose message is already gone (deleted, or never sent) closes without that render. A change dispatched inside abatch()still open at the close is announced when the batch closes, after it. - A file passed to a render the library sends later uploads what was
passed. A click's render whose one-request answer stalled, a render
held while the view was being sent or navigated, and a closed view's
last render held by
refresh_cooldown_msor a rate limit kept the caller's owndiscord.Fileand read it when they went out. A callback that had sent the same File elsewhere by then (aiohttp 3.11 closes a stream once it has written it) made that edit fail, and one that had written the next image into the same buffer uploaded that image. These renders now keep a copy of the bytes as they were whenrefresh()was called. - A push or pop whose first edit stalled and whose later edits failed redraws the panel. Discord may still apply a stalled edit, but the navigation counted as never landed, so the message could keep the discarded screen while the panel skipped its next unchanged render. It now redraws itself as it does after a timed-out navigation edit.
restore_on_dropped_render()puts its attributes back after an edit that stalled pastedit_timeout.refresh()returnsDROPPEDfor one, since Discord may not have applied it, but the manager kept the write: a two-click confirmation whose arming edit never landed showed unarmed with its flag armed, and the next click ran the action. An edit that did land now asks once more. A click's one-request edit that stalls is sent again once the click is acknowledged, so it is not undone, andrefresh_degradedstill reports only a failure that never reached Discord.- An edit Discord refuses for its contents (code 50035) is not sent again another way. A click's one-request edit and a push or pop retried a refused edit through the channel, which Discord refused the same way, uploading any files again; the error now raises from the first refusal, and a push or pop rolls back before raising it.
- A
build_ui(),on_load(), or pattern rebuild that raises part way leaves the panel as it was. The tree kept the items added before the raise, a valid one, so the next close froze, or the next render sent, a panel cut short at the failing item: a style refused while building, or a fetch that failed during areload()or a send. The build undoes only its own changes: one that raised before changing the tree leaves it alone, and so does one whose tree another task changed meanwhile (a page turn during areload(), a click's own rebuild). The paginated recompose, the form rebuilds, and the tab and step trees keep it the same way. - A
push()orpop()from a callback that replied first, or beside a reply still on its way (asyncio.gather()), moves the panel, not the reply. The click's original response was the reply, so the destination was drawn on the reply while the panel kept the old screen's controls, which no longer answered. A reply whose connection dropped before Discord answered, or one a cancel cut off, may be showing all the same, so it counts as a reply until the interaction's token expires. - A
push()orpop()made outside a click on an ephemeral panel past its 15-minute token leaves the panel working. Discord refused the edit, the navigation counted it as landed, and the panel kept showing the old screen while none of its controls answered. It now stays on that screen, live. - A view pushed with
auto_back_button = Truekeeps its Back button. Only the patterns put it back after rebuilding their tree, so a plain view whosebuild_ui()clears and rebuilds lost it on its first redraw and left the person with no way back, and apop()to a view that was itself pushed rebuilt it with no Back at all. Every render of a view with somewhere to go back to now carries it, untilauto_back_buttonis turned off on the instance. A view with no room left for it renders without it and logs one warning naming the fix, where a push onto it raised, and a V1 Back whose row 4 is full takes the first row with room. - A send whose
on_bind()oron_pre_send()is slow is acknowledged in time. The send's backstop countedauto_defer_delayfrom after those hooks, so a slowon_pre_send()andon_load()together posted past Discord's 3 seconds with nothing acknowledged, and the command failed. It now counts from thesend()call; a fast send still posts directly. - A hybrid command's send survives the backstop's acknowledgement. A
view sent with
context=ctxfrom a hybrid command answers throughContext.send. When the send's own backstop acknowledged the command between that check and the post, Discord refused the post (40060), the send rolled back, and the person saw "thinking..." until the command expired. It now posts as a followup, as a send made withinteraction=already did. - A panel whose message could not be read back after its send keeps
working past 15 minutes. When reading the posted message back through the
channel failed (a dropped connection, a Discord error), the view kept the
interaction's copy, which edits only while that interaction's 15-minute
token lasts, and logged nothing; from then on every edit made outside a
click failed. The read is now tried again in the background over the next
eight minutes, following the message into a
push()orpop(), and one WARNING says what stops working if it never succeeds. A read Discord refuses for missing access is not tried again, and warns once per view class. A read that stalls goes to that retry after 30 seconds, where the send waited up to five minutes for it. - With
auto_defer = False, the library's own waits are acknowledged. An older panel's exit underinstance_policy = "replace", or another task'sload()the send waited for, ran on the interaction's 3 seconds unanswered, and a slow edit failed the command; the send's interaction is now deferred onceauto_defer_delayhas passed sincesend()was called, as withauto_deferon, and the post goes out as a followup. A click that waits for another click, or for a push or pop, to finish is now acknowledged onceauto_defer_delaypasses, on your own controls too; before, it got nothing until its callback ran, which could be past Discord's 3 seconds. A callback on your own control that starts after that acknowledgement finds the interaction deferred:respond()replies as a followup, andopen_modal()shows its fallback message instead of the modal. - A modal callback that answers by sending a panel gets no "session ended"
notice beside it. When the view that opened the modal had closed, a
panel the callback sent after the submission was acknowledged went out as
a followup, which the check for an existing reply did not see, so the
notice followed it. A panel sent that way now counts as the reply, as one
sent through
respond()already did. - A modal's
on_error()that answers too late is reported. An override answering throughinteraction.responseafter the submission's timer had acknowledged it raised out of the dispatch, and the log named no cause. It now logs a warning namingrespond(), which works at any point. - A modal opened again after it took a submission raises. discord.py
stops a modal once a submission returns, a rejected one included, and
does not store it again, so the dialog opened and what the person sent
was dropped with nothing logged.
open_modal()now raisesRuntimeErrornaming the fix: build a newModalfor each open. - One person's modal submission no longer runs another person's modal.
discord.py files a modal by its
custom_idalone, so two modals opened with the samecustom_id=shared one entry, and the first person's submission ran the second modal's callback with the first person's values. A modal opened throughopen_modal()now refuses a submission from anyone it was not opened for, with a short reply (Modal.stale_submission_message;Nonesends none) and a warning naming thecustom_id. When one of those modals is submitted, times out, or stops, the other person's modal still takes their submission, where discord.py had dropped it. - A choice left out of
Modal.submit()keeps the options marked as its defaults. A radio group, checkbox group, or select left out ofvaluesread as no answer, though the dialog opens on its defaults and a text box left out kept its own, so a form's dialog lost a pre-filled answer the test did not name. - A modal someone closes without submitting no longer stays in memory
for the life of the bot. Discord sends nothing when a dialog is closed,
so discord.py kept every dismissed modal, with its callback and the view
that opened it. When the same person opens another modal through
open_modal(), the one they closed is let go, unless someone else still has it open; it can still be opened again. - A modal takes inputs labeled in any language. An input's id keeps only its label's ASCII letters and digits, so two labels in Japanese, Russian, or emoji, or two that differ only in punctuation or case ("Name" and "Name!"), gave one id and the modal refused them as duplicates; a form refused such modal fields too. The later input now takes a code made from its label after the id, the same on every build, and the first keeps its id. Two inputs with the same label are still refused, and the message now names the label.
- Modal inputs refuse text past Discord's caps when built. A
placeholder or description over 100 characters, a
TextInputdefault over 4,000, and a checkbox or radio option whose label, value, or description is over 100 built cleanly and failed when the modal opened. Each now raisesValueErrornaming the input, and a placeholder, description, or default that is not a str raisesTypeError. TextInputrefuses astylethat is not adiscord.TextStyle. A string such as"long"built cleanly and raisedAttributeErrorwhen the modal opened, naming nothing.open_modal()checks a modal's raw discord.py items before it opens. A title orLabeltext over 45 characters or empty, a description or text input placeholder over 100, a text input value over 4,000, a select placeholder over 150, a select with no options or more than 25 (or option text over 100), a select disabled inside aLabel, an emptyTextDisplay, and acustom_idover 100 reached Discord, which refused the modal with a 400 in front of the person who clicked. Each now raisesValueErrornaming the item, before anything is sent. A raw modal whosecustom_idis not a str raisesTypeError: the modal opened, and its submission never arrived.- A text input's default must fit its length bounds. Discord refused a
modal whose input was prefilled with text longer than its
max_length, or shorter than itsmin_length, when it opened.TextInputraisesValueErrorwhen built,open_modal()refuses a raw discord.py text input the same way, and a form field whose default does not fit, measured as its edit dialog shows it ("007"in an integer field shows as7), raises when the form is built. An empty default is not sent, so it passes. - A dismissed modal no longer freezes the view that opened it. A
callback that opened a
Modaland awaited itswait()held the view's click turn, and Discord sends nothing when a person closes the dialog, so every later click on the view, by anyone, Exit included, waited behind it for good.Modal.wait()now gives up the turn while it waits and takes it back before returning, so the code after it still runs in order. A plaindiscord.ui.Modal'swait()keeps the turn. - A
with_confirmationprompt that times out disables its own buttons, not the panel's. When the click had been acknowledged before the prompt went out (it waited behind another click pastauto_defer_delay, or awith_loading_statearound it answered first), the prompt posted as a followup, the wrapper took the clicked panel for the prompt, and the timeout replaced the panel's controls with the prompt's two disabled buttons. On a plain discord.py view it does too. - A wrapped control refuses a click before its wrapper acts.
with_cooldown,with_confirmation, andwith_loading_stateran ahead of the control's own checks (a button'sowner_only, achoice_rowdropdown's pick check), so a click the control refused started a cooldown (a global one then turned the owner away for its whole length), showed the confirmation prompt, or flashed the panel into its loading state for everyone. The refused click now gets only the refusal. - A question asks the cooldown inside it before it asks the person. With
with_cooldownapplied beforewith_confirmation, a click inside the cooldown still got the prompt, and its Yes showed "Confirmed." before the cooldown turned the action away. The click now gets the cooldown's notice and no prompt; a Yes the cooldown turns away (a second prompt left open) changes the prompt to the notice; and a No still leaves the button free.with_loading_statewrapped around a cooldown no longer shows its loading state for a click the cooldown turns away. - A Yes takes its turn on the panel and does nothing once the panel has
closed. The prompt stays open while the panel goes on, and its Yes ran
the action beside a click still running on the panel, or after the panel
had closed, timed out, or moved to another screen. A Yes now waits for a
click in progress (acknowledged at once, answered when that click ends),
and on a closed panel it runs nothing and the prompt shows the panel's
session_ended_message, or itson_session_ended()override answers. A No'son_cancelwaits for that click the same way, and still runs once the panel has closed. - A cooldown notice never shows a wait shorter than the real one.
{remaining}was rounded to the nearest tenth, so 2.41 seconds read "2.4" and a wait under 0.05 seconds read "Try again in 0.0 seconds", and a click at the time shown was turned away again. It now rounds up: 2.41 reads "2.5". - Assigning
timeoutafter the send restarts the count from the assignment, for every view. Atimeoutset in the class body hid the property, so a later assignment reached no timer at all; it is now the constructor's default (see Breaking). A shorter timeout waited out the longer one, since discord.py's timer sleeps to the deadline it last read, and0ended the view at that deadline instead of stopping the count. For a card discord.py does not track, the library's own timer counted from the last edit, so a card idle for a minute whose timeout was raised from 60 to 90 seconds closed 30 seconds later instead of 90, and one set toNoneand then to a number never timed out.set_class_attribute("timeout", ...)now sets it the same way, andself.timeoutassigned in__init__beforesuper().__init__()is the constructor's default instead of raisingAttributeError. - A timeout no timer can read raises where it is set.
timeout=nanin a view's constructor or class body stopped the event loop on Python 3.14 once a card with nothing to click was sent (earlier versions timed the card out at once), and a string such as"300"madesend()raise after the message was posted. A value that is not a number, a bool included, now raisesTypeError, and NaN or a negative numberValueError, from the constructor, the class body when the class is defined, an assignment, andset_class_attribute(). AModal'stimeout=andwith_confirmation()'s are checked the same way where they are passed: discord.py times both, so a string failed only once the modal opened, NaN left it open for good, and a negative number ended it before the user could submit. edit_timeoutandauto_defer_delayrefuse NaN. NaN compares false to everything, so it passed their positive-number checks: a NaNauto_defer_delayleft a slow click unacknowledged (the backstop's sleep raised on Python 3.14 and never returned on 3.11), and a NaNedit_timeoutmade the library's bounded edits time out. Both raiseValueErrorwhen the class is defined,auto_defer_delayon aModaland aDynamicPersistentButtontoo.- A private re-send that fails leaves a panel's
timeout=Nonein place. discord.py gives an ephemeral view 900 seconds before the request is made, so a panel declaredtimeout=Noneand sent again withsend(ephemeral=True)kept them when Discord refused the send or the caller cancelled it, and froze for every user 15 minutes later. - An ephemeral view that declines the Continue handoff times out on every
send path. discord.py gives it a 900-second timeout on an interaction
response, but on a followup only when it has something to click, so a card
sent after a defer with
timeout=Noneandauto_refresh_ephemeral = Falseheld its instance slot until a restart once the user dismissed it. It now times out on every path, 90 seconds before its newest interaction's fifteen minutes end. - A Continue that cannot bring the panel back says so. When the
replacement's send failed (Discord refused it, as for a V2 panel naming a
file the send did not carry), each click on Continue flashed and did
nothing: the failure was logged and
on_reopen_failure()never ran, soreopen_failure_messagewas not sent. Every failure now runs it, and the Continue button stays. The resumed panel keeps its message, uploads included, and a V1 panel keeps its embed, where it came back as its controls alone. - A Continue button clicked after its view is gone is answered. The
button outlasts its view when the bot restarts, or when the view times out
after its last interaction ran out, since the close cannot reach the
message. discord.py found no item for the click, so the person saw "This
interaction failed" on a button that still looked live. The button now
turns grey and the person gets the view class's
session_ended_messageprivately (Nonesends nothing). For a class that overrideson_session_ended()the button only turns grey, since no view is left to run the override. A Continue given its owncustom_idinbuild_refresh_button()is left to the bot, and so is one a 3.14.2 panel drew, whose generated id names no class. - An ephemeral panel used past its first fifteen minutes can still be
closed and edited. Edits went through the send's interaction token, which
Discord refuses after fifteen minutes, so on a panel kept open by clicks an
exit()left it on screen, a timeout left its controls live, and a Continue clicked after fifteen minutes posted a new panel while the old one kept a Continue button whose view was gone. The view now edits and deletes its message through the newest click that updated it, whose token lasts fifteen minutes from that click, and a close made inside a click past every other token goes through that click. Sending the view again past its command's fifteen minutes posts through the click being handled, or else that newest click. A private send takes only a token of the person who ran the command, since Discord shows it to no one else, and one that none of theirs reaches raisesRuntimeErrorinstead of going out publicly, as discord.py'sContext.sendposts it. send(ephemeral=True)from a command invoked by prefix sends a public panel, and the view treats it as one. discord.py posts it publicly, since a prefix command has no interaction to reply through, but the view counted it as ephemeral: with no timeout, a Continue button replaced the public panel after 13.5 minutes, and a click on it moved the panel into a reply only the clicker could see.- A panel sent after a defer of your own is treated as Discord posted it.
Discord gives a reply after a slash command's defer the defer's
visibility, so a command that deferred publicly and sent
ephemeral=Truegot a public panel the view treated as private, and its Continue button replaced the public panel after 13.5 minutes; deferred privately and sent public, the panel was private and stopped updating after 15 minutes. The view now reads the posted message's flag, behaves as what is on screen, and logs a WARNING naming the defer, once per class. - A private reply after a slow public send stays private. A send from
a slash command that outlasted
auto_defer_delaywas deferred publicly by the library, so a refusal sent withephemeral=True(an instance limit, a full panel, a reply fromon_pre_send()), or a panel the command then sent privately, appeared in place of the "thinking" message for the whole channel. The library now deletes its own "thinking" message first, and the reply goes out privately. - A view sent again after its Continue button appeared posts its own
panel. The send posted the Continue button alone, the panel's controls
gone, unless the view's
on_load()rebuilt them. A send that fails leaves the old message's panel armed as it was. - A click on a dynamic button puts off the timeout of the view that drew
it. Role buttons and every
DynamicPersistentButtonroute by template, so their clicks never reached the view, and a sessionRolesLayoutViewfroze its role buttonstimeoutseconds after it was posted (180 by default) while members were still using it. wait()returnsTrueafter a directon_timeout()call, as it does after the timer's timeout; it returnedFalse.- A view built with no event loop running takes clicks, times out, and
reads as finished once closed. discord.py gives a view the future it
reads all three from only when it is built on a running loop, so a view
built at import time or in a synchronous test fixture and sent later got
none of its clicks, never timed out, and read
is_finished()asFalseafterexit(). The view now takes that future from the loop it is sent or pushed on. - A view class that declares
allowed_usersin its body still turns members into ids. The declaration hid the property that does it, soself.allowed_users = {member}in__init__kept the member objects and refused every one of them. The declared value is now the default, and an assignment goes through the property as usual. - A
Membergiven for a user or guild id stands for that id everywhere.unregister_participant(member)removed nothing, so the person kept their place and the instance limit kept counting them. The scoped-state reads and writes (get_scoped(),set_scoped(),dispatch_scoped(),user_scoped_state()) andcheck_instance_available()built their key from the member's text, so they used a slice nothing else reached, and a full limit read as free.StateStore.iter_scoped()takes a member or a digit string as a filter, asget_scoped()does, where either matched nothing, and adispatch_scoped()payload carries the id. A member assigned toview.user_id, or a guild toview.guild_id, after the view is built stands for its id as well; it was kept as given, and the member's own clicks were refused. Data written from a member before this release stays under the key made from its text, which reads by id do not reach.register_participant()already took a member. A string passed tounregister_participant()now raisesTypeError, as it does forregister_participant(). - A view sent to a channel that its instance limit refuses raises
InstanceLimitErrorfromsend(). Built withcontext=channel, it raisedTypeErrornamingephemeralinstead: the refusal went through the channel'ssend(), which takes no such argument, and there is no one to tell privately. A command'sctxstill gets the refusal as before. - A player the instance limit refuses during someone else's send is named,
not addressed. With
auto_register_participants = True,send()checks each listed player on the sender's interaction, and the defaulton_instance_limit()told the sender "You're already taking part in one of these." about another player. The reply now names that player, with mentions off. A player refused on their own click is still addressed as before, andinstance_limit_messageis sent as written.InstanceLimitError's own message reads "Instance limit" where it read "Session limit". - A sent view given another owner counts against the new owner's instance
limit. Assigning
view.user_idafter the send left the view counted for the owner it was sent for, who was then refused a panel they no longer had, while the new owner could open one more.view.guild_idmoves it the same way, and the view's row in the store, which the inspector and/cascadeuiread, records the new ids too. A participant made owner leaves the participants, whereparticipant_limitcounted them twice. On a view not yet sent, participants follow a new owner, guild, orinstance_scope: they stayed filed under the old one, holding a seat there even after the view closed. An owner, guild, or participant set while a push, pop, orreplace()loads the next screen reaches that screen, which had copied them when it was built: the panel landed under the old owner. An owner passed topush(), or one the new screen sets itself, is kept. The view keeps the session it was opened with, and a persistent panel restored after a restart keeps the owner it was registered with. - Session data written before a view's send is kept.
update_session()beforesend(), or in a view's firston_load(), wrote nothing and said nothing, since a view's session opens when its send registers it. The session now opens with those values, andshared_datashows them before the send. - A view with no owner has a session. A panel posted to a channel had a
session_idofNone, soshared_dataread{},update_session()wrote nothing, andpop()returned without moving: Back did nothing on a screen it pushed from code or withpush(instance), which is howfrom_data()andfrom_cursor()screens open. Such a view now gets a session of its own, and an owner set on a view before its send gives it a session for that owner. Withsession_continuity = True, such a panel's opens share one session per server. A restored panel whose row recorded no session gets one of its own too, rather than the bare per-user key every such panel shared. push(instance)keeps an owner or guild given to the instance when it was built, aspush(Cls, user_id=...)keeps one passed there. The source's were copied over them.update_session()takes a key namedsession_id. It raised aTypeErrornamingActionCreators.session_updated().- An undo puts back only the session data its step changed. It restored
the session's whole
shared_dataas the step found it, so a key written after the step by another view in the session, a screen the panel pushed, or code with no view behind it was lost. Session data is now undone key by key, as application slots already were. undo_limit = Nonekeeps every step. It passed the class check, and then every change logged "Undo could not record" at ERROR and none was kept.- A view or bot class that defines
__eq__sends, attaches, and closes normally. The library kept those objects in sets that hash their members, and defining__eq__without__hash__makes a class unhashable: such a bot class made every send raiseTypeError, and such a view class made the bot'sclose()raise it, leaving that bot's views registered instead of released. Attached views were compared with==, so when a view class's__eq__called two children equal, the second was taken for the first: it was never attached and outlived its parent. - A component class whose
__eq__calls every item equal no longer loses the Continue button. An ephemeral view showing its Continue button compared its children with==, so arefresh()from the caller's own code took the rebuilt panel for the button and shipped it over the button. - An item from
build_extra_items()whose class defines__eq__stays on a V2 tab view, wizard, or paginator. The pattern told its own items from the extra ones with==: an__eq__reading the other side's attribute raised from the library when the view was built, and one calling every item equal was taken for the pattern's own and dropped at the first re-render. - A component callback that is an object with its own
__eq__is accepted on Python 3.10 to 3.12, as is afunctools.partialor afunctools.wrapsadapter around one. Reading its signature there compared it withtype, so an__eq__that reads an attribute of the other side raisedAttributeErrorwhen the button or select was built. Such an object is now read through its__call__. - A component callback annotated with a name imported only for type checking
is accepted on Python 3.14. From 3.14 an annotation is evaluated when it
is read, so reading the callback's signature raised
NameErrorwhen the button or select was built, where plain discord.py builds it. Signatures are now read without evaluating annotations. - Collecting a copy of a registered view leaves the original registered.
A view's finalizer unsubscribed and unregistered by the view's id, which a
copy.copy()of the view shares, so when the copy was garbage-collected the live original stopped receiving state changes and no longer counted toward its instance limit. It now removes only the entries that belong to the object being collected. - A
nav_rebuilddeclared as aclassmethodis accepted. It reads back bound to the class, so the view it renders is its one argument, and every read of it works; it was refused with a message saying it would be handedself. Another object's bound method is accepted on every supported Python; 3.10 and 3.14 refused it with the same message. set_class_attribute("nav_rebuild", ...)takes what the view will call. A plain function or lambda and aclassmethodwere refused as callables that bind as a method, which an instance attribute never does, and an override on a pattern that declares its ownnav_rebuild(PaginatedView,TabView,WizardView,FormView,MenuView, andMenuLayoutView) was refused as a method or property. Each is now stored as the view reads it.set_class_attribute("theme", ...)works on a view whose class sets no theme. It raisedValueErrornaming a missing attribute, while the same call worked on a class that set one.- A plain mixin's
persistent_slots,build_ui(), andon_load()work as they do in the class body. The slots were never registered, so nothing written to them was saved, and the two hooks ran outside the view's theme and without the guard that puts back a tree a build left half done. - A
build_ui()oron_load()declared as astaticmethodorclassmethodruns. The wrapper that sets the view's theme passed the view to it, so every call raisedTypeError. - A view class whose definition raises is left in no registry. An async
state_selector, atab_overflow_policythe tabs refuse, and a rolescategoriesentry or hook the panel refuses raised after the class was registered, so a lookup by name still found it. The role categories listed before the bad entry stayed registered to it, and a corrected class under another name was refused as a collision. - A view class listing a Protocol before the view base is set up, from
typingortyping_extensions.class Panel(Renders, StatefulLayoutView)withRendersa Protocol ran no__init__at all, so the view had no id and failed at its first use with anAttributeErrornaming neither cause. A view whose own__init__callssuper().__init__()through such a Protocol, which Python ends at the Protocol, raisesTypeErrorwhen it is built, naming the Protocol and the order of bases that fixes it. - One subscriber whose
action_filteris a list no longer stops every batch. The store checks a filter against a batch's action types with a set operation a list does not support, so a singlesubscribe(..., action_filter=[...])made every batch raiseTypeError, and every view'ssend()runs one. A list or tuple is now read as a set (a str is refused, see Breaking). - A payload of
0,False,"", or[]reaches reducers as given.dispatch()replaced every falsy payload with{}, so a reducer reading a count of 0 or a cleared list got an empty dict. Only a missing payload (None) becomes{}. LoggingMiddlewarelogs an action whose payload is not a dict. It read the payload's keys, sodispatch("SET_COUNT", 5)raisedAttributeErrorinside the middleware chain and the action never reached its reducer. Such a payload is now logged by its type.- A later
setup_logging()call changes the action log an earlier one installed. It kept the first call's:setup_logging(actions="DEBUG")aftersetup_logging()still logged actions at INFO, andactions=Falseleft the action log running. ALoggingMiddlewarethe bot installed withsetup_middleware()is the bot's and is left as it is. - A middleware written as a plain
defcan stop an action by returning the state. Its result was awaited, so every action it stopped raised aTypeErrorsaying a dict cannot be awaited. One that passes an action on by returningnext_fn(action, state)already worked. access_slot(state, name, key)on a slot that is not a dict names the slot. It raised Python's ownTypeErrorfrom inside the helper; it now raises one naming the slot and how to read it whole.set_scoped()is saved, and keeps a copy of what it is given. A persistent slot written byset_scoped()reached the database only when a later dispatch wrote the same slot, so a value seeded at startup was lost at a restart. The store kept the caller's dict, so a later change to it showed in the store with no write.dispatch_scoped()refuses data it cannot merge, at the call. A list, a string, orNonereturned normally while the reducer logged an error naming neither the call nor the argument, and nothing was written.merge_scoped(subkey=)over a value that is not a dict raisesTypeErrornaming the key and the subkey; it raised Python'sAttributeError: 'str' object has no attribute 'update'.iter_scoped()skips a key that is not text, as it skips any key that does not parse. A slot keyed by guild id ints raisedAttributeErrorfrom inside the loop.- A
@computedvalue whose function raised is computed again on the next read. The selection was stored before the function ran, so after a raise the next read with the same state returned the value from before the change, with nothing raised. - A
@computedvalue whose selection cannot be compared is computed on every read, with one WARNING naming it. A selection whose==cannot become a bool (an array-like value) raised its own error from the second read on. - A store hook gets the state its action's subscribers got. Hooks ran after the dispatching view's redraw and read the store's state then, so a change another click committed during that redraw reached the first click's hook. Inside a batch every hook gets the state the batch left, as the batch's subscribers do.
store.persistence_managerreadsNoneuntilPersistenceMiddlewaresets it up. The store had no such attribute before then, so reading it on a bot without persistence raisedAttributeError.state["modals"]stays an empty dict when its last entry goes, asstate["components"]does. Closing the last view with a modal submission on record, or the inspector's purge, removed the key, so code readingstate["modals"]raisedKeyError.- Library work an event loop leaves unfinished raises nothing when its
coroutine is destroyed. A send, close, navigation, click, or backend call
still running when its loop closed without cancelling it (a test runner's
per-test loop, an application closing its own loop) ran its cleanup on a loop
that was gone, and
close()raisedRuntimeError: no running event loop,Event loop is closed, or a context variable's "created in a different Context", printed at a program end or reported by pytest as an unraisable exception. That cleanup is skipped now. Cleanup an async generator runs when its caller leaves it early still runs. - Tasks run as written under an eager task factory. With
asyncio.eager_task_factoryset on the loop (Python 3.12+), a task ran its first step insidecreate_task(), before the library recorded it. A task started withview.create_task()that calledexit()went on past the call against the closed view, since the teardown, which cancels the view's tasks, did not know of it; and a persistent slot changed faster than the backend wrote could keep an older value stored, because each change cancelled the write in progress as if it were still waiting. A task the library orview.create_task()starts now begins once the code that started it has run, as without a factory. - Profiling credits each edit to the dispatch that made it when two overlap. A dispatch that ended first could take the other one's edit count, so an edit landed in the sample of a dispatch that had already ended.
- A registry prune deletes only the row it checked, so a panel posted again
under the key keeps working. A reattach pass or the unreachable sweep could
delete the registration of a panel posted again while it ran, and the panel
came back dead after the next restart. A prune of a key whose new panel had
not reached disk yet also dropped that panel's entry from
state["persistent_views"], so itsexit()removed nothing and the closed panel returned at the next restart. A reattach pass could likewise drop it from the rows an in-process restart restores. Every prune, a directprune_registry()call included, now deletes only the row it read and drops only that row's entries. A custom backend owes one more property for this, listed with the guide's backend contracts:row_deletemust match awherebuilt from the values itsrow_selectreturned, or a registration is never pruned. - A delete that fails after reaching the database still reports the rows it
removed. A delete that reached the database and then raised, or was
cancelled while it waited for the reply, removed rows with no
REGISTRY_PRUNED. It now dispatches them, except a row whose key was posted again meanwhile, since it cannot tell whether its own delete took effect. A row can be reported more than once: when two prunes race on one row, both can report it, so a handler should act on a key only while the message it recorded matches the one inmessages(any record, where that id isNone), which also skips the deletion of an older post under a key posted again.prune_registry()returns the number of rows its own deletes removed; before, a hook that edited the action'smessagescould change that count. - A prune cancelled while
REGISTRY_PRUNEDruns still announces what it deleted. A cancel landing while a hook or a middleware awaited (the bot's close cutting the daily sweep, or a caller's timeout) cut the dispatch, so later hooks never heard of the deleted rows, and when the reducer had not run yetstate["persistent_views"]kept the key: a panel later sent under it closed the message the prune had left up. The prune now waits up to five seconds for the dispatch before the cancel goes on, the dispatch runs to its end either way, andclose()waits for one still running, or a prune still in flight in another task, before the backends close. The dispatch runs outside anystore.batch()the pruning code opened, so a prune inside a batch is announced at once rather than as the batch closes, where a cancel could still cut its hooks short. - A
prune_registry()override is reported by what it deleted. An override callingsuper().prune_registry()more than once (per key, or a retry) had every call after the first dispatched withsource="prune_registry", so a hook skipping reattach deletions handled them twice. Each such call now carries the pass'ssource, and itsreason("gone"or"unreachable") when it passes none. A reattach pass listed every key it handed the override as removed, even rows left stored, and an override that emptied the list it was given made the pass and the sweep list none. Both now hand the override a copy and report the rows they find deleted. A row the override deleted some other way is dispatched under the pass's ownsource, even when the pass is cancelled before the override returns. A row another prune deleted while a pass or the sweep ran, which appeared in no list, is listed removed (prunedby the sweep) and dispatched under the pass'ssourcetoo. prune_registry()refuses bad keys. Astrpersistence_keys(read one letter at a time) or a key that is not astr(anintmatched the stored text on SQLite while the store kept the row) raisesTypeError, and a key named twice is pruned once.prune_application(older_than_days=)checks its cutoff. A negative number moved the cutoff into the future, so slots that had not expired were deleted with nothing raised, andTruewas read as one day. Anything but an int or a float, a bool included, now raisesTypeError, and a negative or non-finite numberValueError, before anything is deleted. These checks and the refusal ofslot=witholder_than_days=run with no backend configured too, where the call returned 0. A cutoff so large it falls before 1970 deletes nothing; SQLite raisedOverflowErrorfor it.- A persistence hook that calls back into the manager raises instead of
stopping persistence.
on_flushandon_errorrun while their namespace's write waits on them, so a hook awaitingflush_all(),close(),rehydrate(), orprune_application(slot=)waited on itself: no later write was saved, and the bot's close timed out, with nothing logged. Each now raisesRuntimeErrornaming the call and the fix (start it withasyncio.create_task()and do not await the task); a call a hook awaits through such a task is named in a WARNING after 30 seconds. A hook may now callbot.close(): persistence closes once the hook returns, where it stayed open. - A
PersistenceManagerbuilt directly checksrestore_concurrency=, asPersistenceMiddlewarealready did. A0left the restore waiting forever for a slot no row could take, and a str raised from inside the restore naming neither the argument nor the class. - A kwargs or schema migrator written as a plain
defruns. The restore awaited a kwargs migrator's result, so a plaindefput every row it should migrate underfailedwith'dict' object can't be awaited, and a schema migrator failed the start. - A kwargs migrator registered with the decorator and passed to
migrators=as well no longer logs a warning. The warning said the one passed was ignored, though it was the same function. A different migrator for the same key still warns. - A persistent panel whose class body sets
persistence_keyis saved. The declared value hid the property, so a class with one alone was refused as having no key, and one also given a key at construction registered under the class value with no row saved, so it did not come back after a restart. The declared key is now the default, the constructor's wins, and a declared key that is not a non-emptystrraises when the class is defined. - A persistent panel takes a
custom_idof 32 hex characters. An id such asuuid4().hexor an md5 digest was read as one discord.py generated, and the send raised "missing a custom_id". The check now asks discord.py whether the id was given, as discord.py itself does. - A restored panel takes clicks only once its
on_bind()has returned. The restore handed the panel to discord.py first, so during areattach()or the unreachable sweep's restore, with the bot connected, a click could run beforeon_bind()set what the callback reads. - A raw-SQL transaction is kept to the backend and the block that opened
it. Raw SQL on a second
PostgresBackendinside the first one'stransaction()ran on the first one's connection and rolled back with it. With transactions open on two backends at once, raw SQL on the first one inside the second one's block left the first one's transaction: on PostgreSQL it committed past that transaction's rollback, and on SQLite it waited forever on the lock the transaction held. A task started inside the block and still running after it ran its raw SQL on the connection the block had given back, and asyncpg refused it; it now takes a connection of its own, as on SQLite. Such a task opening atransaction()of its own while the block is open raisesRuntimeError, as on SQLite: it opened a savepoint on the block's connection, which committed with the block and failed to close once the block had given the connection back. APostgresBackendtransaction thatclose()cuts off raisesRuntimeErrorsaying nothing it wrote was committed, as on SQLite, instead of asyncpg'sInterfaceError. InMemoryBackendmatches aNonein awhereclause to no row, as SQL'scol = NULLnever matches. It matched a storedNone, so code tested against it behaved differently on SQLite or PostgreSQL.InMemoryBackendrefuses an emptywhereor key list, as the SQL backends do.row_delete(namespace, {})deleted every row, androw_upsert()orrow_upsert_many()with no key columns overwrote the first stored row, where SQLite and PostgreSQL raiseValueError.SQLiteBackend.fetch()andfetch_one()commit a statement that writes.fetch_one("INSERT ... RETURNING id")returned the new id with the row uncommitted: the nexttransaction()failed at BEGIN and rolled the row back, or a close lost it.- A SQLite
transaction()whose COMMIT fails is rolled back. A COMMIT refused by a deferred foreign key or a full disk left the transaction open, so the next unrelated write failed on it, or a later commit wrote the rows of the block that raised. - A task started inside a nested SQLite
transaction()joins the block around it once the nested block ends, as on PostgreSQL. Its next statement waited for good on the lock the outer block held. - A change saved from inside the caller's SQLite
transaction()is written once the block ends. The flush inherited the block's marker and the backend refused its write as the caller's own: an ERROR, anon_errorcall, and the write left to the retry backoff. - A PostgreSQL role holding only
SELECT,INSERT,UPDATE, andDELETEon the tables can run the bot once the owner has made them, as the Backends page describes. Every start ranCREATE TABLE IF NOT EXISTSandCREATE INDEX IF NOT EXISTS, which PostgreSQL checks againstCREATEon the schema and ownership of the table before it looks for the object, so the start failed withpermission denied for schema publicfor any role but the owner.PostgresBackendnow creates only what is missing, and a missing table or index the role cannot create raisesPersistenceInitErrornaming it and the fix. A failedinitialize()closes the pool it opened, so a later call starts over instead of returning at once with no tables. - A start that fails closes the backends it opened. When
setup_middleware()raised partway (a database a later release migrated, a failed read, a backend that could not open after another had, a cancel), the connections already open stayed open, and the store never got the manager that could close them. Withoutbot=, SQLite's worker thread then kept the process running after the program ended. The start now closes them before the error goes on, and callingsetup_middleware()again opens them again. - A
setup_middleware()retried after a failed start uses what the retry passes. The failedPersistenceMiddlewarestayed installed, and a new one took its place only for the bot, so the retry ran the first call's backend and migrators again: a fallback to SQLite after PostgreSQL refused failed with an error naming PostgreSQL. - The rename of the old table names finds a table the role holds no grant
on. It looked for
persistent_viewsandapplication_slotsthroughinformation_schema, which lists only tables the role has a grant on, so a role with none started on new, empty tables and left every saved panel and slot in the old one, logging nothing. The rename now reads PostgreSQL's catalog, and a role that cannot rename the old table getsPersistenceSchemaErrornaming both tables. - PgBouncer in statement mode is refused when the backend opens. Every
write runs in a transaction, which statement mode ends by closing the
connection, so the bot started and every save failed after it.
initialize()now runs one transaction first and raisesPersistenceInitErrornaming the pool modes that work. - A custom raw-SQL backend in a dialect other than SQLite's or PostgreSQL's
starts. The library's own SQL took any
placeholder_stylebut"qmark"to mean PostgreSQL, so such a backend (a MySQL driver's"format") was sent PostgreSQL's queries: every start raisedPersistenceSchemaErrorfrom the rename of the old table names, and the unreachable sweep's stamp never landed. The rename now leaves such a backend alone, the stamp goes throughrow_upsert(), and a schema migration adds its column without PostgreSQL'sIF NOT EXISTS. - An
async definvalidation callback runs, and an error a callback raises is reported as its own. The callback's return value was dropped, so anasync defcallback never ran and Python warned it was never awaited. ATypeErrororAttributeErrorit raised was logged as a malformed notification, and asyncio logged any other error as one in the library's own_on_notify. Either kind of callback now runs, and its error is logged at ERROR naming it and the(namespace, key)it was handling. - A listening connection whose network path goes quiet is reconnected.
PostgresBackendchecked it every 10 seconds with asyncpg'sis_closed(), which reads a flag on this side, so a connection a NAT, firewall, or load balancer dropped without telling either end still read as open, and no notification arrived again until a restart, with nothing logged. Each check now runs one small query and reconnects when no answer comes within 10 seconds; the query also keeps an idle path from being dropped. PostgresBackend.close()lets go of everything when the listening connection does not answer. It waited with no limit for that connection to close, so on a quiet path persistence's 10-second close limit cut it off before the pool closed, and the nextinitialize()found the pool, returned at once, and never listened again. The listening connection's close is now limited, a reconnect cut off before it listens drops its new connection instead of waiting on it, and a close cut off part way still closes the pool and the connection.- A PostgreSQL
table_prefixlonger than 41 characters is refused when the backend is built. The prefix also names the notification channel, which PostgreSQL refuses past 63 bytes, so such a backend started cleanly and then every write failed withchannel name too long, saving nothing.PostgresBackend()now raisesValueErrornaming the limit. - A deployment whose
table_prefixends incascadeui_leaves another deployment's tables alone. The rename of the pre-3.11 table names looked for the old names under the prefix, and with a prefix that is another deployment's pluscascadeui_those are its current tables: the first start renamed them, rows included, and the other deployment came back empty. A prefixed database never held the old names, so the rename runs only without a prefix. - A
table_prefixstarting withidx_works. The index names were prefixed after the table names and prefixed those a second time, so the tables were created asidx_idx_cascadeui_*while every call addressedidx_cascadeui_*, and the first read or write failed. - A start without
bot=warns only about panels and buttons that will not come back. Importing CascadeUI registers its own persistent classes and the roles panel's button, so every such start logged two WARNINGs namingPersistentView,PersistentLayoutView, and other library classes, even for a bot with nothing persistent of its own. The WARNINGs now name the persistent panel and dynamic button classes the bot defines, and the class of every panel the registry holds. - A bot run as several processes, each on its own shards, restores and
checks only the panels on those shards. Every process restored every
panel: it fetched each panel's message at start and held a view no click
reaches, a view with
on_restore()redrew its panel once per process, and every process's unreachable sweep fetched every row. A process now leaves a panel in a guild on another shard to the process running it; a bot running every shard, or one whose shard count is not known yet, keeps them all. - A saved slot whose expiry has passed is dropped at the next start, however
its
ttl_dayswas set. The start dropped expired rows only while some slot had attl_dayspolicy, so a slot whose policy is registered withregister_slot_policy()aftersetup_middleware()came back expired and was served until the daily sweep a day later, and a row whose policy had been removed was dropped or kept depending on another slot's policy. The expiry stored with the row now decides, on every backend declaringCapability.TTL_INDEX(all three the library ships). - A saved slot another process changes is read back instead of written
over. On
PostgresBackend, each process kept the copy of every saved slot it read at its start, so a second process showed the old value, and its next save of that slot wrote the old copy back over the first process's change (for the scoped slot, every person's entry at once). When PostgreSQL's notification of another process's write arrives, persistence now reads the slot, puts it in the store, and dispatchesAPPLICATION_SLOTS_RELOADEDnaming it; a slot another process removed leaves the store. Every slot is read again after the listening connection reconnects and after a reopen. A slot with a write of this process's own still waiting keeps this process's value, which is written after the other process's. - A saved slot that
seed_initial_state()changes in place is saved. The hook is handed the store's state, soaccess_slot(state, ..., persistent=True)there changes it in place and no action announces the change. It was written only if a later action happened to copy the slot, and lost at a restart otherwise. Once the hook returns, the send now compares every saved slot with what is stored, for views that override it. - The install command in the missing-
aiosqliteerror works in every shell. It readpip install 'pycascadeui[sqlite]', and Windowscmdhands the single quotes to pip as part of the name. It now readspip install "pycascadeui[sqlite]", as the README and the docs do; their unquoted form failed in zsh, which reads the brackets as a file pattern. - The
on_restore()docstring no longer says a raise unregisters the panel. It never did: the exception is logged at ERROR, and the panel stays registered and clickable, showing what its message showed before the restart. To take a panel down there, callexit(). - The
DynamicPersistentButtonexample no longer shares its ids with the roles panel's buttons. The guide, the API reference, and the class docstring built ids of the formroles:<category>:<role id>, which the roles panel's own button also matches, and discord.py runs every class whose template matches a clicked id. Each click on a button copied from the example also ran the roles panel's handler, which replied that the panel was out of date or, for a category a roles panel uses, changed the role a second time. The example is now a ticket's Close button, and the docs nameroles:as taken. A button already posted from the old example gets its own class's answer alone: the roles panel's button leaves a click on a category no roles panel uses to the other class. - The wizard example's Background step can be edited after a short
backstory. It stored the backstory trimmed and prefilled the Edit modal
with it under
min_length=20, so a backstory with trailing blank lines opened a modal Discord refused, and the step could not be passed. It now keeps the text as typed and trims it only where it shows or checks it. - The lobby example answers a prefix
!lobbysent in a DM. It refused the open in silence; it now replies through the command's context, as the slash form already did. - A leaderboard hook that returns the wrong type raises a
TypeErrornaming the hook. Anon_leaderboard_empty()override missing itsreturnshowed a "Loading..." line that never went away. A value other than components or strings from it,build_title,build_header, orbuild_footerfailed inside discord.py withexpected Item not int, naming neither the hook nor the fix. - A leaderboard subclass that assigns
self.botbefore callingsuper().__init__()keeps it. The leaderboard's__init__reset it toNone, so no avatar resolved. An explicitbot=still wins. - A leaderboard whose
banneris adiscord.Fileuploads it wherever the board goes out. The file was turned into itsattachment://reference and dropped, so apop()back to the board named a file it did not carry, and every send needed the file passed tosend(files=)as well. The board keeps a copy of the file and its ownget_files()supplies it; a subclass that overridesget_files()adds its files tosuper().get_files(). A persistent board saves the file as its reference, and once restored, a send to a new message reads the upload back from the board's message. - A leaderboard's
discord.Filebanner keeps its description and spoiler. The banner was drawn from the file's reference alone, so its alt text was lost and a file sent withspoiler=Trueshowed unblurred. - A leaderboard built from
entries=rebuilds with the same entries. Given a generator,pop()back to the board showed it empty; given a mapping, a persistent board came back with its ids as strings. AMembergiven as an entry's id now stands for that id, where it rendered a broken mention and kept a persistent board from saving. - A leaderboard attribute set with
set_class_attribute()shows at the nextreload(). A newtitle, page size, or other board attribute waited for the entries to change, since the board skipped its rebuild on an unchanged entry list. - A section-mode leaderboard renders ids that are digit strings. JSON
hands ids back as strings, so a board fed scoped data after a restart
raised
TypeErrorfrom its avatar lookup on every render once a bot was bound, and missed the cached avatar of a member it could have shown. The avatar lookup and the backfill read such an id as the Discord id it names; an id that names no Discord user shows its two lines as text. - A card returned from
build_titleraises naming the hook. The masthead sits inside the rankings card, and the card failed insidecard(), whose message said to place it beside the card, whichbuild_titlecannot do. It is still aValueError; the message points atbuild_header()instead. - A leaderboard with
leaderboard_top_n = Noneandleaderboard_per_page = Noneshows every entry on one page. It raisedTypeErrorfrom inside the page build, naming neither attribute. - A leaderboard
card_colorof the wrong type is refused when the class is defined, naming the class, as its other attributes are. It was refused at the board's first send, namingcard.set_class_attribute()refuses it too. nav_inside_containerkeeps aContainersubclass'sinteraction_check. The wrapper copied the page's card into a plainContainer, so a check the subclass ran on clicks inside it stopped running; such a page now keeps the sibling layout. The wrapper also keeps a plain card'sid.nav_inside_containerkeeps the buttons outside a page card marked as a spoiler. The wrapper copied the spoiler onto the card that held the buttons, so the page's controls stayed blurred until the reader revealed the page.nav_inside_containerkeeps the buttons beside a page that fits only that way. The card holding page and buttons is one more component, so a page that fit Discord's 40 components beside its buttons raised once wrapped.set_page()refuses a page that is not an int before anything moves. A float firedon_page_changedwith it and then raised from the page lookup, and a str raised a comparison error naming no parameter.PaginatedRegion'sset_page()andshow_page()stored a float as the page.refresh_data()takes whatfrom_data()takes. A generator raised fromlen(); any iterable is now read into a list first. A mapping given to either raisedKeyErrornaming a slice; it raisesTypeErrornaming the method.- A paginator's formatter runs inside the view's theme. The formatters of
from_data()andrefresh_data(), and afrom_cursor()page fetched on a page turn, ran with no theme:get_current_theme()returnedNone, which a V1 formatter reading it failed on, and adivider()there stayed small.from_data()formats inside the theme the view will take (itstheme=, the class's, or the global default), and inside none for a class that overridesget_theme(), since the view does not exist yet; its cards still take the theme when the view renders. - A V1
PaginatedViewpage given as a dict ofembedsshows them. Onlyembedandcontentwere read, so the page showed nothing and the previous page's content stayed on screen. - A V1
PaginatedViewpage shows only itself. A page edit names only its own fields and Discord keeps the rest, so a text page after an embed page showed above that embed, and an embed page kept the previous page's text above it. A page turn now clears what the view's own previous page set and the new one does not, putting back what was passed tosend()for it. - Emptying a paginator's list shows that it is empty.
refresh_data([])andrefresh_pages(new_total=0)sent no edit, so the message kept showing the last page's items. APaginatedLayoutViewshows its "No pages." card; aPaginatedViewshows "No pages." with its indicator at "Page 0/0", and an empty one is sent that way too, where it sent three disabled buttons reading "Page 1/1" and nothing else. refresh_data()andrefresh_pages(new_total=)refuse page buttons with no room before the pages change. Crossingjump_thresholdadds three buttons to row 0 of aPaginatedView, wherebuild_extra_items()puts an item given no row. The refusal named the library's own button, the new pages were kept, and the buttons were left half built for the next render to send. It now names the row and the fix, and the pages and buttons stay as they were.set_class_attribute()refuses a paginator setting the view has no room for.jump_thresholdandauto_exit_buttonwere accepted on aPaginatedLayoutViewwhose pages could not hold the extra buttons, or aPaginatedViewwhose row 0 or row 4 could not, and the next page turn raised from the person's click. The call now raises, naming the setting and the page or row, and the view keeps its value. ATabView's and aWizardView'sauto_exit_buttonare checked the same way. A leaderboard, a menu, and a V2 tab view or wizard draw their content when they render, and the render refuses what does not fit.- A
PaginatedViewkeeps its page buttons in place on row 0 when they are rebuilt. A label, emoji, or style changed withset_class_attribute()rebuilt them behind an itembuild_extra_items()had put on row 0, so the row read Help, Previous, Page 2/3, Next. - A page turn, tab switch, or wizard step that raises names the page, tab,
or step turned to. When the one shown could not be drawn either (a
PaginatedLayoutView,TabLayoutView, orWizardLayoutViewwhose every page, tab, or step raises), the error of redrawing it replaced the first and named that one instead. - A
PaginatedLayoutViewpage may take the shapes a builder returns. A tuple of components, text inside a page's list, and a page callable that returns a tuple, text, or another iterable now draw (text in a list as aTextDisplay, text from a callable as a card, as a text page is), where each raised discord.py'sexpected Item not tuplenaming no page. A leaderboard'son_leaderboard_empty()takes a tuple too. button_gridand aTabLayoutView'stab_overflow_policytake more than five rows. Five rows is a V1 message's limit; a V2 message has only its 40-component cap, which each row's ActionRow and buttons count toward.button_gridtakes up to40 // (cols + 1)rows (6 of 5, 20 of 1), and arowsorcolsgiven as a bool raisesTypeErrorwhere it built a grid of one.TabViewkeeps the five-row limit.- What
build_tab_rows()returns is checked when the tab view is built, naming the hook and the row: a row of more than five buttons, a tab placed twice, an empty row on a V2 view, and a return that is not rows of buttons (a flat list, orNone). Each failed inside discord.py or at the send, naming neither the hook nor the tabs. An empty V1 row leaves that row free, as discord.py does. - A tab name that cannot be a button label is refused when the view is
built (
ValueErrornaming the tab). An empty orNonename made a button with no label, and one over 80 characters a label past Discord's cap; both reached Discord, or on V2 the send, naming the button. - A tab view keeps its own copy of
tabs=. A change the caller made to the mapping afterwards reached the view, and a tab removed from it raisedKeyErrorat the next render. - A V1
TabViewwhose tabs need more than five rows raises naming the count, the layout, and the fix: more than 25 tabs under"fill"or"balance", more than 21 under"pin_first"or"pin_last", or abuild_tab_rows()returning more rows. It raised discord.py'srow cannot be negative or greater than or equal to 5. A layout set later withset_class_attribute()gets the same message, where it blamed the view's other components. - A V1
TabViewkeeps its tabs ahead of the other buttons on their row whentab_overflow_policychanges. The tabs were laid out again behind an itembuild_extra_items()had put on the same row, so the row read Help, A, B. - A
tab_overflow_policythe tab view refuses is not set again bypop().set_class_attribute()raised and kept the previous layout, but the refused value stayed in whatpop()sets on the view it rebuilds, so returning to the view raised the same error. - A wizard step's or tab's builder may return what a frame hook returns. A
V2 builder's tuple, generator, text, or
Noneshows as its items, aTextDisplay, or nothing, where each raised inside discord.py naming neither the step nor the tab. A V1 builder may return a list of embeds, sent asembeds. Any other return raisesTypeErrornaming the step or tab, where text or a dict reached the request and failed there. A wizard'sbuild_progress_header()takes text and tuples too. - A V1
MenuViewwith more than 25 categories raises naming the count. Each category is one button and a V1 message holds 25, so a longer list raised discord.py'srow cannot be negative or greater than or equal to 5, naming neither the menu nor its categories. The Exit button counts toward the 25: with it, 25 categories raised the Exit's own error, which blamedbuild_extra_items(). AMenuLayoutViewpast Discord's 40 components names its categories andauto_exit_button, where the message advised showing a Section without its accessory, which would drop a category's button. - A V1
MenuView'sbuild_embed()may return a list of embeds orNone, and any other value raisesTypeErrornaming the hook. Text or a dict reached discord.py at the send, which raised naming neither. - A
MenuLayoutView'sbuild_header()andbuild_footer()take text, as the leaderboard's do. Text they return shows as aTextDisplay, where it raised discord.py'sexpected Item not str, and any other value that is not a component raisesTypeErrornaming the hook. A tuple or generator from either pattern's frame hooks, or from the leaderboard'sbuild_title(), is unpacked like a list, where it raisedexpected Item not tuple. add_item()names what it was given when it is not a component, and a coroutine by the function that made it (TypeError). On a V1 view discord.py raisedAttributeError: 'coroutine' object has no attribute '_is_v2', naming neither. A V1 paginator'spage_kwargs()that returns anything but a dict raises naming the hook; it failed inside the render.- A pattern subclass whose
on_load()does not callsuper().on_load()still shows the pattern's content. The pattern's own load runs after the override returns: a tab view's open tab, a wizard's step, a paginator's page fromfrom_cursor(), a leaderboard's entries, and an instance override (set_class_attribute) on a form, menu, or roles panel. A V2 tab view, wizard, or paginator sent a bare nav row, and a leaderboard an empty board. An override that callssuper().on_load()runs the load once, where it calls it. - A menu's or form's first message shows what an
on_load()override loaded. Both draw when they are built, and their load drew again only when an attribute they are built from changed, so abuild_header()reading data the override loaded sent the panel without it, and a value the override filled in showed "Not set", until the next draw. Their load now draws again after the override and keeps the new draw when it shows something different. When it shows the same, an item the override added stays. - A wizard opens on its first visible step, and its counter counts the step
on screen. A first step whose
conditionhid it was shown anyway. A step hidden by a control on it read "Step 1/3" with Back still enabled; it keeps its place in the count until the person moves on. - A
WizardViewstep with no builder no longer shows the previous step's embed. An edit keeps the embed it does not name, so reaching such a step by Next, Back, or a redraw left the last step's embed above its buttons. The step now shows the embedsend()was given, else none, as a paginator page that sets no embed does. - A wizard's
step_indicator_labelis checked when the class is defined. A string, a function written for(current, total)withoutself, afunctools.partial, and astaticmethodtaking the wrong arguments each failed at the first render naming neither the attribute nor the fix. Anasyncmethod now gets the message saying the label must be synchronous. A label the render reaches through the instance as(current, total)(aclassmethod, another object's bound method, apartialmethod) defines as before.set_class_attribute("step_indicator_label", ...)checks the value as the view will call it; it took a string or anasynclabel and failed at the next render. - A wizard step refused with a bare
Falsetells the person why. The defaulton_validation_failed()sent the validator's error as it was, and a bareFalse,(False, None), or(False, "")has none: Discord refused the empty message, and Next did nothing with no reply. It now sendsvalidation_failed_message("Finish this step first.", a class attribute;Nonesends nothing). A validator's own message still wins. - A wizard step dict with
"validator": Nonemoves on. It passed when the wizard was built and raisedTypeErroron the Next click, so the person could not leave the step.Nonereads as no validator, as it does for the other step keys. - A wizard step
conditiondeclared as astaticmethodin the class body is checked when the class is defined. Its signature could not be read from the descriptor, so one that cannot take the view passed, raised on every render, and was treated as visible: the step it meant to hide showed. - A wizard step
conditionthat reads an attribute the subclass sets aftersuper().__init__()no longer logs a WARNING per step when the wizard is built. The navigation row is built inside__init__, before the attribute exists; the first render runs every condition again and still warns for one that keeps raising. - A wizard's
steps=, a form'sfields=, a tab view'stabs=, and a menu'scategories=given as a generator are kept forpop(), which rebuilt the view from the spent generator: the wizard and form with no steps or fields, the tab view and menu raising for having none. - A form's edit-modal inputs are checked when the form is built. The
modal is built when Edit is clicked, so a field its inputs refuse (a
placeholder past 100 characters,
min_lengthabovemax_length, a default past 4,000) and atext_edit_button_labellonger than 45 characters, which is also the modal's title, raised there and the person got the error reply. The form now raises when it is built, and the label when the class is defined orset_class_attribute()sets it, as it does for an empty label, which Discord refuses as a title. - A form's edit dialog reopens on what the person typed. It reopened on
the stored value's text, which a parse can change:
0042typed into an integer field withmin_length=4stored 42, Discord refused the dialog prefilled with "42", and the field could not be edited again. The dialog now opens on the text typed, while it still parses to the stored value. A value whose text does not fit the field's length bounds, such as one set from code, opens the box empty. - A form's default submit reply lists the answers as the form shows them.
It printed the values mapping by field id, a
secretfield's answer included, and a long answer made a reply past Discord's 2,000-character limit, which Discord refused. It now replies "Submitted." with one line per field (a secret field's as dots), cut to the limit. - An empty
set_form_error("")inon_submit()keeps the form open. The form showed the error and then closed behind it, since the error drew for anything butNoneand kept the form open only when it was not empty. - A form shows a picked option by its label. A select or multi-select
field's line showed the option's
value, often an id the person never saw.valuesstill holds the value. - A form shows a long answer cut. A text answer near Discord's
4,000-character input limit made a
FormLayoutView's redraw after the Edit dialog raise at Discord's text cap, so the person got "Something went wrong" and the panel kept the old answers, and aFormViewgroup of long answers passed an embed field's 1,024 characters, which Discord refused. An answer past 100 characters now shows cut to 100 with an ellipsis wherever the form shows it, an error that quotes an answer quotes it the same way, and aFormViewgroup too long for one embed field goes on in the next.valuesand the Edit dialog keep the whole answer. - A form field whose control would take another control's
custom_idraises when the form is built, naming both: aselectnamedsubmitbeside the Submit button, or aFormViewselectx_yesbeside a yes/no fieldx. Discord refused the message at send, naming neither. So does a field id too long for its control's id, andset_class_attribute()turning onauto_exit_buttonbeside a select namedexitraises before the setting lands. - A select whose options repeat a value is refused before it reaches
Discord. Discord rejects it with HTTP 400 (code 50035, "the specified
option value is already used"), a rule its component reference does not
state, and the refusal came only after the click that rebuilt the screen
had done its work.
StatefulSelectandDropdownraiseValueErrorat construction naming the select, the value, and the two options that share it (a form's select by its field), and every send, refresh, and navigation edit checks each select in the tree, a rawdiscord.ui.Selectand options added after construction included. - A select given more than 25 options is refused before it reaches
Discord. discord.py refuses a 26th option only through
add_option(), so a rawdiscord.ui.Selectbuilt with a longeroptions=list reached Discord, which takes 25. Every send, refresh, and navigation edit raisesValueErrornaming the select;StatefulSelect,Dropdown, andchoice_row()already refused it when built. - A button or select given
custom_id=""is refused before it reaches Discord. discord.py keeps the empty id (onlyNonegets one generated), leaves it out of a button's payload, and sends it on a select; Discord takes 1 to 100 characters and refused both. The check that refuses an id over 100 characters now refuses an empty one too, naming the component, andModal(custom_id="")raisesValueErrorwhen it is built. - A form's select option without a
valuetakes its label as the value, as aDropdownoption does. It was sent with no value. - A
StatefulSelectgiven no options sends whatever its bounds. The disabled placeholder it shows is one option, and amin_valuesabove 1 kept from the filtered list it stood in for made Discord refuse the send. The bounds now fit the placeholder. - An
emoji_gridwithcell_sep=""keeps its letter labels apart. Two regional indicator letters that touch render as one flag, so"alpha"column labels read C and D as the Congo's flag. A zero-width space now goes between any two that would touch. - A link or premium button style is refused where it is given. Discord
takes those buttons only with a url or a sku_id and never with a
custom_id, and they send the bot no click, so one given a callback was sent with a generated id and refused with HTTP 400 naming no builder. Every builder's style, a pattern's*_button_styleattribute (andset_class_attribute()),StatefulButton,with_confirmation(),RoleCategory.button_style, and a roles panel'sformat_button_style()raiseValueErrornaming the style and where it was given; a link isLinkButton.StatefulButton,with_confirmation(),RoleCategory, andformat_button_style()also refuse a style that is not aButtonStyle, which failed at send. - A button with neither a label nor an emoji is refused before it reaches
Discord. Discord rejects it with HTTP 400 ("label: This field is
required"), naming a position in the request rather than the button.
Every send, refresh, and navigation edit raises
ValueErrornaming the button, for V1 and V2 views and withvalidate_placement = False; an empty label, or one of whitespace alone, counts as none.button_rowandtab_navrefuse such an entry when they build the row. Premium and link buttons are left alone. - Text of spaces alone counts as empty. Discord refuses a text display, a
button label, and a select option label made only of spaces, as it refuses
empty ones. The placement check,
card()and the other text builders, a tab's name, a form option's label, and a roles panel's label now treat text of spaces, tabs, or line breaks alone as empty and raiseValueErrornaming the component. Wider spaces, such as a no-break space, are left for Discord to judge. - An emoji Discord refuses is refused where it is written. Discord
answers HTTP 400 ("Invalid emoji") for a button or select option whose
emoji is empty, a plain word such as
"fire", or a custom emoji whose id discord.py cannot read:"<:fire:12345>", with an id under 13 digits, is sent whole as a name. Every button the library builds,StatefulSelectoptions (Dropdownincluded),button_row,tab_nav,link_section,LinkButton,Collapsible,with_loading_state(), a roles panel'sformat_button_emoji(), and the emoji class attributes raiseValueErrornaming the component; the placement check refuses a raw discord.py button or option, andopen_modal()a raw select's option. A well-formed custom emoji id is left for Discord to judge.is_emoji(), and with it theemoji()validator, now answersFalsefor a custom emoji token whose id is under 13 digits. - A select Discord refuses is refused before the send or edit. Discord
answers HTTP 400 for a bound outside its ranges (
min_values0-25,max_values1-25), a string select with no options, and a select starting with more defaults than itsmax_values:default_valueson a user, role, channel, or mentionable select, and options markeddefaulton a string select. Every send, refresh, and navigation edit now raisesValueErrornaming the select, for V1 and V2 views and withvalidate_placement = False, and a form'smulti_selectfield with more default values than itsmax_valuesraises when the form is built. ACheckboxGrouporFileUploadwith amin_valuesof 0 whilerequiredisTrue, and a raw discord.py checkbox group, file upload, or string select added to aModalthe same way, raiseValueError: Discord refused the modal when it opened. - A File component naming a web address is refused. Discord refuses it
with HTTP 400 ("does not support arbitrary external urls"); the File
component shows only a file uploaded with the message.
file_attachment()raisesValueErrornaming any other URL, and a rawdiscord.ui.Filenaming one is refused by the placement check before the send or edit. Pass thediscord.Fileitself, or show an image from a link withgallery()orimage_section(). - Button and select text over Discord's caps is refused on a V1 view too,
and on a V2 view with
validate_placement = False: a button label over 80 characters, a select placeholder over 150, and option text over 100. Only the V2 placement check knew these caps, so on every other view the text reached Discord and was refused with HTTP 400 naming no component. A button label set ahead of the send is checked where it is set: a*_button_labelclass attribute past 80 characters (the paginator's, the wizard's,PaginatedRegion's,refresh_button_label) when the class is defined orset_class_attribute()sets it, and a roles panel'sformat_button_label()when its card is built, naming the role. A label a control shows only after a click is checked when the control is built: a toggle's other label, everycycle_button()label, aCollapsible'sexpanded_label, aToggleButton's toggled label (the default one too, its label with a check mark), andwith_loading_state()'sloading_labelandwith_confirmation()'sconfirm_labelandcancel_label, checked when the wrapper is applied. The send saw only the label on screen, so the click that showed the long one was refused and the control stopped answering. PaginatedRegion,Collapsible, andToggleGrouprefuse akeytoo long for their ids at construction, naming the id and how short the key must be (aToggleGroupid also carries the option's label). A V1 view sent the long id and Discord refused it with HTTP 400 naming no component; a V2 view was refused at send, naming the id rather than the key.- A
Collapsiblewhoserevealreturns a tuple, a generator, orNonerenders it. Only a list was unpacked, so a tuple reached the host as one entry andadd_item()orcard()raised "expected Item not tuple", naming neitherrevealnorCollapsible. Any iterable of components is unpacked now,Nonereveals nothing, text shows as aTextDisplay, and anything else, a dict included, raisesTypeErrornamingCollapsible.reveal(). - A
CollapsibleorPaginatedRegionbuilt insidebuild_ui()opens and pages. Built anew on every redraw (inbuild_ui(),on_load(), or a tab or step builder), it came back closed or on page one each time, so a click changed only the one it replaced and the panel never moved, with nothing logged above DEBUG. One made during a render now takes the open state or page of the one the view last showed under the samekeyin the same tab or step, and a click hands its change to the one the redraw makes. A collapsible givenexpanded=takes the view's value, as before. So does each one a build makes after setting the state itself withexpand(),collapse(), orset_page(): it starts as built, so a picker the build opens only while its own flag is set still closes. When the build sets the state back over a click (a givenexpanded=,collapse(), orset_page()), one WARNING per view class and key names the fix. - A
CollapsibleorPaginatedRegionin a pattern's own hook opens and pages. Placed throughbuild_extra_items()(paginator, tabs, wizard), a leaderboard'sbuild_header()orbuild_footer(), or a V2 paginator page, it answered its click and the panel never changed, even built once: the patterns kept what those hooks drew. Its click now runsbuild_extra_items()again, rebuilds a leaderboard's pages (fetching the entries, asreload(force=True)does), or composes the page again. A view whose render leaves the clicked controls on screen logs one WARNING per view class and key naming the fix. progress_bar()andrender_progress()refuse what they cannot draw. A NaN value or maximum drew a full bar at 100%; it raisesValueError. Awidththat is not an int, or afilledoremptyglyph that is not a str, failed with Python's own message naming neither parameter, and two int glyphs drew the bar as a number; each raisesTypeError.button_row,tab_nav, andkey_valuekeep every pair. The pairs were folded into a dict, so two sharing a label made one button, tab, or line, and the first was dropped unseen.- A
choice_rowdropdown takescustom_id=None, as its button form does. It raised discord.py'sTypeError(expected custom_id to be str). It refuses acustom_idover 100 characters where it is given, as the button form does; a persistent view refused one only at send, naming the id and not the builder. - A
choice_rowdropdown whose options share a value gives that value once.on_selectreceived it once per option picked, and a single-select marked every option carrying the selected value as chosen, sending a select that holds one pick with several defaults; it now marks the first. - A
choice_rowdropdown pick naming an option the control no longer has runs nothing and is answered with the view's current render. A persistent view keeps a dropdown's id when its options change, and the option values were positions, so a pick on a copy of the message drawn before the change reported whichever option now sat there, or raisedIndexErrorfrom the builder's callback once the list had shrunk past it. A multi-select pick that names one such option is dropped whole, and the store records noCOMPONENT_INTERACTIONfor it. Options with akey(see Added) are found by it wherever they moved. - A
choice_row(multi=True)toggle sent while another is being handled keeps the other's result. The toggle ran on the button of the render the other replaced, so the selection it handedon_selectlacked the other toggle and took it back off the screen. choice_row(multi=True)buttons, achoice_rowdropdown, and V1PaginationControlsrebuilt on each render keep their ids across renders. Each id was derived from an object rebuilt with every render, or from the selection its render showed, so outside a persistent view a render gave those controls new ids, and a toggle, pick, or page step made from the screen that render replaced was dropped as a click on a control the view no longer had.ToggleButton,toggle_button(), andcycle_button()show their new label without arefresh(). Each changes its own label and style on a click, but the click was acknowledged bare unless the callback redrew, so the person kept seeing the old label, and aToggleButtonwith no callback never showed its flip. A click the callback leaves unanswered is now answered with the view's current render, as a select pick is, at the same one request, and a reply throughrespond()goes out after it. A click the library acknowledged first, withack_firstor a callback slower thanauto_defer_delay, is redrawn with an edit of the message, inside arefresh_cooldown_mswindow as well, and after a callback that raises unless the raise cut a rebuild short.choices()checks each pick of a list. ACheckboxGroupormulti_selectvalue is a list, never one of the allowed values, sochoices()refused every pick.min_lengthandmax_lengthcount a list's picks, with "Pick at least 2" and "Pick at most 1" as their messages. They counted the characters of the list's text, so one pick passedmin_length(2)and two failedmax_length(1)as "Must be at most 1 characters".validate_field()checks its validators as an input does when it is declared, naming the field. A validator passed bare raised "'function' object is not iterable", and one taking the wrong arguments raised from inside the call.- A view's
theme=that is not aThemeis refused when the view is built, naming the fix.theme="dark"built and then failed the first send with anAttributeErroronget_style. - A view switching between two themes of one name repaints. Its selector
carried the theme's name alone, so a
get_theme()buildingTheme("custom", ...)from a person's colours never repainted a view with astate_selector. It carries the styles too. apply_to_embed()prefixes the header emoji once. An embed themed on every render gained another emoji each time.- A
get_theme()override may read what the subclass sets aftersuper().__init__(). APaginatedLayoutViewwith pages, aFormLayoutView, and aMenuLayoutViewdraw in their constructor, and calledget_theme()there, so such an override raisedAttributeErrorfrom the constructor. That draw now runs in the class's theme, or in none for a class that overridesget_theme(), and its cards take the theme at the send.get_current_theme()called during that draw returnsNonefor such a class. - A
RoleCategorycolorof the wrong type is refused when the category is built, naming the category. It was refused at the panel's first render, namingcard. An int becomes adiscord.Colour, as it does oncard(). - A role category named with no ASCII letter or digit works. Its slug was empty (Cyrillic, CJK, or an emoji alone), so its buttons' ids never matched a click, so no click on them did anything, and two such categories were refused as sharing one slug. Such a name now takes a slug made from a digest of itself, the same in every process; every other name keeps its slug, so posted panels keep their buttons.
- A member's quick clicks on two roles of one category leave the roles the category allows. Each click applied the category's rules to the roles the member had when it was sent, so Red then Blue in an exclusive category left both, each reply claiming a clean switch, and removing two roles of a required category at once left none. A member's clicks in one category now take turns, and a click that waited reads the member's roles from Discord first.
- An exclusive swap adds the new role before removing the old one. When Discord refused the new role (one above the bot's), the member was left with no role in the category, required or not.
- A click on a roles panel subclass runs the subclass's replies and
hooks. Categories are filed under the class that declares them, so a
subclass that changed
assigned_messageor anon_role_*hook had its panel's clicks answered by the parent. A click now uses the class of the live panel on the clicked message, and the declaring class when no panel is live there. - A role button whose label is empty or
Noneshows its emoji alone. It showed the category's slug. - A
RoleCategorythat lists one role under two labels is refused when it is built, naming both labels. It was refused when the panel was sent, as a duplicate custom_id, with advice aboutkey=that means something else on a category. - A roles panel too big for one message names the category that does not fit, with the counts and the fixes that apply to a role panel. The message came from discord.py's 40-component check and named a Container the panel's code never built.
- The inspector's view and session selects act on the one picked. Their option values were positions in the list, which re-renders as views open and close, so a pick made as the list changed selected whichever view or session had moved into that place, and Exit Selected closed it.
/cascadeui scopedcountsuser_guildbuckets asuser_guild. It looked for a key shape the library never builds, so every one was counted underother.InspectorView(scope_guild_id=)also takes a guild for its id, where it showed empty Views and Sessions tabs. A slot keyed by something other than text, such as guild id ints, is counted underother, where the command raised.- The inspector opens, and
/cascadeui flushreports its size, when a slot is keyed by a tuple. Both measured the state withjson.dumps, which refuses a tuple key, so the inspector's Overview tab raised and the flush command answered with an error after its write had landed. - The inspector's Exit All closes only the views its Views tab lists. On
an inspector scoped to one server it closed every live view the bot had,
in every server and other people's inspectors with them, while its label
counted only that server's views.
/cascadeui exitallwas already scoped. /cascadeui subscriberssays what each filter hears. A view whosesubscribed_actionsis empty, the default, hears only its own undo, and the command listed it as hearing all actions; it now says "its own undo only", and "all actions" forNone. A filter that lists actions is shown by their names, sorted and cut to a line, where it printed only how many, which could not say whether a view hears a given action.- Smaller
/cascadeuioutput fixes./cascadeui middlewarenames a function middleware, where it printedfunction. The inspector's History tab and/cascadeui historyprint-for an action with no source, notNone. A guild-scoped inspector titles its View Registry card "(all guilds)", since its counts were never scoped. The Config tab's Persistence card names the Registry and Application namespaces, where it printed the table each one saves to. The inspector shows session ids, class names, action types, and slot and key names as written: a session id from a view defined in the bot's run script (__main__.Panel:user_1:...) showed as an underlined "main". The History tab leaves out the two actions that opened the inspector, which topped its list every time it opened. The History, Sessions, and Performance tabs show times as Discord timestamps, which each person reads in their own time zone; they showed the UTC clock time with no zone named. The Export Report keeps UTC and its tables say so. with_retryraises as soon as the last attempt fails. It waited out a full backoff after the last failure before raising. The wait stays capped atmax_backoffhowever many retries there are, where the wait before retry 1024 raisedOverflowError.with_retryandwith_error_boundarytake afunctools.partialor a callable object.with_retryread the function's__name__for its log line, so when such a function failed the caller gotAttributeErrorinstead of the function's own error, andwith_error_boundaryraisedAttributeErrorwhen applied.with_error_boundarylogs a failure's traceback once. It logged it at ERROR and again at DEBUG.- A background task that raises is logged with its traceback. The task
manager logged the error's message alone, and because it retrieves the
error, asyncio's own "Task exception was never retrieved" line, which
carries the traceback, never appeared. That includes every task a view
starts with
create_task(). cascadeui.testing.stub_interaction()carries every attribute the library reads off an interaction. A view could not be built with it (no attribute 'guild'), and a modal callback that refreshed its view failed ontype. It now carriesguild(Noneoffline, withguild_idholding the id),type,message,data, and the response and original-response edits, recorded inedits. Itsresponse.defer()records the type discord.py records: a message update for a component or modal interaction (a channel message when called withthinking=True), where it recorded a channel message for every defer. Itsresponse.edit_message()sends nothing for any other interaction type, as discord.py's does. A reply with no text (an embed alone) is recorded inrepliesas"", where it wasNoneand broke"text" in replyover the list.- The test stub refuses a call discord.py refuses before sending. Its
response and followup took any keyword or positional, so a test passed over
a misspelled keyword,
delete_afteron a followup,embedbesideembeds, or more than ten embeds, each of which raises in production and leaves the reply unsent. Each call is now checked against the discord.py method it stands for, so a test that passed over one fails, as the call does. Itssend_modal()recorded anything it was given; it builds the modal's payload as discord.py does, after the answered check, so a value that is not a modal raisesAttributeError. cascadeui.testing.stub_client()logs nothing when built. It was built without the guilds intent, and discord.py warns "Guilds intent seems to be disabled" for every such client, so a suite counting WARNING records counted each test client. It connects to nothing, so the intent changes nothing else.- The components reference has an entry for
file_attachment(), and givesdivider()andgap()theirlarge=Nonedefault, which follows the theme's spacing (it gave bothlarge=Falseand small spacing).
[3.14.2] - 2026-10-11¶
Added¶
REGISTRY_PRUNEDnames the message each pruned row was on. Its payload carriesmessages, each pruned key mapped to themessage_idandchannel_idits row named, so a bot that keeps its panel's message id can tell whether a pruned row was its current panel or an earlier post under the same key.
Changed¶
- A stalled click edit logs at INFO, at most once an hour per view. A
click's one-request edit that outlasts
auto_defer_delay - 1.0seconds was logged only at DEBUG, so a bot logging at INFO showed nothing when its panels stalled. A stall now logs at INFO, and the view's stalls in the hour after it at DEBUG. send()callson_bindfor a persistent view posted through a channel. It bound only a view whose interaction or command context carried the bot, so a panel posted withcontext=channelneededawait view.on_bind(bot)before its send. It now binds the client the channel belongs to, so that call can go, unless code beforesend()reads whaton_bindsets. Code that keeps it sees the hook run twice, which an idempotenton_bindalready allows.DISCORD_CALL_ERRORSincludesasyncio.TimeoutError. discord.py sets no timeout of its own, so a request Discord never answers ends after aiohttp's five-minute default as a plainasyncio.TimeoutError, which is not anaiohttp.ClientError. Code that catches the tuple now catches that timeout, and with it anyasyncio.wait_fororasyncio.timeout()expiry inside the sametry; a block that handles its own timeout differently catchesasyncio.TimeoutErrorin a clause above the tuple.reattach()orprune_unreachable()logs a warning after waiting a minute for a walk already running. A hook inside one that awaited the other through a task of its own (asyncio.gather, orwait_forbefore Python 3.12) waited forever with nothing logged, which during the boot pass kept the bot from becoming ready. The two still wait on each other; the warning names the cause.
Fixed¶
- A panel no longer stays stuck on a page after a slow page turn. A page
turn whose edit outlasted its time bound was given up on, but Discord could
still apply it after a later page turn, leaving one page on screen while the
view held another. A press leading to the page the view already held rebuilt
the render it had sent and skipped the edit, and from 3.14.0 a press on a
control the view held disabled was dropped, so when every button left on
screen did one or the other the panel stayed stuck. A click or modal
submission that a skipped render leaves unanswered, and a click on a control
the view holds disabled, each got a bare defer. Both are now answered with
the view's current render, which costs no extra request and puts the screen
right. This needs
serialize_interactions(the default). ADynamicPersistentButtonclick keeps its plain acknowledgement, as does a modal submission that arrives while a click on the view is still being handled. - A view posted through a channel finds its bot. A channel carries no
.bot, so three steps that looked for one found no client for a view sent withcontext=channel: a bot that setsClient(allowed_mentions=...)had those rules on the post and lost them on every later edit of a V2 view; a persistent panel posted again left an earlier run's message live instead of closing it byexit_policy; and with no persistence installed, aDynamicPersistentButtonclass such a view carried could stop routing on other messages once the view stopped. These steps now read the client off the channel, as discord.py's own send does. - A request Discord never answers is handled like a dropped connection.
aiohttp's total timeout escaped the library's handlers:
respond()raised it into the calling callback,open_modal()raised it instead of returningFalse, the defaulton_instance_limitraised it out of a command'ssend(), a role panel click skippedon_role_error, and a restore logged the panel as failed, with a traceback, instead of unreachable. Each now treats it as it treats a dropped connection. A role panel's default error notice names the timeout, which carries no text of its own. - The unreachable sweep restores a panel it finds reachable again. A row
that
prune_unreachable()or the daily sweep (prune_unreachable_after_days) found reachable again had its stamp cleared, but its panel stayed dead until the next restart or areattach()call. The sweep now restores it in the same pass, andrecoveredlists only the rows it restored. A row whose restore fails is listed underkeptwith a new stamp, so the next sweep tries it again and its age counts from that check. A panel the sweep restores runson_restorewhile the bot is up, as after areattach()call. - The unreachable sweep keeps a row whose re-check says nothing about its message. A re-check that failed on a dropped connection, a rate limit, a server error, or a channel type the installed discord.py cannot read counted as still unreachable, so an aged row was deleted on a failure that says nothing about its message. Such a row now waits for the next sweep. A re-check that failed because the bot was closing logs at DEBUG, as a restore does, instead of a WARNING with a traceback per row.
- A panel whose restore fails during its registration leaves nothing
behind. A middleware that raised while a restored panel registered left a
view row and a session naming it in the store, which the inspector listed as
a ghost. When
on_bindraised, a panel subscribed to every action rendered onto its message before it was discarded, and workon_bindhad started kept running. The restore now rolls all of it back, and does the same when it is cancelled. A reattach pass cut off by a cancel (asyncio.wait_foraroundreattach(), for example) left the panels it had already restored live but never repainted or recorded, so a laterreattach()skipped them; it now repaints and records them before the cancel ends it. - A restart in the same process restores a panel whose row outlived its
view. A screen pushed from a restored panel that timed out without
returning to it (one with its own
on_timeout()) kept the panel's row with nothing holding its key, and a restart in the same process skipped that row until the process itself restarted. - A persistent panel posted again reports an earlier run's message it could
not close. A failure to close the message an earlier run's panel left under
the key (a 403, a server error, no answer from Discord) was taken for the
message being gone and passed over in silence, while its buttons stayed on
screen answering nothing. It now logs a WARNING naming the message and
channel; only a 404, or a bot that has closed, stays quiet. The message is closed on a task of its
own, each request bounded by
edit_timeout, sosend()no longer waits for it (a request Discord never answered held it for five minutes) and a cancel of the send no longer leaves it open. A channel the client has not cached is fetched instead of skipped. - A
prune_registry()that fails part way reports the rows it deleted. The rows deleted before a failing delete stayed in the store's mirror of the registry and noREGISTRY_PRUNEDnamed them. They are now dropped from memory and announced before the error is raised, and a reattach pass whose prune fails part way lists them underremovedinstead offailed. - A role panel no longer reports a failed toggle when only a hook failed.
A Discord error raised by
on_role_assigned,on_role_removed,on_role_swap, oron_role_required_blockreachedon_role_error, which told the member the change had failed: after the role had changed, or, fromon_role_required_block, when no change was made. Only the role change itself is caught now, and a hook's own error propagates like any other. - The
reload()reference no longer describesDEFERREDas the throttle alone. A send, a navigation, or a rate limit can hold the edit afteron_load()has run, so the value does not say whether it ran; the reference now says so. - The
PersistentRolesLayoutViewreference and guide no longer say an unchanged panel's restore costs no API call. A restored view has no render-hash baseline, so the defaulton_restoreships one edit per panel on every restore.
[3.14.1] - 2026-10-10¶
Added¶
StateStore.unsubscribe(subscriber_id)removes a subscriber added withsubscribe(), which had no public counterpart. An id that is not subscribed is ignored. A view's id raisesValueError, since a view whose subscription was removed could no longer be closed byexit().safe_defer(interaction)defers an interaction unless something has already answered it, for a callback whose work routinely runs long, so the click is answered at once instead of when the ack backstop fires. The guides have taught it since 3.0.0 under the private name_safe_defer().REGISTRY_PRUNEDnames the call that pruned in a newsourcefield:"reattach","prune_unreachable", or"prune_registry". A subscriber that takes a reattach pass's deletions fromtotal_reattach_summarycan skip the dispatch whosesourceis"reattach".
Changed¶
- A render that finds its view closed returns
RenderOutcome.CLOSED.NO_MESSAGEcovered both a view that closed itself (an exit, a timeout, a navigation, a restart) and a message deleted out from under the view, so a caller could tell them apart only by readingis_finished()before the deletion's teardown ran.reload()and a page, tab, or step render whose turn came after the close, and a render after the view's own close deleted its message, now returnCLOSED. A message deleted out from under the view still reportsNO_MESSAGE, on every render after it as well. Code comparing those outcomes withNO_MESSAGEneedsCLOSEDtoo, and code that lists every outcome has one more. - A render after a select pick ships even when the tree is unchanged.
The client shows a pick until the message is edited, and a render that
redrew the same tree as the last one was skipped, so a pick the callback
refused stayed in the dropdown. After any pick on the view's own message,
accepted or refused, the next render that lands now ships. A select whose
options mark no
defaultthen shows its placeholder again, so a screen that keeps a pick for a later step marks the chosen optiondefault. - A view's timeout counts from its last click or its last landed post or
edit, whichever way the view was sent. A card with nothing to click
sent to a channel or as a followup never timed out, staying registered
with its state and instance slot until
exit(), although the views guide said its timeout cleaned it up. One sent as a command's response timed out after its send while its edits still landed. Both now time outtimeoutseconds after their last click or landed post or edit. A buttonless view edited less often than itstimeoutnow closes between edits, so one meant to stay up setstimeout=None. - The unreachable sweep reports a deleted panel as
reason="gone".prune_unreachable(), and the daily sweep thatprune_unreachable_after_daysstarts, deleted rows whose channel or message returned a 404 underreason="unreachable", together with rows that only aged past the cutoff. They now arrive in aREGISTRY_PRUNEDof their own withreason="gone", as a reattach pass reports them, and the result's newgonelist names them.prunedstill lists every deleted row. A subscriber that acted on"unreachable"for deleted panels handles"gone"as well. Areattach()pass reports its deletions as"gone"too and lists them intotal_reattach_summary["removed"], so act on each key from one of the two. The newsourcefield tells the dispatches apart.
Deprecated¶
_safe_defer()is nowsafe_defer(). A call to the old name keeps working and warns with aDeprecationWarning. An override of the old name keeps working too: its class definition warns, and the library calls the override through the new name wherever it called the old one. The old name is removed in 4.0.0.
Fixed¶
- Calling
connect()on a bot discord.py has closed no longer reopens persistence. By default discord.py closes a bot only on a gateway close code it cannot recover from, such as a rejected token, and a bot it closed cannot connect again:clear()resets its state, not the HTTP session the close shut. A retry loop callingclear()andconnect()still reopened persistence and tried to restore every stored panel through the closed client, logging an error for each, beforeconnect()failed. Persistence reopens for the new bot a restart builds, as before. A gateway drop discord.py resumes never closes the bot, so views stay live through it. - A
RuntimeErroryour own code raises while the bot is closing logs as an error. Raised from a render, anav_rebuildhook, a re-send closing the message it left, or a persistent panel's restore (itson_bind()or a kwargs migrator), it was logged at DEBUG once the bot had closed, as if it were aiohttp refusing a request on the closed session. A restore also left the panel out of the summary, to be retried by the next pass, instead of listing it underfailed. Only that refusal logs at DEBUG now. REGISTRY_PRUNEDreportsreason="gone"when reattach deletes the row of a panel whose channel or message no longer exists. It reported"explicit", the reason an operator's targeted prune gets, so a subscriber could not tell the two apart. A subscriber that acted on"explicit"for these removals handles"gone"as well.total_reattach_summary["removed"]reports the same removals, so act on them from one of the two.- A persistent view whose
on_bindoverride skipssuper()keeps its bot at send. The restore stored the bot on the view before calling the hook and the send did not, so such aPersistentLeaderboardLayoutViewposted without avatars until the next restart. One sent through a channel, which finds no bot to bind, now resolves avatars through the botPersistenceMiddlewareholds. Theon_bindexamples in its docstring and the persistence guide assignedself.bot, which the leaderboard exposed read-only, so a copied example raisedAttributeError. The leaderboard'sbotnow accepts assignment, checked like thebot=argument, and the examples callsuper().on_bind(bot)first. - A persistent panel whose restore failed no longer runs its buttons on a
dropped view. A restore that failed after the panel was attached to its
message, such as an
on_bind()that raised, left the message routing clicks to a view the library had already dropped: each button ran its callback, and the panel never redrew. Its buttons now answer nothing until areattach()or the next restart restores it, as when a restore fails before attaching. - A
PaginatedRegionpage turn or aCollapsibletoggle no longer renders while a host withbuild_uireloads. It built the host's tree from whaton_load()had loaded so far. It now waits for a reload or a state render the host is already running in another task, as a tab or wizard step render does, and sends nothing if the host closed while it waited. One called from inside that reload or state render does not wait: from the host'son_load()oron_state_changed(), or from a task either of them started, such asasyncio.gather(region.show_page(n)). On aTabLayoutViewhost or one that renders inon_load(), that call waited forever. It now renders, except inside theon_load()of a host that renders there, where it raisesRuntimeErrornamingset_page(). Two page turns gathered from one render built the tree at the same time and one failed on a duplicatecustom_id, and a page turn the render started without awaiting it kept building beside the next reload or state render. They now build one at a time. A build still running when the host closed no longer goes out over a closing card sent throughrefresh()after the build began. - A tab, wizard step, or page still loading when its view closed shows
what it loaded. The close froze the tree as the render had left it, often
the tab row with nothing under it, and the render, finding the view
closed, sent nothing. A tab or step render now runs its builder before it
touches the panel, so the close freezes the tab or step on screen, and the
finished render goes out after the close, with its controls as the close
left them. So does a
reload()whoseon_load()outlasted the close. Like any late render, it never covers another edit asked for after it began: a closing card sent throughrefresh(), before the close or after it, stays on the message. A card sent withmessage.edit()bypasses the library and can be covered. A V1 render still sends its embed when that later edit changed only the controls. - A cursor paginator's page turn overtaken by another shows no page it has
not loaded. The second turn moves the page before it waits for the
first, and the first then rendered that page unfetched:
PaginatedLayoutViewshowed its "Loading..." card andPaginatedViewkept the old page's text under the new indicator, until the second turn rendered. The first turn now loads the page the second one named. Page turns overlap when code callsset_page()while one runs, or withserialize_interactions = False. - A failed push or pop puts the view back on its message when its
nav_rebuildraises or itson_timeout()keeps it. When the edit to the new screen stalled or failed partway, the view redrew itself through itsnav_rebuildhook, and a hook that raised left the message on the discarded screen, whose buttons answered nothing, while the view stayed live on no message. The view's components, as they were before the hook, now go back. A V1 message keeps the embed the new screen may have shown until the view sends one. An exit that closes the view before its redraw has run freezes those components too, where it froze whatever part of them the hook had rebuilt before it raised. When the view's timer ran out during the push, the redraw was left to the timeout's freeze, which anon_timeout()override that keeps the view never makes. The view now redraws itself. A timeout freeze that found nothing left to disable, and a redraw inside arefresh_cooldown_mswindow, dropped the embednav_rebuildnamed, so the message could keep the discarded screen's. Both now send it. - An exit whose message is deleted while its redraw runs logs no error.
When a deletion landed while an exit awaited
nav_rebuildfor that redraw, the exit loggedError cleaning up messageat ERROR. It now ends quietly, as a timeout already did. - A failed push or pop no longer covers what the view sent while it was
stalled. The redraw after a failed push went out over anything
the view's own code had sent meanwhile: an embed passed to
refresh(), a tree it rebuilt, a state change it rendered, or the message a send queued behind the push posted. A timeout or exit that closed the view during the push froze the redraw in its place. The redraw stands for the screen from before the push, so it now restores only what nothing newer has set, including content that lands whilenav_rebuildruns, and a V2 view'snav_rebuilddoes not run once the view has rendered a new tree since the push began. - A render on an ephemeral view showing its Continue button keeps the
button. A
refresh()from the caller's own code after the handoff armed, such as a modal callback submitted late, shipped the rebuilt panel over the button, and the view, still armed, took no render that could put the button back, so the panel stopped working at the token's end with no way to continue. The button now goes back in place of the rebuilt panel. An arming edit that failed with a Discord server error left the panel without its button. It now tries again, as one dropped in transit does. - The panel a Continue sends no longer arrives frozen. The Continue
deletes the old message, and Discord can report that deletion before the
delete call returns, or delete the message while the reply is lost. The
old view then ran
on_message_delete()as if the message had been deleted from outside, and that close followed the hand-over to the replacement, which showed the right content with its buttons disabled. An edit of the old view coming back 404 at that moment did the same. The Continue's own delete no longer reacheson_message_delete()oron_message_gone(). - A Continue that hits an error after posting its replacement still
hands the panel on. A middleware raising during the hand-over stopped
it partway: the old panel stayed live beside the new one, its message was
never deleted, and its Continue button ignored every later click. Each
step now logs its error and the next one runs, and an
exit()override that raises on the old view is logged instead of failing the click. A Continue cancelled once the replacement is posted also finishes the hand-over, and one cancelled before that leaves its button working. - A view attached to an ephemeral panel while its Continue runs moves to
the replacement. One sent with
parent=while the old message was being deleted attached to the old view, whose exit then closed it. exit_children()waits for a Continue running on the view. Called meanwhile, it closed the attached views the replacement was about to take over.send()waits for a Continue running on the view. Called meanwhile, it posted the old view again on a message the Continue then deleted, and returned that message as if a live panel had come of it. It now waits for the Continue and then raises if the Continue handed the panel on, as it does on any view that has handed its panel on, and raises at once when called from inside the Continue (frombuild_reopen_view()or the replacement's own hooks).- The Continue button works on a view with
instance_limit,auto_register_participants = True, and other users inallowed_users. The per-user limit counted the view being replaced against each participant, so every Continue was refused and the panel ended when its token ran out. - An ephemeral panel with the Continue handoff keeps
timeout=None. discord.py gives an ephemeral view'sNonea 900-second timeout, so the panel ended while its Continue button still showed, a click on the button then failed, and sending the same view again turned the handoff off. The declaredNonenow comes back once the message is posted or the send fails, and the panel lives untilexit()or a restart, including one the user dismissed, which the views guide covers. An ephemeral view that declines the handoff keeps discord.py's 900 seconds. - A confirm prompt takes one answer.
confirm_sectionand the V1ConfirmationButtonsranon_confirmoron_cancelfor each click of a double-click, so a delete or a payment ran twice, and ran a Cancel sent from the same render after the Confirm had acted. Once one button's callback runs, a click on either button sent before its result was on screen is now dropped. Awith_confirmationprompt takes one answer the same way: a second click on either button, sent before the first answer landed, ran the action again or ranon_cancelafter it. - A stateful button or select in a plain discord.py view works as a plain
one. After running its callback the click reported itself to a state
store the plain view does not have and raised
AttributeError, so every click logged an error, and one whose callback sent no reply showed "This interaction failed". This includesconfirm_sectionand the other builders made of them. Withowner_only=Trueand auser_idon the plain view, another user's click is refused and left unanswered, as the view's owninteraction_checkwould refuse it. That refusal raisedAttributeErroras well. subscribe()refuses a view's id. Subscribing under it replaced the view's own subscription, so the view stopped rendering on state changes with nothing raised. It now raisesValueError.- A closed view stays closed when code subscribes under its id. Whether
a view was still open was read from every subscriber, so such a
subscription opened it again: another
exit()on it ran the teardown a second time and removed the subscriber, and a view whose removal a middleware refused counted against its instance limit and showed as live in the inspector. - A second
subscribe()under the same id compares the new selector with its own values. The replacement kept the last value the replaced selector returned, so its first change went unannounced whenever the two values happened to match. set_class_attribute("subscribed_actions", ...)works on a view whose class keeps the default. The base class did not declare the attribute, so the override raisedValueErrornaming an unknown attribute unless the class body set one.- The components guide gives the
"numeric"grid label preset as 1 to 10. It said 0 to 9, and the preset renders the keycaps 1 through 10.
[3.14.0] - 2026-10-06¶
Breaking¶
- A
rebuild=ornav_rebuildhook that calls the destination'sreload()orload()now raisesRuntimeError. The destination'son_load()has already run by then, so the call loaded it a second time and edited the message twice. Remove the call, and load what the hook needs before navigating, as a constructor keyword or on a view built and passed topush(). - An
on_state_changed()that awaits another task reloading the same view now stalls. Areload(),load(), send, or navigation now waits for a state render already running on the view, so the two no longer rebuild the tree at once. A render that awaits a separate task doing one of those on its own view, such asasyncio.gather(self.reload()), waits on a call that is waiting on it, and a warning naming the view is logged after 30 seconds. Awaitself.reload()directly, which runs inside the render, or reload onceon_state_changed()has returned. - A modal callback that re-renders its view and then replies through
interaction.responseraisesInteractionResponded, as a click callback doing the same always has: the re-render now answers the submission (see Changed). Reply with the view'srespond()or withinteraction.followup. - A reducer that awaits holds up other dispatches until it returns, and
dispatch()from inside a reducer raisesRuntimeError. Reducers now run one at a time, so a change another command commits can no longer be overwritten by a reducer that was awaiting; a dispatch waits behind it instead, and one kept waiting 30 seconds logs a warning naming the reducer. An action dispatched from inside a reducer, or from a task it started, was lost when the reducer's result replaced the state, and now fails while the reducer runs; unless the reducer catches the error, its own change is not applied either. Do slow work before dispatching and pass its result in the payload, and dispatch a follow-up after the first dispatch returns or from astore.on()hook. - A view that pushed or popped away hands its message to the view it
navigated to. Once the edit lands, the old view's
messagereadsNone, and a secondpush()orpop()on it raisesRuntimeError. Holding on to the message, the old view could still change it under the new one: arefresh()painted over it, a V1exit()stripped its buttons, a persistent panel'sexit()removed the registration it carries, and a secondpush()shipped over it while it stayed live. Navigate from the view the call returned;replace()on the old view raises too, since it closed nothing and its new view posted a second live panel, and so doesreplace()on the view a failedpush()orpop()returned, whose new view posted a second panel beside the one the navigation started from.exit()on the old view does nothing, since code still holding it (its own timeout, the lines right after the push) refers to a view that has handed its message on; the library's own cleanup closes the one that took its place. Code that keeps a reference to a panel reaches the screen now on it through the new read-onlycurrent_viewproperty; a subclass that assigns an attribute of that name needs another name for it. push(),pop(),replace(), andexit()raiseRuntimeErrorwhen called from inside a push or pop the view takes part in: from the new view'son_load(), or arebuild=ornav_rebuildhook on either view, including a parent'sexit()that would close either one. The navigation had not yet decided which view owns the message, so a nested push shipped a view over the one it moved to, an exit froze it onto the message, and a push from the source left a second view registered. Decide before navigating, or act on the viewpush()orpop()returns.push(),pop(), andreplace()also raise from inside the view's ownsend()(itson_pre_send(),on_load(),seed_initial_state(), or a hook the send runs), where the push landed on a view with no message yet and the send then reported the torn-down view as sent. Navigate oncesend()returns.push()andpop()raiseRuntimeErroron a view that has closed or is closing: afterexit(), a timeout, orstop(), or whileexit()orreplace()runs. The push brought the closed panel's message back to life under a new view, or raced its freeze and left a live view on a frozen message. Navigate before closing, or send a new view.send()raises the same way on a closed view, including one whose send failed or was refused (it posted buttons that answered nothing), and on a view already being sent, timing out, or navigated away. Construct a new view instead.push()andreplace()raiseRuntimeErrorfor a view instance that has already been sent, pushed, or closed. A cached instance pushed a second time was the view the firstpop()had torn down, so the panel's message was left with nothing answering it. Construct a new instance, or pass the class.replace()closes the view it was called on as that view'sexit()would. It only stopped the view, so the old panel kept buttons that answered nothing, its attached views stayed open, and a persistent panel was put back on its message at the next restart. Itsexit_policynow freezes the message (the default) or deletes it, attached views close, the registration is removed, and anexit()override runs. Drop any cleanup of the old message that follows areplace(): underexit_policy = "delete"it is already gone.- Closing a view a persistent panel pushed to retires the panel's
registration, whether the message is frozen or deleted. Only a deleted
message retired it, so a panel closed from a pushed screen (its Exit
button, or a
replace()from it) came back on that message at the next restart, beside any replacement. Give the pushed screen a Back button when the panel should stay up behind it. Sending the pushed view again to a new message moves the registration there instead, so Back rebuilds the panel on the new message and a restart restores it there. A pushed screen left idle returns to the panel rather than closing it. - A persistent panel's old message closes by the panel's
exit_policy, like every other view's: frozen by default. When a panel was sent again, or posted under a key an earlier run's panel still held, the duplicate-key cleanup deleted the old message (V2) or stripped its buttons (V1), whatever the policy said. A bot that re-posts its panels now leaves the old ones frozen in the channel; setexit_policy = "delete"to keep deleting them. - A persistent panel's
send()raises when a button itson_load()builds has nocustom_id. The check ran beforeon_load(), so the panel sent and then could not be reattached after a restart. Give the button acustom_id, as one built in__init__already needed. - More view attributes are checked when the class is defined: the
leaderboard and roles panels' text attributes,
podium_emojis,entry_separator, and a persistent view'skwargs_schema_version. The leaderboard'stitle=andsubtitle=keywords are checked at construction. Apodium_emojiskeyed by strings never matched a rank, so the podium showed plain numbers. Akwargs_schema_versionofNonekept the panel from being restored, and0read back as1, so a later bump to1restored the old rows without their migrator. A value that happened to work, such as a number for a title or a version written as"2", now raises too: write the string or the int. A class on version0moves to1, which is how its stored rows already read. persistence_key=must be a non-empty string. Stored keys come back from the database as strings, so anintkey stopped matching its own registration after a restart, and the duplicate-key cleanup and every lookup by that key missed it. An empty key was read as no key at all. Build the key as a string, for examplef"panel:{guild_id}".- The persistent leaderboard and roles panels check the ids of nested
controls. Their id check read only the top-level containers, so a button
or select placed inside one without a
custom_idposted fine and stopped answering after the next restart.send()now raisesValueErrornaming it, as it does forPersistentLayoutView. Give each such control acustom_id. set_class_attribute()refuses an attribute the library reads with no view instance in hand:session_continuity(read in__init__),persistent_slotsandsession_class_key(read when the class is defined), a persistent view'skwargs_schema_version(read at restore), and the roles panel'scategories,*_message, andhint_*attributes (read by a role button's click, which has no panel instance). A value set on one instance was accepted and then ignored, and a roles panel's owncategoriesrendered buttons whose clicks answered "This role panel is out of date". Set them on the class body. Every other attribute it accepts now takes effect. Ascoped_slotoverride is checked against the class'spersistent_slotsas the class body is, raisingValueErrorwhere the class persists"scoped": the override sent scoped writes to a slot nothing saved.PaginatedRegion.show_page()raisesRuntimeErrorbefore the region has a host. Called before the host's render rancontrols(view), it moved the cursor and firedon_page_changedwith nothing rendered, and returned as if it had. Useset_page()to seek before the first render.
Added¶
load()runs a view'son_load()without editing its message. It takes the same lock asreload(), so two loads on one view never interleave, and it suits a view whose data another view reads, wherereload()would ship an edit for a message that has not changed. No throttle applies, and it returnsTruewhenon_load()ran. A subclass that already definesloadkeeps its own; the library never callsload()itself.exit_children()closes the views attached to a view and leaves it open: the cascade its own exit runs, for a game view closing its players' private panels when a round ends.delete_message=Falsefreezes them instead, andNonefollows each one'sexit_policy. The docs and the Battleship example had called a private method for this.current_viewgives the view now showing a panel. Navigation inside a panel returns the new view only to the callback that ran it, so code that kept a reference to the panel (a cog closing it from a command) had no way to reach the screen on it once the user moved;panel.current_viewfollows eachpush()andpop(), and an ephemeral panel's Continue button, to that view. A call that does nothing on the old view (refresh(),reload(),exit(), ...) logs a warning naming the view the panel shows now.- The ephemeral Continue button's two hooks are public.
build_refresh_button()builds the button, andbuild_reopen_view(interaction)builds the view it sends. The default rebuilds the view from its constructor arguments, as before; override it for a view that must be built another way (a constructor with side effects, a live reference the old view holds, or a different view), or returnNoneto end the session. A result that cannot be sent (the class instead of an instance, a view already sent or closed) reacheson_reopen_failurewith an error naming the hook. The failure modeson_reopen_failuredocumented were only reachable through a private attribute.build_refresh_button()may be async. A button that cannot be built or placed (an override that raises, a label past 80 characters) is logged and leaves the panel as it was, where it used to freeze the panel with no Continue button. on_session_ended(interaction)andsession_ended_messageanswer a user who reaches a session that has ended: a modal submitted after its view closed, or a Continue whosebuild_reopen_view()returnedNone. The default hook sends the message ("This session has ended."), andNonesends nothing.InstanceLimitError.scopeis theinstance_scopethe limit counted under, which the default reply reads to name who the limit counts.auto_exit_buttonon the paginated, tab, wizard, and form patterns, asMenuViewhas:Trueadds the library's Exit button and keeps it through every page turn, tab switch, or step change. Off by default. The button has a fixed id, so it keeps working after a restart on a persistent panel.DISCORD_CALL_ERRORSis exported:discord.HTTPException,discord.RateLimited, andaiohttp.ClientError, the exceptions a failed Discord call raises, for anexceptthat tolerates a failed call while a programming error still raises. The last two are not subclasses ofHTTPException, so catching that alone lets a rate limit or a dropped connection escape.set_page()on both paginated views,switch_tab()on both tab views, andPaginatedRegion.show_page()takenotify=False, which moves without firingon_page_changedoron_tab_switched: for a jump the view makes on its own rather than one a user asked for. A timer that returns to the first page after inactivity, re-armed by that hook, otherwise cancelled itself.Collapsible(summary=)takes the text itself, as well as a callable for text that changes between renders; a string used to raise.fetch_as_file(max_bytes=)refuses a larger body withValueError, counted as it arrives so it is never read in full. The default, 100 MiB, is the most Discord accepts from a bot in any server, so nothing a bot could upload is refused;Noneturns the limit off.- Examples:
/v2roles_movemoves the role panel to another channel withretire_previous_on_sendturned off, the navigation demo's Start Over button usesreplace(), the pagination demo setsauto_exit_buttonand bounds its cursor cache withcache_size,/tasks_closecloses a task list throughcurrent_view, and the wizard answers a modal submitted after it closed with its ownsession_ended_message.
Changed¶
StateStore.get_active_view()costs the same however many views are live. It walked every live view on each call, so a refresh loop over many panels slowed with the square of their count. It now answers from an index kept as views register, with the same resolution rules as before.- A modal opened from a button on a view answers its submission with the
view's re-render, in one request, as a click does. This covers the
paginator and
PaginatedRegiongo-to-page modals, a form's field-edit modal, and aModalwhose callback re-renders the view whose button opened it. A view re-rendering onMODAL_SUBMITTEDdoes so before the callback runs and still edits its message, leaving the answer to the callback. The submission used to be acknowledged first and the message edited separately, through an endpoint Discord does not order against later clicks, so a click made soon after could land first and the typed page seem never to arrive. - A click the library answers without running its callback logs a
DEBUGline naming the view, the control'scustom_id, and why: the view has closed, the control is disabled on screen or is no longer on the message (the click came from an earlier render), the click repeats one still being handled (a double-click, a second Finish or Submit, a role button still toggling, a second Continue), or the view's access check or the control's ownowner_onlyrefused the user who clicked. on_message_gone()runs on a task of its own, after the render that found the message deleted has returned. It ran inside that render, where dispatching a state change back into the view re-entered the render's lock; an override may now dispatch, reload, or send the view again.refresh()returns before the hook runs, and the hook is skipped when a send has meanwhile moved the view to a new message.- A frozen panel keeps its link buttons clickable. The freeze on exit or
timeout disabled them too, though a link opens its URL with no view behind
it. Every other control is still disabled, and a V1 view's
exit()still removes every control. - A persistence backend must open again when
initialize()is called afterclose(). Persistence now closes with the bot and reopens on the same backend objects on a restart in the same process (see Fixed). The built-in backends support this; a custom backend whoseinitialize()runs only once fails every write after such a restart. Every backend'sclose()now gets ten seconds, after which persistence logs a warning and closes without it. - Closing a SQL backend waits up to five seconds for a transaction already
running on it, then closes anyway.
SQLiteBackendclosed under an open transaction at once, andPostgresBackendwaited for it with no limit, so one stuck query held a bot's shutdown indefinitely. A SQLite transaction the close cuts off now raises when it exits instead of committing on whatever connection is open by then. - Outside a persistent view,
choice_row, andbutton_rowortab_navgiven acustom_id=, no longer number their buttons{custom_id}_{n}. Ids that name positions are now derived the way auto-generated ids are (see Fixed), so twochoice_rows in one ordinary view no longer need distinctcustom_id=values. A persistent view keeps the numbered ids, since its ids must survive a restart. - The log file follows the date. A process running past midnight moves
to the new day's
<prefix>-YYYY-MM-DD.logand deletes the oldest pastmax_files, as a daily restart would; it used to write everything to the file named for the day it started, so a bot running for weeks kept one growing file thatmax_filesnever reached.
Deprecated¶
_build_refresh_button()is nowbuild_refresh_button(). The guides have told users to override the private name since 3.0.0. An override of it keeps working, called through the new name, and warns with aDeprecationWarningwhen its class is defined;super()._build_refresh_button()still returns the default button. The old name is removed in 4.0.0.
Fixed¶
- A push or pop always ends as a landed swap or a working source. A
cancellation while the new view was being built (an
asyncio.wait_for()aroundpush(), or astore.on()hook that awaited), or a back button that overflowed a full new view, left the source unsubscribed for good and the new view registered, with nothing on screen able to recover either. - A paginator rebuilt by
pop()or an ephemeral panel's Continue button shows the data it showed before. The rebuild replayed the constructor's arguments, so afterrefresh_data()the page list went back to the items it was built with, and afterrefresh_pages(new_total=)to the old page count. - A push or pop that fails leaves its source working. The source's tasks
were cancelled before an edit that could still fail and never restarted,
so a panel that looked live had lost its leaderboard avatar backfill, a
throttled render, and any task started with
create_task(), and dropped state changes meanwhile. The source now keeps its tasks and subscription until the edit lands, and renders what it was asked to once the push fails. A message deleted while the push was in flight now tears the source down once it fails, where it stayed registered to a message that no longer existed, and closes the view the push lands on when it lands, where that view stayed live on the deleted message. A source stopped withstop()while the push was in flight is closed once the push fails, asexit()closes it, where it stayed registered under the discarded view's buttons. - A push whose edit stalls redraws the view it left. A stalled edit may
still have reached Discord, so the message could show the discarded view.
The view that stayed live now redraws itself with the content
pop()would restore, and one that times out or exits first carries that content into its final edit, where a V1 view froze under the discarded view's embed. - Only the navigation edits the message while it runs. A destination
that listens to state rendered before its
on_load()ran, so the message showed unloaded content before the loaded one, and arefresh()from the destination's ownon_load()edited the message before the push had decided, so a push that then failed left the discarded view on screen. Both now ride the navigation's edit, and a change that arrives meanwhile renders after it lands. An edit the source had already started, including one retried on another endpoint, could reach Discord after the push's and cover the new view; the push now waits for it. - A button the new view shares by
custom_idwith the one it replaced keeps working after a push or pop. The old view stopping removed every id it had registered, the new view's matching ones included, so a view pushing its own class, or one paginator pushing another, lost every shared button. exit(), a timeout,replace(), a parent's cleanup, and another navigation wait for a push or pop in flight on the same view, or on the one it is bringing in. They acted on a message about to change hands: an exit froze the source over the destination, two pushes both edited the message, a parent closing mid-push left the child's new screen up, and anexit()on a new view still loading froze it before it arrived, and the navigation then shipped it dead. A wait that lasts 30 seconds is logged, naming the view.- A push or pop and a send of the same view no longer overlap. A click can land as soon as the message is posted, while the send is still finishing, and a push then moved the message under the send, which returned a torn-down view and attached it to its parent. A send made while the view's push was in flight posted a view the push then tore down. Each now waits for the other.
- Library cleanup closes the view on screen, not one that navigated away while it waited. An instance-limit replacement, a persistent panel's retirement, a parent's cleanup, and the devtools exits closed the old view, which does nothing, when a push landed in between, leaving the new one live: past the instance limit, or on a retired panel's message.
- A child sent with
parent=while its parent pushes attaches to the view the parent became. It attached to the old parent, which never exits again, so nothing closed the child.view.parentandattach_child()resolve a view that navigated away the same way. A view attached as a child and then pushed onto its parent's message no longer names that parent as its own, and a child sent while its parent exits closes with it instead of staying live. - A panel the new view opens from its
on_load()closes when the push fails, instead of staying live with nothing left to close it. - A
push()orpop()made without an interaction loads the new view and edits the message. Called from a background task on a view sent to a channel, it committed with neither: the old buttons stayed on screen answering nothing, and a new view that listens to state rendered before itson_load()had run. Arebuild=hook passed to such a call now runs as well. - A push or pop driven by a slash command edits the panel it was called on, not the command's original response, which is a different message when the panel was sent as a followup or by an earlier command.
- A view whose constructor takes a
messagekeyword keeps it through a push and pop.pop()rebuilt the view without it, as if the library supplied that keyword, so the view came back with its default. - A view a menu opened looks the same when the user comes back to it.
For a destination naming no
nav_rebuild, the menu's own render (build_embed()on V1,build_ui()on V2) applied to the push alone, so a pop back rebuilt it bare: a V1 message kept the child's embed under its buttons, and a V2 one came back without its tree. Its redraw after a failed push and its close had the same gap. - A menu category whose
"view"is not a view class raisesTypeErrorwhen the menu is constructed. Every click pushes it, so an instance worked on the first click and failed on the second with an error namingpush(), and anything else failed on every click. - A
rebuild=hook may return any awaitable.push()andpop()awaited only a coroutine, so the edit keywords aFutureresolved to were dropped and the new view shipped without them. - The first refresh after a push or pop no longer re-ships an unchanged view.
- A
replace()that fails leaves the view it was called on working. It was left stopped and still listed byget_active_views()and the inspector, on a message whose buttons answered nothing. - A click sent from a screen that has since changed no longer runs a
different button. Generated ids named a button by its label and
position, so a double-click, a second user on a shared panel, or a quick
page turn could run the row that took its place: a second "Delete" removed
the next task. The id now also reflects what the button does, so a stale
click reaches a button only when it would do the same thing, and is
dropped otherwise. A view whose callbacks capture objects rebuilt on every
render, with no equality of their own, gets new ids each time and ships an
edit where it used to skip one;
custom_id=pins an id. - A tree built in
on_load()or__init__ships stable component ids. Onlybuild_ui()stabilized ids, so such a tree went out with discord.py's random ids, and the first refresh renamed them in an edit of its own, which a click in that window could miss. - A button added after a view's tree was built no longer shares an id with
an identical one. A button added in
on_load()after the same button inbuild_ui()took the same id, and the send refused the view naming acustom_idthe caller never set. - An extra click on a panel that has already moved on is dropped. A second click queued behind a Back or push ran on the view the first had left, and a double-clicked Back left a second copy of the parent panel live. It is now acknowledged and nothing runs; the same holds for a click on a panel that has closed or is closing.
- A click on a button that is disabled on screen is dropped. It was sent from an older render, such as a second click on a board cell the first click played, or a move on a game that had just ended, and it ran against state the player never saw. It is now acknowledged and nothing runs.
- A click on a button a newer render replaced is answered. discord.py
found no button for its id and discarded it unanswered, so Discord showed
"This interaction failed", as for the second player's vote on a rematch
button whose label counts the votes. It is now acknowledged and nothing
runs, and so is a click on a button
remove_item()took off the view before the edit reached the message. The acknowledgement waitsauto_defer_delayand is skipped when something else answered, so a bot's ownon_interactionhandler for such clicks keeps its reply. A button whose label changes while its action stays the same keeps its clicks withcustom_id=. - A double-click acts once. Its second click queued behind the first and
ran again: a wizard's
on_finishor a form'son_submitran twice whenever the first left the view open,ToggleButton,toggle_button, andtoggle_sectionflipped back to where they started, aCollapsibleclosed what it had just opened,cycle_buttonskipped a value, in a persistent viewchoice_row(multi=True)toggled the option back out, and a roles panel's button granted the role twice or took it back. The second click is now dropped. A click sent after the first one's result still acts, and so does a Finish or Submit sent after one that was refused, by validation or byon_submit. - A double-click on a wizard's Next or Back no longer skips a step. The
second click advanced again, past a step the user never saw and its
validator. A nav click now acts only on the step it was drawn for, and the
Back and Next custom_ids carry that step (
wizard_next:2). - With
auto_defer = False, a click on a control the library built is answered. A page or tab button whose render changed nothing, the Exit button, a re-pick of the option achoice_rowdropdown already shows, and clicks the library drops showed "This interaction failed", since no code of yours ran that could answer them. A control built with your own callback is still yours to answer. - A view is torn down once. An
exit()on a view whoseexit()or timeout was running or had run, or that had moved on withpush()orpop(), ran the teardown again:VIEW_DESTROYEDreachedstore.on()hooks and subscribers twice, the message was frozen again, and a persistent panel'sPERSISTENT_VIEW_UNREGISTEREDfired twice. A parent's exit did the same to a child that had already exited. A close that starts while another is running now waits for it, for up to 30 seconds, and does only what the earlier one left undone. - A teardown called from a task its own view owns finishes.
exit()oron_timeout()run from such a task, whether one the library schedules or one started withcreate_task(), cancelled that task mid-freeze and left the panel up with live-looking controls. A parent exited from its child's task lost its freeze the same way, and apush()orreplace()from one stopped at its first await. The task is now cancelled once the call returns, and one that navigated carries on as the destination's. - A render that finishes after its view exits no longer repaints it. A
reload, or a tab, step, or page render, still loading when
exit()froze the panel put live controls back on it, and a reload on a view that had just pushed painted it over the destination. A state change coalesced into a render in progress re-ran it after the exit as well. Such a render now returnsRenderOutcome.NO_MESSAGE, andload()returnsFalse. - A close freezes the message after an edit the view already started has landed, where the edit landing last put live-looking buttons back on the closed view's message.
- A render after the close shows the controls as the close left them. A
modal submitted after its view closed, or a caller's own loop still
updating a timed-out panel, rebuilt the tree and put its buttons back,
clickable, on the closed panel's message.
refresh()on a stopped view now ships them disabled, or leaves them off where a V1exit()removed them, and sends nothing when the close deleted the message. Neither that render nor one already in flight when the view's own close deletes the message callson_message_gone(), which reports a message deleted out from under the view: an override that sends the view again logged an error on an ordinary Exit. - A closed view's last render survives a cooldown or rate-limit window.
An
on_timeout()override's final card, or any other render after the close, returnedRenderOutcome.DEFERREDinsiderefresh_cooldown_msor a 429 backoff and was then dropped, since the deferred render reads state a closed view no longer follows. It now ships when the window ends, as the tree stands, with the keywords it was called with. One Discord itself refuses with a 429 is dropped with a warning rather than retried. - A close cut off while it deletes or freezes the message makes that edit again. A view closed from a task another view owns (a parent's round timer ending its players' panels, say) was cut off when that view pushed or exited. It had already been torn down, so its message stayed up with buttons that answered nothing.
- Views attached to a stopped view close when its parent closes. A child
stopped with
stop(), or whoseon_timeout()override skipssuper(), was torn down by its parent's cleanup without its own attached views, which stayed live. on_timeout()called directly stops the view, as the timer does. discord.py kept such a view registered, with its timer running, after the freeze, and a push during its cleanup moved the message to a new view the freeze then covered. The view now refuses clicks and navigation from the moment the call begins.- A view closing or timing out freezes its
DynamicPersistentButtons. They stayed live, so a role panel posted again, or exited, kept handing out roles from the old message. A render that only changed a dynamic button's label, style, or disabled state was also skipped as unchanged. A role button whose role its category no longer lists is now refused rather than granting it. - The inspector cleans up a view whose teardown failed. A view whose
VIEW_DESTROYEDa middleware refused stayed registered after its exit, and the inspector listed it as live, where its Exit did nothing. It is listed and cleaned up as a ghost. - A view closed while it is being sent no longer leaves a dead panel. The
close tore the view down under the send, which then posted it with buttons
that answered nothing; the reachable case is a command run twice while
Discord is slow to answer the first, under
instance_policy = "replace". The send now carries the close out and returnsNone: before the view has loaded nothing is posted, and after that the message is posted and then frozen or deleted as the close asked. A view stopped withstop()during its send is closed the same way, asexit()closes it, since discord.py routes no clicks to a stopped view, and a persistent panel closed or stopped during its send, including during itson_bind(), is not registered, or loses the registration the send gave it. - A send that raises while it registers the view, or is cancelled while it
replaces an older one, is rolled back. A raising
on_participant_limit()oron_instance_limit()override left the view registered with no message and counted by its instance limit, which underinstance_policy = "reject"locked its owner out of the view class. A send cancelled while aview_createdhook awaits, such as a timeout aroundsend(), is rolled back the same way, and a send refused before its view reached the state no longer leaves an empty session behind. - A send cancelled after Discord accepted its message finishes before it
raises. A timeout around
send()landing after the post skipped the rest of the send: a persistent panel was live but never registered, so it did not come back after a restart; a view sent withparent=was not attached; and a cancel while the posted message was read back left the view without its message, so its renders never reached it andexit()could not freeze it. The send now carries on with that work, then raises, so the caller'sCancelledError, or a timeout'sTimeoutError, arrives when it is done. The step the cancel lands in is cut and the steps after it run, for at most five seconds after the cancel, after which none starts and a warning is logged; the message a re-send left is still closed if that step was the one cut. A close requested during the send is carried out after it raises. A program ending while a send is in that window waits for it the same way. - A send is no longer rolled back after Discord accepted its message when
reading that message back fails. The send read the posted message back
with a second request, though
send_message()already returns it; a failure there, such as a 503, rolled the send back and left the message on screen with buttons that answered nothing, and a caller that retried posted a second copy. The send now takes the message from the response, one request fewer per interaction send. When the channel fetch that follows a public interaction send times out, the view keeps the message the send returned, as it already did on an HTTP or transport error. The timeout escaped a send that had posted, before the view had its message or the rest of the send had run. - A step of a send that raises after Discord accepted the message no
longer skips the steps after it. A middleware raising on the view's
VIEW_UPDATEDleft the ephemeral refresh handoff unscheduled and a view sent withparent=unattached. Each failure is logged naming the step, and the send goes on. - Views a panel's
on_load()sent withparent=close when the panel's send is refused or fails, instead of staying live attached to a panel that no longer existed. Views attached before the send began stay open, released from the panel. - A view sent again closes the message it left, as its
exit_policysays. The old message kept its buttons, still wired to the view, so a click there acted on the panel now shown on the new message, for as long as the process ran. A V1 view sent again from a context with no interaction also sent itsrefresh(embed=...)edits to the old message, so the new message kept its first embed. The old message is frozen as it looked when the send began, and no render during the send reaches it: arefresh()fromon_load()or from another task used to put what the send built, possibly for another user, on the message being left. - A view sent again is no longer closed by the deletion of the message it
is leaving. Deleting a panel's message and sending the same view again
raced the gateway's delete event, which tore the view down on its new
message and left that message's buttons answering nothing. A 404 from an
edit still in flight on the old message did the same, and so did an
on_message_gone()that sends the view again. - Two views whose
on_load()awaits the other'sreload()no longer hang each other. Started at once, each waited on the other forever, with nothing logged. The reload that would close the cycle now raisesRuntimeErrornaming the views, and the other completes. A cycle throughasyncio.gather()or a task theon_load()created cannot be seen that way, and logs a warning naming the stalled view after 30 seconds. - A reload started while a view is being sent or navigated to no longer
runs a second
on_load()beside the first. The leaderboard'savatar_backfill, scheduled from inside the send'son_load(), could finish first and render nothing, and the send then posted the default avatars for good. A reload orload()from another task now waits while the send loads or delivers the view; one arriving while the send registers it runs there, and its data ships in the first message. - The library's fetches outside
on_load()no longer race a reload. A leaderboard's rebuild on a state change, afrom_cursorview's page loads andrefresh_pages(), andrefresh_data()with an async formatter could finish last with older data and overwrite the newer result until the data changed again. They now take the same turn ason_load(). LeaderboardLayoutView.reload(force=True)keeps its force when it queues behind a reload already running, instead of short-circuiting onto pages built from the older data. Thereload()docstring recommended that shape for subclass keywords and now describes one that holds.- A tab or wizard step render no longer interleaves with a reload. A tab
switch, a step change, or
refresh_content()could otherwise ship the content and any extra rows twice. They now wait for the reload. - A state change that arrives during a reload renders after it, against
the state at that point, instead of rendering whatever
on_load()had loaded so far. That includes a change that coalesced into a render already running when the reload began. A reload that starts while a state render is running waits for that render. Anexit()or timeout made before the reload finishes freezes the message without the change. - A state change that lands while a message is being sent now reaches
it. A rebuild during the send's request was recorded as shipped, so
every later unchanged refresh skipped and the message stayed a state
behind. The send now replays that render once the message exists, and the
send, each refresh, and each push or pop record the tree they actually
sent. A rebuild while the send was still registering could also leave the
tree half-built when the send validated it, failing the send with a
placement error that blamed the view's own tree. An embed or content that
another task passed to
refresh()during the send reached no message; it now ships after the send. refresh()no longer raisesAttributeErrorwhen a concurrent refresh finds the message deleted.- A page turn, tab switch, or wizard step whose render raises no longer
leaves the cursor ahead of the screen, where the next press moved on
from a page the user never saw. The patterns now put the cursor back when
Discord refuses the edit or the render fails before it (a page fetch, a
tab or step builder), as they did for a dropped edit.
PaginatedRegion,Collapsible, and the V1PaginationControls(whoseon_page_changedraws the page) had the same gap. The exception still reaches the caller. - A render abandoned on a slow Discord response is sent once the interaction is answered. The one-request edit of a click is given up when Discord is slow to respond, so the click's acknowledgement stays inside the 3-second window, and the render then waited for the view's next one: on a slow network a click seemed to do nothing, and the next click jumped past it. The render is now sent through the view's message as soon as the click is acknowledged. Modal submissions answered with a re-render get the same.
- A
discord.Filearrives whole every time the library sends it. A file passed again to a later call (the same chart to everyrefresh(attachments=[...]), an image arespond()and then asend()both carry, a file arebuild=ornav_rebuildhook hands back), or sent again after a first attempt failed and the library fell back to another endpoint (the one-request answer to a click, the interaction webhook after its token expired, the edit of a push or pop, a view's send that lost the race to a defer), was read from where the last request stopped and uploaded empty, which Discord shows as a broken image, with nothing raised. A file opened from a path raised instead. Each file is now read from its start, and one opened from a path is opened again. A direct discord.py call such aschannel.send(file=...)still needs a newdiscord.File. - An edit that fails after the view was sent again stays off the new message. A click's one-request answer, or an embed edit through the interaction webhook, that failed once another task had sent the view again fell back to the message the view had by then: the older render landed on the message the send had just posted. An expired webhook token there also cleared the handle the send had set, so that message's later embed edits went through the channel endpoint, which ignores them. The render belonged to the message the view left, and is now dropped.
- On Python 3.10 and 3.11, a cancel that lands as the library finishes an
edit or a save is no longer lost.
asyncio.wait_foron those versions returns the result when its caller is cancelled just as the work finishes, so a teardown that cancelled a view's render, or a shutdown that cancelled a write, found the task still running. The library now bounds these waits in a way that keeps the cancel on every supported version. TaskManagerlets go of a task whose event loop closed before it ran. A loop closed that way (a test runner's, or one a program closed itself) left the task tracked though it could never run:wait_tasks()on its owner from the next loop raised, andget_task_count()still counted it.- A panel with a push or pop in flight counts once toward its
instance_limit. The panel and the view it was moving to were both counted, as was a view torn down but not yet removed, so under a limit of two a second send was refused andcheck_instance_available()answered no while the first panel was navigating. - A view pushed from a panel counts toward the panel's
instance_limitwhatever its owninstance_scope. A panel scoped per user (instance_scope = "user") never found pushed views left at the default, so running the command again opened a second panel while the first stayed live. A participant joining through a pushed view is checked against the panel's limit rather than the pushed view's own, andcheck_instance_available(session_origin=...)reads the panel's scope and limit as well. - The default instance-limit reply names who the limit counts. Under
instance_scope = "guild"or"global", and for a participant turned away for taking part in another view, it said "You already have one of these open"; it now names the server, everyone, or the view they are in.InstanceLimitErrorcarries thescopeit counted under. - A view
replace()returns can be sent under aninstance_limit. The send counted that already-registered view against its own limit and closed it. - A view pushed onto a persistent panel returns to the panel when it times
out. It froze instead, and since the panel itself never times out, the
shared message stayed dead for everyone until a restart. A pushed view
that defines its own
on_timeout()still times out as that says, and one whose return fails times out as before. - A push that fails no longer lets the view it hands back remove the panel's registration, which left the panel on screen but not reattached after a restart.
- A persistent panel whose
exit()is cut off while its attached views close keeps its registration. It was removed first, so a cancelled or failed exit left the panel live, answering clicks, with nothing to reattach it after a restart. - A persistent panel sent again whose registration fails no longer comes
back on the message it left. When a middleware raised on the new
registration, a cancel cut it off, or the panel was stopped during the
send, the row still named the earlier message, which the send closes, so a
restart restored the panel there with nothing to click. That row is now
removed, and under
retire_previous_on_send = Falsean earlier panel still live under the key takes it back. A raise is logged as an error and a cancel as a warning, each saying where the panel is registered; the error used to say the panel would not be reattached, even when it would be. - A persistent panel posted in a channel discord.py cannot build registers. The posted message carried no channel, and registering it raised, so the panel was live but did not come back after a restart. The channel now comes from the interaction, which also fills in the view's state row.
get_active_view()no longer answers with a view a push is still bringing in. A failed push discards that view, so areload()on the result did nothing, and underretire_previous_on_send = Falserolling a swap back during a push registered it, so a restart attached its class to the old panel's message.- Rolling a swap back under
retire_previous_on_send = Falserestores the old panel when it is showing a view it pushed. The registration was lost, so a restart reattached nothing to that message; the registration now returns to it with the panel's own class and arguments. Closing a view the new panel pushed to hands it back the same way, and so does rolling back after the new panel is sent again. - When the view a panel pushed to loses its message, every registration naming that message goes. A key renamed in place leaves a second row on the same message, and only one was retired, so the other claimed a deleted message until the next restart.
- A persistent view's stored
kwargs_schema_versionis the class's. A version set on one instance was stored, and rows written under it skipped their migrator. - A persistent slot or persistent view argument with a non-string key is
named in the log. JSON stores every key as a string, so
{42: 3}came back as{"42": 3}after a restart and a lookup by42missed, with nothing raised. The value is still saved, and an ERROR names the key and where it sits, once; a key beside its own string form (42and"42") is named as losing one of the two values. A slot value that cannot be saved at all is now logged with what to store instead; the persistence guide said that case raised, when the slot is skipped. - Persistence closes with the bot. Nothing closed it before, so
application-slot changes still batched when the bot stopped (up to ten
seconds of them) were lost, and a bot on
SQLiteBackendnever exited: the database's worker thread kept the process alive. Withbot=, persistence now writes what is batched and closes its backends after the bot's ownclose(), including when a shutdown command closes it from another task. On Linux and macOS, the first SIGTERM (systemd,docker stop) now closes the bot the same way instead of killing the process, unless the application handles SIGTERM itself; a second one ends a program still running other work, as does any SIGTERM once the bot has closed, and a program that starts the bot again after a SIGTERM ends there, once any change made since the close is written. Withoutbot=, callawait get_store().persistence_manager.close()at shutdown. A restart in the same process reopens persistence when the new bot'ssetup_hookrunssetup_middleware()again (discord.py cannot log a closed bot in again, so the restart builds a new bot object); a change made while it is closed is held and written once it reopens, and the first one logs a warning. - A restart in the same process releases the views the old bot left,
and restores its persistent panels. Every view the closed bot left
answered "This interaction failed", held its instance slot (for good after
bot.run()again, whose new event loop had ended its timer), and logged an error each time a state change rendered it through the closed client; a persistent panel stayed dead until the process restarted. When a bot closes, the views sent through it are now released without an edit, as a process restart would release them: their timers stop, their instance slots are freed, they leave the state with no action dispatched (noVIEW_DESTROYEDhook runs for them), and code awaiting a view'swait()ends. Persistent panels are restored through the new bot when itssetup_hookrunssetup_middleware(), before it connects, andcurrent_viewon an old panel reaches the one restored in its place. - A
reattach()re-drive no longer attaches a second panel when one is sent under the same key while the re-drive runs. Keys a live panel holds were checked once, when the pass began, so a send landing while the pass fetched its messages was restored beside. Each is now checked again just before it is restored. - A bot built on
discord.Clientworks withPersistenceMiddleware(bot=)and with every send.discord.Clienthas nolisten(), so installing the message-deletion listeners raised:initialize()failed, and the first send through such a client skipped the rest of its setup, so an ephemeral view's Continue button never armed and a view sent withparent=was never attached. The listeners are now skipped for a plain client, whose deleted messages are found by the view's next edit. - Steady traffic no longer keeps application writes from finishing. A change arriving while a batched write was in progress cancelled it, so with changes coming faster than the backend wrote, nothing was saved until the traffic stopped. A write in progress now finishes, and the change is written after it. One still running after 30 seconds is cancelled and retried.
- A batch whose write failed is kept for the retry when the
on_errorhook is cancelled. The batch went back to the buffer only after the hook returned, so a shutdown cancelling the flush while its hook ran lost it. - Calling
setup_middleware()again with a new middleware instance uses the one already installed. Asetup_hookthat builds a newPersistenceMiddlewareeach time it runs initialized that second instance beside the installed one, which still handled every dispatch. The second instance opened another database connection (on SQLite, one that kept the process from exiting), rehydrated over live state, and pointedstore.persistence_managerat a manager nothing wrote through. A restart that builds a new bot object hands that bot to the installed middleware, and aPersistenceMiddleware(manager=...)install now setsstore.persistence_manageras well. setup_middleware()installs every function middleware it is given. It matched middlewares by class, and every function has the same class, so only the first function passed was installed.- A middleware that awaits before passing an action on no longer undoes
another dispatch's change. The reducer ran on the state the chain was
called with, so with an audit or rate-limit middleware that awaits first,
two clicks at once kept only one of their changes. A middleware that passes
on the state it was given now hands the next step the store's current
state.
UndoMiddlewarerecords each step as the reducer commits it, so an undo never takes back another dispatch's write, an action a middleware stops adds no undo step, and a middleware that awaits or dispatches a follow-up after passing the action on no longer loses a step. A batch holding such a follow-up undoes back to before the batch; it could be left with nothing to undo. A field a middleware adds to the state it passes on is undone with the action, wherever that middleware sits. - A reducer that awaits no longer overwrites a change another command
dispatched meanwhile. Its result was built from the state it read before
the await, so a write committed during the await was lost, with nothing
logged. Reducers now run one at a time. A batch's undo step,
set_scoped(), the slots and registry rows restored at startup, the views a bot's close lets go of, and/cascadeui resetare no longer replaced by a reducer that was awaiting when they landed either. - A middleware that raises after passing an action on no longer hides the
change. The reducer had committed it, but the raise skipped the
notification, the hooks, and the write, so memory held a change that
subscribers never saw and a restart lost. The change is now announced and
saved, and then
dispatch()raises; if a subscriber or hook raises first, the middleware's error is logged. An action that changes nothing (a broadcast only hooks handle) is announced as well. A dispatch cancelled after the reducer ran still saves the change and tells subscribers; hooks that had not started when the cancel landed do not run. - An action a middleware stops writes nothing to disk. Persistence
compared the store before and after the whole chain, so a change another
dispatch committed while a middleware below it awaited was saved as this
action's: a panel registration the middleware dropped left a registry row,
and the panel came back after a restart. Writes now follow exactly what the
reducer committed, so a change a middleware makes by assigning
store.statedirectly is no longer saved. - An action a middleware blocks is not announced. A middleware that
returned without calling
next_fn, the documented way to block an action, still had the action delivered to subscribers andstore.on()hooks, so a hook for it ran for something that never happened. A blocked action now reaches neither;store.historystill lists it. - A value nested too deep to save is declined like any other. A
persistent slot or persistent view kwarg deep enough to exhaust
json.dumpsmadedispatch()raiseRecursionError; it now logs the same "was not saved" error as a value that is not JSON. - A persistent slot written while panels are restored at startup is
saved. Persistence saved nothing until the restore had finished, so a
slot a restored panel's
on_bind()wrote was only in memory and was gone after the next restart. - A persistent slot is written only when what it stores changes. An
action handled by a
@cascade_reducercopies the whole state, so every persistent slot was queued to be written again after it, whatever the action changed: each save wrote all saved data, and everyttl_daysexpiry moved back, so a slot with a TTL never expired on a bot that ran such an action within each TTL period. A slot's expiry now counts from its last change. - An expired or pruned application slot leaves the running bot. The
daily TTL sweep and
prune_application()deleted the database row only, so the slot stayed in memory, was served until a restart, and was written back by the next action; afterprune_application(slot=...), a write still waiting for the slot also put the row back. The slot now leavesstate["application"]with any write waiting for it, andAPPLICATION_SLOTS_PRUNEDnames the slots removed in a newslotskey. - A failing database is retried with backoff while changes keep arriving. Each change replaced the pending retry with a flush after the batching window, so under steady traffic a failing database was retried every two seconds, and every registry change was tried at once, instead of waiting out the backoff.
rehydrate()run again on a running bot keeps changes not yet written. It replaced them in memory with the older stored value, which the waiting write then overwrote on disk, so memory and the database disagreed. It also waits for a write already in progress instead of reading around it.- A selector returning a value that cannot be compared no longer stops the
fan-out. A value such as an array, whose
==refusesbool(), raised out of the notification, so no other subscriber was told and no hook fired. The subscriber is notified on every action instead, with a warning. - A batch announces its actions in the order their reducers ran. An action whose middleware awaited after the reducer was announced, and reached its hooks, after an action that was reduced later.
- A hook that removes itself no longer makes the next hook miss the
action. Hooks ran from the list
store.off()changes, so the hook after one that removed itself was skipped.off()now holds from the moment it returns, and a hook added while an action's hooks run is first called for the next action, in a batch or outside one. Persistence'son_flushandon_errorhooks likewise first run a hook registered during a flush at the next one; one that registered a hook each time it ran never let the flush finish. - Profiling times a batched dispatch under its own batch. One dispatched
from inside another dispatch's middleware counted its reducer time as the
outer reducer's, so
/cascadeui perfshowed an instant reducer as slow. An action that reached a batch after it closed reported zero for every timing; it now reports its own. - Another task no longer joins an open
SQLiteBackendtransaction. The transaction was tracked per backend, so while one command heldbackend.transaction()open, another command'sexecute()ran inside it and was rolled back with it, and its reads saw rows the transaction had not committed. A transaction now belongs to the task that opened it, as onPostgresBackend, and other tasks' reads and writes wait for it to finish. A namespace write (row_upsert,kv_write, ...) inside the task's own transaction hung forever on the lock that transaction holds; it now raisesRuntimeError. - A
SQLiteBackendwrite cancelled before its commit is rolled back. It stayed open on the database's one connection, so the next write's commit saved it anyway (a batch included), and until thenbackend.transaction()failed with "cannot start a transaction within a transaction". A shutdown cancelling a write in progress, or a cancelled task awaitingexecute()or openingtransaction(), left it that way. - A
PostgresBackendtransaction always returns its pooled connection. One cancelled while it was starting, or ended from another task (the loop closing an abandoned async generator that held one), kept its connection out of the pool for good. - An Undo or Redo of a persistent slot is saved. Both were skipped as bookkeeping, so the value a user undid came back after the next restart.
- An Undo or Redo inside a batch reaches every view it changes. Only one
dispatched outside a batch passed a view's
subscribed_actionsfilter, so after an undo insideself.batch()another panel kept showing the undone value. - A batch that pushes or pops keeps its undo step. The step was added
when the batch ended, to the view the batch started on, which the
navigation had already closed, so the first Undo on the new screen skipped
the batch's change. It now goes to the view the panel passed to, with the
rest of the undo history. So does the step for a change from the view that
commits after the push or pop: one another task made while the navigation
ran, one a middleware held until it landed, and one dispatched from the
view after
push()returned. The last of these, and a change held ahead ofUndoMiddlewareuntil the view had closed, recorded no step at all. - A change or an Undo made while a push loads reaches the new screen's undo history, and one made while an ephemeral panel's Continue runs reaches the replacement's. The history was copied when the push or the Continue began, so a change made on the panel meanwhile was missing from it, and an Undo made then left the undone step in place and lost its Redo.
- Undo steps back through changes in the order they were made. A batch's step was added when the batch ended, so a change another task made from the same view while the batch was open (a timer tick during a click) was undone after the batch's change instead of before it. A batch's step now sits where its first change was made.
- An Undo or Redo made while another task's batch on the view is open waits for the batch to end. The batch's step joins the history only then, so an Undo meanwhile took back an older step over the batch's writes, and undoing everything afterwards ended on a value already undone. That holds for an Undo on the view a batch pushed or popped to, and for one a middleware held while a batch opened; one a middleware passed on a state it built is skipped with a warning instead, since that state predates the batch's writes. The wait is at most 30 seconds, after which the Undo goes ahead and a warning is logged.
- Undoing everything returns to where the history began when a batch and another task write the same key. A batch's step takes the place of its first change, so a write another task made to one of its keys between the batch's changes sat above it, and the batch's step held that write's result as the key's starting value. Undoing to the bottom ended on it; the batch's step now holds the value from before the earlier of the two. The same holds when the other writer is a batch too, and when a batch ends with a key as it found it after another task changed the key in between, which dropped the key from the batch's step.
- An action whose undo step cannot be recorded still applies. A session
shared_dataholding a value that cannot be copied madedispatch()raiseTypeErrorbefore the reducer ran; the action now applies, and an error names Undo and the view left without a step for it. A batch whose undo step could not be recorded, such as one comparing ashared_datavalue whose==refusesbool(), raised out ofasync with batchwithout announcing anything; it is now announced, with the same error. - Undo puts back only what the undone action changed, so it no longer erases other users' state. All scoped data shares one application slot, and an undo put back every slot the action touched, whole, so undoing a scoped change wiped every other user's scoped data in every guild and feature, and a Redo then restored stale copies of it. Undo now restores only the keys the action changed, at any depth, so a guild or global bucket every member writes into keeps the others' keys too. Undo is still per view: on a panel several users share, it steps back through every change made on that panel, whoever made it.
- The ephemeral refresh button is no longer overwritten by a render in
progress. Arming it while an
on_load()was running, or a tab, step, or page render reaching the armed view, rebuilt the tree without it, and since an armed view drops every notification that could restore it, the panel froze at the token cliff with no way to reopen it. Arming now waits for the load, and those renders leave the button in place. - Continuing an ephemeral child panel that reads its parent while it is
built works. The replacement was rebuilt without its
parent=, so a panel whose__init__readself.parentfailed on every Continue with the reopen-failure message. - Continuing an ephemeral session whose replacement is refused keeps the
current panel. When the replacement's
on_pre_send()vetoed it, or it hit an instance or participant limit, the panel closed anyway, handing its attached views to a replacement that never went live, so nothing would close them. The panel now stays, and Continue can be clicked again. - A close or a navigation that lands while an ephemeral panel's Continue
runs waits for it. An
exit()from another task, or the panel's timeout, closed the panel and its attached views while the replacement was being sent, and the replacement then went live without them or its undo history. Apush(),pop(), orreplace()from code committed as well, leaving two live panels. Each now waits for the Continue to finish. Once the replacement is live, anexit()does nothing and logs the warning it logs after apush(), and a navigation raises as on any view that handed its panel on;current_viewreaches the replacement. - Sending a view again no longer lets the earlier send's refresh handoff arm it. A timer left from a previous ephemeral send could mark the new message's view armed, and it then dropped every render.
- The V1 patterns accept
embeds=onsend().PaginatedView,TabView,WizardView,FormView, andMenuViewadded their own first embed beside the caller's, and discord.py refusesembedandembedstogether. - A V1 pattern's first embed reflects
seed_initial_state(). It was built before the hook ran. - A paginator sends the page it is on. A V1
PaginatedViewsent again from page 2, or opened on a later page withfrom_cursor(), posted page 1 under the later page's indicator. Afrom_cursor()view, V1 or V2, whosecurrent_pagewas set past its last page raisedIndexErrorwhen sent or reloaded; it now shows the last page. - A V1 form's row budget is checked against its finished layout. Field
order decided whether a form fit: five boolean fields with a text field
listed last were refused, and the same fields with the text field first
accepted. Five select fields passed the check and then failed inside
discord.py with
item would not fit at row 4; that case now names the button that does not fit. PaginationControlsandToggleGroupno longer report a handled click as an error. A click queued behind a slow one could be acknowledged by the auto-defer backstop first, and the composite's own acknowledgement then raised intoon_error, which sent the user the error reply.- An attribute set with
set_class_attribute()takes effect from the view's next render. Several were read only while the view was built, so the override was accepted and never shown: the paginated patterns' button labels, emoji, and styles,jump_threshold,nav_inside_container, andnav_divider; the wizard's Back button; the form's Edit button;tab_overflow_policy, which also skipped its own check and accepted an unknown preset;MenuView'smenu_styleandauto_exit_button; a roles panel'stitleandsubtitle;enable_undo,undo_limit, andsubscribed_actions, which__init__had already registered;instance_scope, which left the view counted under its old scope after it closed; andinstance_limiton a root view, which a participant joining through a screen it pushed did not meet.auto_exit_buttonfollows the same rule on every pattern that has it, andauto_register_participantsapplies at the nextsend(), which read the class and registered nobody. An override also survivespop()and the Continue button, which rebuild the view from its constructor arguments and dropped every override, so a limit set on a panel lifted after one Back. - Components Discord refuses in their container fail where they are
placed. A
discord.ui.TextInputin a view's tree fails the send's placement check naming it, as the other modal-only inputs already did, and so does anActionRowholding a select beside buttons, which discord.py builds when the select is added first. A button, or a select passed to aModalwithout thediscord.ui.Labelaround it, raisesTypeErrorat construction or frommodal.add_item(). ADynamicItem, such as a role button, is checked as the button or select it carries, so an over-long label or one placed outside anActionRowis refused like a plain button's. Each used to fail at Discord: the message was refused, or the modal would not open. - A
Modalshows adiscord.ui.TextDisplaypassed among its inputs. It raisedTypeErroras an input with nocustom_id, although Discord displays text in a modal. - A modal submitted after its view closed tells the user. The
submission was acknowledged with nothing shown, so the user's input seemed
to vanish. A
Modalopened withopen_modal()still runs its callback, and when the view had closed before it ran and it sent no reply of its own (a defer it made counts as one), the view's newon_session_ended()runs, whose default sendssession_ended_message("This session has ended." by default,Nonefor silence), the text the ephemeral refresh already sent. A view that navigated to one still open, or that the callback closed itself, gets no notice. The paginated go-to-page dialogs answer the same way instead of turning a page on a closed view. - A required modal text field answered with only spaces is refused, with
the field named, as a validator failure is. Discord refuses an empty
required box but accepts one of spaces, and the
Modalpassed it on, through any validator that lets a blank value by. setup_logging()deletes only the log files it wrote. Pastmax_filesit deleted the oldest.logfiles whose names merely began withprefix: withprefix=""that was any.logfile in the folder, andprefix="bot"also took another tool'sbot_errors.log. It now counts only its own<prefix>-YYYY-MM-DD.logfiles, oldest date first.- A misspelled log level raises.
setup_logging(level="DEBG")andLoggingMiddleware(level="DEBG")fell back to INFO without a word; both now raiseValueErrornaming the level, andsetup_logging()keeps the configuration it had.LoggingMiddlewarealso takes a numeric level, assetup_logging()already did; anintraisedAttributeError. fetch_as_file()raises on an error status, as its docstring said. A 404 or 500 page came back as the file and was uploaded as a broken attachment.cascadeui.componentsexports the fourMAX_*limits andcascadeui.viewsexportsEntryList, as the package root already did; importing them from their subpackage raisedImportError.- The Task Manager reference no longer awaits
cancel_tasks(). It is synchronous, so the snippet raisedTypeError. The page also credited the manager with cancelling tasks at bot shutdown, which the event loop does. - The API reference covers
switch_tab(),active_tab,create_task(),physical_table(), andfetch_as_file(), which it had left out. - The API reference says when
on_page_changedandon_tab_switchedfire. It said after the change completes; both run before the repaint, report the move the user asked for, and are not called again when that repaint does not land. - The persistence guide's schema migrator examples can be registered.
They used
cascadeui_persistent_viewsversion 1, the step the library's own migrator holds, so the decorator example raisedValueErrorat import and themigrators=example was skipped without a word. Amigrators=entry for a step already registered now logs a warning, and the guide says a migrator keeps its statements in onetransaction()and returns early on anOPEN_ROWSbackend. - The two-player game examples ignore a click that arrives after the game has moved on. Clicks queue behind one another, so a second click made before a move landed ran after it: TicTacToe and Battleship recorded a finished game twice, a Forfeit queued behind the winning move flipped the winner, and a Cancel queued behind the last Ready closed a game that had just started. Each callback now checks the game's phase first. Accepting a challenge while either player was busy also deleted the challenge; the game is now posted first.
- Other example fixes.
v2_hello_world.pyfailed as a prefix command.v2_wizard.pydropped a modal submitted after its default 180-second timeout, told users to exit with no way to do it, and showed a portrait upload that was not an image as a broken image; it now refuses the file with a message. Battleship's fleet panel froze three minutes after it opened.v2_persistence.pykeyed its visit counts byint, which reads back as a string after a restart. The lobby kept its players seated after Start. The game leaderboards and the README's leaderboard snippet labelled top-N sums as server totals.
[3.13.0] - 2026-09-17¶
Breaking¶
- An ack backstop delay of
3.0or more now raisesValueErrorwhen its class is defined. Lower it below3.0before upgrading. This coversauto_defer_delayon views,DynamicPersistentButton, andModal, and a form'stext_edit_modal_auto_defer_delay. The backstop defers after its delay, so a value at or past Discord's 3-second deadline could never land, and every handler slower than 3 seconds failed with nothing raised. The guides already named 3.0 as the ceiling; nothing enforced it.
Added¶
retire_previous_on_sendfor replacing a persistent panel under its own key. A send under a key another panel holds exits that panel during the send, which leaves nothing to fall back on when the new panel still has to be confirmed. Setretire_previous_on_send = Falseto retire the old panel yourself once the swap succeeds. The superseded panel'sexit(), or a deletion of its message, leaves the new panel's registration alone, and exiting the new panel to roll back hands the registration back to the old one while it is still live.StateStore.get_active_view(persistence_key=...)finds the live panel for a key. Code outside a view (a scheduler refreshing a posted panel, a command retiring one) no longer needs its own registry of panel instances. A finished view is never returned, while two panels share a key the one on screen is, and a panel that navigated away withpush()answers with the view now on its message, since navigation replaces the instance.PersistenceManager.total_reattach_summarycovers every reattach pass.last_reattach_summaryholds one pass, and the recommendedreattach()re-drive after late cogs load replaces it beforeon_readyruns. A removal is the case that breaks: only the pass that deletes a row reports it, so a reconcile reading the latest summary after a re-drive found an emptyremovedlist and cleared nothing, with no error to show for it. The new property carries the same five buckets with each key under its most recent outcome, and the guide's reconcile example reads it.PersistenceMiddleware(prune_unreachable_after_days=...)prunes unreachable registry rows without a caller. Rows that could not be fetched were kept and retried at every boot until someone ranprune_unreachable(). With the setting, the manager runs that prune once the gateway is ready and daily after, with the same re-verification against Discord. Off by default; it takes a positive number of days and needsbot=.
Changed¶
prune_unreachable()re-checks its candidates concurrently. The sweep verified one row at a time while holding the registry lock, so its cost was serial in the number of stamped rows, which is largest exactly when an outage or a permission change stamped many at once. Verification now runs under the samerestore_concurrencybound the reattach pass uses; the verdicts are unchanged. A row whose re-check raises is kept rather than aged out, since a check that never answered is not evidence its panel is gone.prune_registry()warns when it deletes the row of a live panel. It matches by key, so it takes whatever holds the key, and a panel running under that key stayed on screen while quietly losing the registration that restores it. The deletion is unchanged (an operator decommissioning a panel wants it) but it now says so, and the reference no longer presents the call as interchangeable withexit(), which retires a registration only while the view still owns it.
Fixed¶
- A teardown override's farewell card reaches the message again after a
push with no interaction. 3.12.3 skipped the teardown edit for any view
that had never rendered, which reached past the restored views it was
meant for: a
push()orpop()with no interaction binds the message without an edit, so the destination's closing card fromexit()oron_timeout()was dropped and the source's controls stayed on screen. Only a view restored from persistence is treated specially now; other never-rendered views ship as they did before 3.12.3. - A restored panel torn down before its first render is frozen again. 3.12.3 avoided the empty-message error by skipping the edit, which left the pre-restart panel on screen with live-looking controls that no longer answered. Such a view never put its own tree on screen, so freezing that tree would overwrite the real panel; the teardown now rebuilds the components the message actually shows, disables them, and ships that, with uploaded images and files still pointing at the message's own attachments. A panel with nothing left to disable is not edited, and a teardown override that composed new content still ships its own tree.
- Teardown no longer sends a tree Discord rejects. The teardown edit
was the one render path without placement validation, so an override
that cleared the tree and composed nothing, a destination whose
on_loadnever ran, or a card built from an empty list still reached Discord and failed with a 400 (error 50006 for an empty message). The edit is now skipped and the message keeps its last render; a view that had already rendered logs a warning naming the problem, since the tree its override left is the bug. - A rolled-back navigation's destination can no longer edit the
source's message. When every endpoint failed a
push()orpop()edit, the returned destination kept the source's message, so callingexit()on it overwrote the recovered, still-live source on screen. - A view whose message is deleted is torn down even when the bot never
hears about the deletion. Teardown came only from the gateway's
message-delete events, which a bot without the message intents never
receives, and which could not match the view anyway once an edit had found
the message gone and cleared it. Such a view stayed registered, subscribed,
and running its tasks, and a persistent panel kept its registry row until
the next restart. An edit that finds the message gone now tears the view
down through
on_message_delete()right afteron_message_gone(), so every view whose edit returns "Unknown Message" is retired, persistent rows included. Deleting the channel or thread a view's message sits in, which Discord never reports as message deletions, now does the same. One raisingon_message_delete()override no longer stops cleanup for the other views in a bulk purge. on_message_delete()is no longer called on a view another view's hook already tore down. The hook documents that a view already torn down is not called again, and the deletion sweep decided that once, before any hook ran. One hook can retire another view first, which a purge catching a panel and a view attached to it does with no override involved: the second view was called anyway and exited twice, dispatching a second teardown and a doomed message call. An override doing its own reconciliation saw the same double call.- A child view that stopped on its own no longer lingers in the registries
after its parent exits. The cascade that exits attached children skips one
that has already finished, and unsubscribed it without tearing it down, so
it stayed in the active-view registry and in
state["views"]: visible in the inspector, counted against instance limits, and unreachable by every cleanup path, since the same unsubscribe is what marks a view torn down. The cascade now completes that teardown. /cascadeui exitalland/cascadeui resetno longer exit a view twice. Both walk a list of the live views taken before the first exit, and exiting a parent exits the children attached to it, so a child already torn down was exited again: a second teardown dispatch, a second Discord call for a message the first exit had deleted, and an exit count that reported more views than there were.exit()on a persistent view that never sent leaves the live panel's registration alone. A panel whosesend()raised, or was refused by the instance limit, owns no registration, but itsexit()removed whatever the key pointed at, retiring the panel actually on screen: that panel then went unrestored after the next restart. Cleaning up a failed send is the ordinary shape this reached.exit()on a persistent view restored after a restart deletes its registry row. Only a send recorded a panel in the store's copy of the registry, so a restored panel was never in it: itsexit()changed nothing, the row stayed on disk, and the panel was restored again on every boot. Rehydrate now records every stored row. The same gap let a panel re-sent under a restored panel's key leave the restored one live; that panel is now exited during the send, as it already was within one uptime. Rows left behind by earlier versions are not removed automatically; retire them withprune_registry(persistence_keys=[...]).- A view a panel pushed to retires the panel's registration when it deletes
the message.
push()replaces the instance, so the panel is gone and its registration rides the destination. Nothing retired that registration when the destination was the view whose message went: the row kept claiming a deleted message until a restart re-checked it, and a panel re-sent under the key in the meantime ran its orphan cleanup against a message that was not there. A view frozen in place still keeps the registration, since its message is still up. - Re-sending a persistent panel also retires a view the old panel pushed.
push()hands the destination the panel's message, but a send under the key exited only views holding the key, so the pushed view stayed live on the superseded message and kept answering clicks. It is now exited along with that panel. - A
reattach()re-drive no longer restores a panel whose registration this process already deleted. Every pass walks the registry rows read once at startup, and anexit()that removed a row left it in that list. A key still pending from boot, re-posted by a cog and later retired, was restored on the next re-drive onto the message the startup row named: a live panel answering clicks with no row behind it, gone again after the next restart. Rows are now dropped from that list when their registration is removed, alongside the prune that already did so. - A
reattach()re-drive no longer attaches a second instance to a live panel. A panel sent under a key whose row was still pending from boot rewrote that row, and a later re-drive adopted the new message and reattached it beside the panel already running on it. Re-drives now skip every key a live panel in the process holds. prune_unreachable()no longer deletes the row of a panel that is live in the process. A panel whose channel the bot lost access to after it was restored still routes interactions, but the prune read its failed fetch as grounds to delete its row, so the panel was gone after the next restart. Such a row is now kept, and the prune waits for any reattach pass already running, so it cannot delete a row that pass just found reachable./cascadeui resetno longer drops the registry mirror and the modal rows. The helper that rebuilds state from scratch listed four of the six top-level keys, so a reset leftpersistent_viewsandmodalsabsent: stored rows stayed on disk while nothing in the process knew about them, and the reattach re-drive and prune could no longer tell which keys a live panel held. The reset also rebuilds that mirror from the rows its own teardown left behind, rather than starting empty.- A reducer that declines an action no longer reverts state committed while its dispatch was waiting. The store rebound whatever the reducer returned, and a reducer that refuses returns the state it was handed, so a dispatch that had paused in a middleware wrote that older state back over anything committed in the meantime. Reached with middleware that awaits real work, an audit log or a metrics push, on the paths where a refusal is routine.
- The persistence example's role panel re-renders on restart.
RoleSelectorPanel.on_restoreinexamples/v2_persistence.pynow callssuper().on_restore(bot), so edits to the role categories reach a restored panel instead of leaving the pre-restart render on screen.
[3.12.3] - 2026-09-16¶
Fixed¶
exit()andon_timeout()no longer send an empty message for a view reattached from persistence but not yet rendered. A restored view is registered and message-bound before its post-ready render runs, so tearing it down in that window read the absent render baseline as "always changed" and shipped whatever the constructor produced -- typically empty for a pattern that builds its tree inon_load, which Discord rejects with error 50006. Both teardown paths now skip the cosmetic edit when nothing froze and nothing has changed since restore, leaving the message's existing content in place; a teardown override that composes new content before delegating still ships it, restored or not.
[3.12.2] - 2026-09-12¶
Changed¶
- Ephemeral acting refreshes now route through the same edit-as-ack fast
path non-ephemeral acting views use, cutting the round trip in half and
acknowledging the same click that renders it. The prior exclusion
assumed an ephemeral message could only be edited through the
interaction webhook (
self._message.edit(), a slower call scoped to the message's original send), butinteraction.response.edit_message()is a normal per-click response Discord treats identically regardless of a message's ephemeral flag. A disqualified fast path still falls back to the webhook edit exactly as before; a stalled or rate-limited fast path still returns without a fallback attempt, exactly as it already did for non-ephemeral views.
Fixed¶
- A view carrying a
DynamicPersistentButtonno longer breaks that button on every OTHER live message sharing the same button class. discord.py's dynamic-item registry is keyed by compiled template, shared across every message carrying a matching subclass, and not refcounted, so two distinct discord.py mechanisms could each clear the shared pattern for every button using it: any one view's teardown (exit(), a natural timeout,replace(), a push/pop navigation commit, or a caller's own directstop()call, reachable for any view CascadeUI sends that also carries at least one ordinary component alongside the dynamic one), and, independently, a live view's OWN edit dropping a dynamic-item class it used to carry (the ephemeral refresh-handoff timer swapping a view down to a bare "Continue Session" button is the concrete case). Every seam that reaches either mechanism now re-drives the full dynamic-item registry with the bot immediately afterward: the teardown seams close the gap before another view's teardown can widen it further, and every successful render (refresh(), navigation's destination edit) closes it before another view's edit can reopen it. A natural timeout, which discord.py clears before any hook runs, carries its own repair at the exact point discord.py calls it, unreachable by a subclass overriding the publicon_timeout()hook withoutsuper(). The same recoveryPersistenceManager.reattach()already performs on every pass.
[3.12.1] - 2026-08-24¶
Added¶
- The API reference documents
on_timeout(), the one lifecycle hook it had never listed, including what an override inherits when it skipssuper().
Fixed¶
- An
on_timeoutoverride that dispatches instead of delegating tosuper()now renders. discord.py marks a view finished before it callson_timeout, so the guard that stops a torn-down view from rebuilding also caught every view inside its timeout window: the dispatch landed, other views saw it, and the timing-out view silently kept its pre-timeout components. The guard now reads whether teardown has run rather than whether the view has stopped, so the final render ships and a notification arriving after teardown is still dropped. The rate-limit retry and the deferred cooldown render carried the same check and were swept with it. PaginatedRegion.show_page()was declined on a host inside its timeout window, so a host jumping to a closing page fromon_timeoutnever re-rendered. The render probe shared by the V2 composites reads whether teardown has run, matching the view seams above.
[3.12.0] - 2026-08-21¶
Breaking¶
SQLiteBackendandPostgresBackendreject atable_prefixthat is not lower-case letters, digits, and underscores, starting with a letter or underscore, withValueErrorat construction; a non-strprefix raisesTypeError. The prefix reaches SQL through two paths that do not agree on quoting: the DDL and the migrator interpolate it as raw text, while a backend's row and key-value paths quote what they build. PostgreSQL folds an unquoted identifier to lower case and preserves a quoted one, so a prefix carrying a capital created one table and addressed another, splitting a deployment across two that both looked right on their own. SQLite matches identifiers case-insensitively, so a prefix likeBot_worked there in 3.11.0 and now refuses to construct. Lower-case the prefix to upgrade: SQLite resolves the new spelling to the existing table, so the data is found in place and nothing needs migrating.
Added¶
MAX_MESSAGE_COMPONENTS,count_components(item), andStatefulLayoutView.total_componentsexpose the per-message component budget the library already enforced.add_itemraises when a tree would cross the cap, but the number and the recursive counter behind it were both private, so a consumer wanting to check a budget before composing had to transcribe the literal and rewrite the walk -- and a hand-rolled walk that counts the view itself disagrees with Discord's own count by one. A caller's check and the library's enforcement now read the same two numbers.count_characters(item)measures a subtree's display text the waycount_components(item)measures its nodes, so both budgets are read from the same place while composing. Without it a caller holding items had to add them to a throwaway view to reachcontent_length(), which borrows that view's component limit: a subtree over the component budget failed a character measurement with an error about components.MAX_MESSAGE_CHARACTERSnames the other budget a V2 message has, and a view over it now warns at every seam that ships a tree. The per-node 4000-character cap on oneTextDisplaywas pre-flighted and the message total was not, so ten short text nodes passed every check and were refused at send with no component named -- on a persistent panel, hours later, in a channel nobody is watching. It warns rather than raises: Discord documents the cap while discord.py counts it without enforcing it, so a hard refusal could reject a message Discord would have taken.LayoutView.content_length()supplies the running total for a budget check while composing, and reachesTextDisplaycontent only: text in a button label or a select placeholder counts zero against it, so a control-heavy screen can approach the cap without the warning firing.Modal.submit(interaction, values)drives a submission offline through the pipeline a real one takes, returning whether the validators accepted it. A modal was the one interactive surface with no offline drive, so a test reached past it to the stored callback, which runs neither the validators, nor the write-back onto the input wrappers, nor theMODAL_SUBMITTEDdispatch. Such a test succeeds against input the modal would have rejected, reporting coverage of a seam it never crossed. Values key by an input's label or its derivedcustom_id, resolved against the same map the modal itself uses, so a raw escape-hatch input is reachable too. A custom_id is an input's identity and always wins a contested name; a key naming no input raises. It assigns the values and callson_submititself, so there is no second implementation to drift. The verdict is whaton_submitrecords as it runs, so an override must call up to it; one that does not is told so rather than having its submissions reported as rejected.cascadeui.testing.stub_interaction()returns the doubleModal.submitasks for, recording what is said instead of sending it. A rejection is then assertable without a connection, including the part measurement cannot reach: whether the response slot or the followup carried the message depends on whether the ack backstop had already fired, so both record into one place.cascadeui.testing.stub_client()returns adiscord.Clientthat never connects, for measuring a view with no Discord connection. It matters where composition depends on a client: a section-mode leaderboard row resolves an avatar into a four-nodeimage_sectionwith one bound and renders a one-nodeTextDisplaywithout, so a five-row page differs by fifteen components between the tree a test builds and the tree that ships. The stub reports the empty user cache a live bot reports for an unseen member, so the composed tree matches.- Component callbacks are checked against the arguments the control will
call them with, at construction rather than on the first click. A button
callback declaring
(interaction, value)was invoked with one argument and raised from inside the library wrapper, surfacing to the operator as "This interaction failed" with a traceback pointing at library code rather than at the wiring. The refusal names the callback's own signature and the shape the control wants. The mirror is closed too:choice_row,cycle_button,toggle_button,ToggleGroup,PaginationControls, andModalreport a value to their callback every time, so one that cannot receive it is refused where it is supplied.PaginatedView.from_cursorrefuses afetch_fnthat cannot take(offset, limit)and aformatterthat cannot take(chunk). Cursor mode stores both and first calls them from inside the page loader, one line apart, so either arity error surfaced there rather than at the constructor that accepted it.Collapsiblerefuses arevealorsummarythat requires an argument: a wrong-arityrevealconstructed and rendered cleanly, then failed on the first expand click with the state already flipped and the screen still showing the collapsed body. A wizard step'sconditionis refused in both declaration forms, the raw dict andWizardStep, because it is the one step callable whose arity error is never seen: the visibility check calls it inside a guard that treats a raising predicate as visible, so a predicate that could not be called rendered the step it meant to hide and logged a warning as the only trace. The other step callables are left as they are, since each already fails at its own call with the callable named. toggle_sectionandToggleButtonpass the new toggle state to a callback that declares a second parameter, matchingtoggle_buttonandcycle_button. A one-parameter callback is called exactly as before. The library's own toggle-shaped controls delivered their value and these two did not, which is the inconsistency behind the wrong-arity callbacks the entry above refuses.- Empty and whitespace-only media references are rejected where they are
written.
image_section,gallery, andfile_attachmentraise at construction naming the builder and the parameter, and the pre-flight validator rejects an empty media URL on a rawThumbnail,MediaGalleryItem, orFile, including one mutated to empty after construction. An empty reference previously shipped and failed the whole message with a 400 that named no component: the same mistake an empty text node has raised for since 3.8.0, one field over.LeaderboardLayoutViewkeeps its degrade paths, so a blankbanner=still renders no banner and a whitespaceget_avatar_urlreturn still takes the stacked-text fallback. - The pre-flight validator enforces two more documented Discord caps:
ThumbnailandMediaGalleryItemdescriptionat 1024 characters, and link-buttonurlat 512. The docs claimed 256 for the alt text and now name the real limit. An empty link-buttonurlis rejected on the same reasoning as an empty media reference: a URL is machine-consumed, so a blank one cannot resolve and ships to be refused as a form error naming no component. send()warns when a send names anattachment://reference it carries no matching file for, across a V2 component tree and a V1 embed's image, thumbnail, author, and footer alike. Discord resolves the two by name and renders an unresolved placeholder when it cannot, raising nothing, so the initial send is the only seam where both halves are in scope.indicator_button_formatonPaginatedView,PaginatedLayoutView, andPaginatedRegiontemplates the middle navigation button instead of replacing it.indicator_button_labelfreezes one literal across every page, which is worse than the default for a board that wants1/12rather thanPage 1/12on a narrow row. Placeholders are{page}and{total}, one-based; the literal still wins when both are set, and a template that cannot render is refused at class definition rather than raising from inside a click. The roles panel's five*_messagetemplates are checked the same way: a typo'd placeholder there raised a bareKeyErroron the click that used it, naming neither the attribute nor the placeholders it accepts.with_cooldown(message=)joins them, and is the one that hid best: its template renders only when a click is refused inside the cooldown window, so a typo survived construction and the first click before raising. It is rendered once where it is supplied, with the value the refusal really passes -- already rounded to one decimal, so a spec like{remaining:.0f}is refused there too rather than failing on a str at click time.
Changed¶
- A toggle callback whose second parameter has a default now receives the
toggle state where it previously received that default.
toggle_sectionandToggleButtondecide by whether a second positional parameter is declared, and a defaulted one is declared, so a callback written(interaction, extra=None)starts seeing the state inextra. Selects have read a defaulted second parameter the same way in every release, so nothing changes for them. Callbacks taking exactly one parameter are called as before.
Fixed¶
- Several wire-visible fields did not reach the render digest, so
refresh()reportedSKIPPEDover a tree that differed from the one on screen and shipped no edit. An entity select'sdefault_values(the equivalent of theopt.defaultfixed for string selects in 3.3.4), aSeparatorappearing, disappearing, or changing spacing or visibility, a select option's label, description, or emoji,min_valuesandmax_values,channel_types, and a premium button'ssku_id. The relabel case is the everyday one: a count badge moving fromInboxtoInbox (3)keeps the option's value and so hashed identically.SKIPPEDstates that the screen already shows this state, which is what made each of these a wrong answer rather than a missed optimization. A test now derives the expected field set fromto_component_dictitself, so a field discord.py adds later fails there instead of silently skipping a render. LinkButtonaccepted an emptyurl. The pre-flight validator refuses one in a V2 tree, and a V1 view reaches no pre-flight, so the same button shipped to a form error naming no component depending only on which view held it. It is refused at construction now, which covers both.- A select inside a modal never delivered its value.
Modal.on_submitcollects submitted values by walking its children and matching types, and the select family was absent from that list, so a user's choice was dropped before the callback, beforevalues_by_input, and before theMODAL_SUBMITTEDdispatch. Reading it raisedKeyError, or readNonefrom a.get(), on every submission. Reachable through the documented raw-item escape hatch, which is the only way to put one in a modal. Modaldiscarded every keyword it did not recognize.on_submit=is the name discord.py subclasses override and the natural guess forcallback=, and passing it left the handler unset: the modal acknowledged each submission, ran nothing, logged nothing, and saved no input. A mistypedview_iddropped theMODAL_SUBMITTEDdispatch the same way, andcustom_id(a realdiscord.ui.Modalparameter) was replaced by a generated one. The signature is closed now, so an unrecognized keyword raises naming it, andcustom_idreaches discord.py.- Pruning a stored registration left the key in the store's own registry
mirror.
prune_registrydeletes the row on disk and reports the prune, butstate["persistent_views"]kept the entry, so re-registering that key afterwards found a stale record, matched no live view, and took the orphan-cleanup branch against the message the prune existed to leave standing. The prune now drops the keys it deleted, and still reaches every subscriber and hook, since reducers run ahead of both notification passes.APPLICATION_SLOTS_PRUNEDstays reducer-less on purpose: the slot it removes is still live in memory and re-upserts on the next write. - A correct prune logged a warning. The store's missing-reducer check read
"something subscribes to this" as the signal for a mistyped action, and
subscriber filters default to an empty set, so
REGISTRY_PRUNEDandAPPLICATION_SLOTS_PRUNEDwarned on every prune: once per row dropped at boot, and once per daily TTL sweep with no consumer involved at all. Actions the library declares dispatch-only now log at debug, and an unknown type with no reducer and no listener still warns. - On PostgreSQL the 3.11.0 table rename left each renamed table's
primary-key constraint and its backing index under the legacy name, so
an upgraded database and a fresh install diverged in the catalog
permanently and only an operator reading
pg_indexeswould see it. Boot renames the constraint to match its table, reaching databases already upgraded under 3.11.0 as well as those still on 3.10.0. A name already taken by another relation warns and boots. SQLite is unaffected, since its autoindex follows the table through a rename. - A leaderboard that outgrew the component budget reported it in the
vocabulary of a hand-composed view, suggesting folded text nodes and a
compacted pager. A board's size is set by how many entries a page
carries, and in section mode by whether a client is bound: the same
class fits with none and overflows with one, because each row grows from
one component to four. The message now names
leaderboard_per_page, and what the page it just built actually cost per row -- counted rather than inferred from the client, since aget_avatar_urloverride returning nothing degrades every row to a stacked text node with a client still bound. python -m cascadeuireported the installed distribution's version rather than the version being imported. An editable install serves the number it recorded at install time, so a checkout several releases ahead still printed the old one, and the bug report form requires this block: the wrong version arrived in the issue stated as fact, with nothing to contradict it. It now reports the running version, and names the installed one only when the two disagree, since that disagreement is worth seeing. The backend probe also listed a driver for a backend the library does not ship while omittingasyncpg, so no report aPostgresBackenduser filed named the one backend with a network surface.- The persistence reference credited
SQLiteBackendandPostgresBackendwith every capability flag, which stopped being true whenOPEN_ROWSwas added in 3.10.0. Both store rows as fixed columns and declare five of the six; a backend author reading the page could conclude an unknown column would round-trip and skip the migrator that makes it. - The documented offline-testing recipe could not measure a section-mode
leaderboard's real budget. It builds the view with no client, which is
the branch that renders one component per row, so a board reported 25
components against a cap of 40 and shipped 40. The recipe binds a client
now and reads
total_components.
[3.11.0] - 2026-08-13¶
Breaking¶
- The two unprefixed library tables are renamed.
persistent_viewsis nowcascadeui_persistent_views, andapplication_slotsis nowcascadeui_application_slots(cascadeui_schemaandcascadeui_kvare unchanged). The old names made an operator scope oncascadeui_%(a filtered backup, a grant, an audit query) silently miss the registry, and letCREATE TABLE IF NOT EXISTSadopt a consumer's same-named table. The SQL backends migrate an existing database in place on the first boot: the old table is renamed -- indexes and schema-version record included -- in one transaction, only after its columns confirm it is the library's. A same-named consumer table without those columns is never touched, and when both names exist with rows, nothing is renamed, the library uses the new name, and a WARNING names both tables. On PostgreSQL the rename needs table ownership, which the usual DML grants do not confer: a role without it getsPersistenceSchemaErrornaming both tables and the privilege, the database is left unchanged, and the rename retries once the privilege is there. A role that cannot see the old table at all skips it silently. What needs a hand: external scripts, grants, and backup filters naming the old tables move to the new names; a schema migrator keyed on an old name is refused at registration with aValueErrornaming the current one (keyed on the old string, it would never be looked up); a custom non-SQL backend that persists rows keyed by namespace string moves itspersistent_views/application_slotskeys itself; and every process sharing one database upgrades together, since an older library will not find the renamed tables.
Added¶
LeaderboardLayoutView.get_entries()accepts anasync defoverride, so a board whose rows live in a database reads them through the documented seam instead of caching into a private field. The patterns guide covers both shapes and when to prefer each.EntryListtype alias, exported from the package root besideEmojiInputandMediaInput, for annotating aget_entries()override.render_progress()returns a progress bar as a string, for inlining into text a caller is already building: a leaderboard row's secondary line, akey_valuecell, astats_cardfield.progress_bar()composes itsTextDisplayfrom it, so an inlined bar and a standalone one cannot render differently. Both clampvalueand hold the bar towidthcells.view.parentreads the view a child is attached to, orNonefor a root. Available from construction when the child was built withparent=, so a child panel reaching its parent no longer stores the same view twice.- The auto-defer backstop logs at INFO when it fires, naming the surface and
the elapsed time. Firing means a handler used its whole
auto_defer_delaybudget and the interaction was rescued rather than lost: the leading indicator for a surface that will eventually miss the deadline. It covers all four acked surfaces (view callbacks, the send pipeline,DynamicPersistentButton, andModal.on_submit), and the window it measures starts before the access check and anyserialize_interactionslock wait, so it prices work no wrapper around a callback can reach. The cancelled path stays silent and free: nothing is timed unless the ack actually lands late. table_prefix=onSQLiteBackendandPostgresBackend, applied to every table and index they create and query, carried on PostgreSQL's invalidation channel so two prefixed deployments do not read each other's notifications, andphysical_table(backend, name)for a migrator resolving a table name through it. The prefix keeps two CascadeUI deployments sharing one database apart. Empty by default, so existing databases are unaffected. The persistence guide now names the full table set.docs/guide/persistence.mdgains a "Class identity" section: moving or renaming a persistent view class leaves its stored rows holding the old name, andsession_class_keyis what keeps them resolving.- Screenshots and short recordings throughout the documentation site and the README, covering every V2 builder, composite, and view pattern. The landing page now opens with a working counter beside the view it renders.
Fixed¶
- A view that set
session_class_keycould not be popped back to. Navigation entries recorded the session key while the class registry is keyed on the import path, so the lookup missed and Back died as a logged warning and aNone. Entries now record the class path. The pin is the sanctioned answer to a persistence hazard, so following that advice on a navigating view had traded one bug for another. - Two persistent view classes sharing one
session_class_keysilently displaced each other in the class registry, and every stored row under that key reattached as whichever class was defined last. The collision now raises at class definition, before either registry is written. session_class_keyaccepted any truthy value. A non-string reached the backend as theview_classcolumn, where SQLite stored its digits and the lookup then missed forever. An empty string was ignored outright, so a class that declared one was never pinned and would orphan its rows on the first move. Both are refused at class definition. Several refusals below fire there too, so a class that imported on 3.10.0 can now fail at import rather than at first render; each entry names the seam it guards.- The reattach warning attributed every skipped row to a missing class, though
rows turned away by a kwargs migrator land in the same bucket. It now counts
only unresolved classes and names each stored string with its row count, the
name an operator registers a class under or pins
session_class_keyto. - The five
on_role_*hooks,get_avatar_url, andresolve_avatar_urlswere awaited unconditionally, so an override that needed noawaitand was writtendefraised aTypeErrorfrom inside the library. On a role button it escaped the handler entirely and surfaced as "This interaction failed". - The leaderboard's frame and row hooks (
build_title,build_header,build_footer,format_entry,format_primary,format_secondary,on_leaderboard_empty) acceptasync defoverrides; an async one previously leaked its coroutine into the page build. format_rank,format_name,format_stats,format_accessory, the roles panel's five compose hooks, and the wizard'sstep_indicator_labelresolve where nothing can await them, so an async override rendered as a coroutine repr in the board, on the button, or in the role card with nothing raised. They are refused at class definition, naming the seam.- Every seam that refuses an async override missed one supplied as a
staticmethodorclassmethod, which is how a class body declares a plain-function hook, and missed anasync defcarrying a strayyield.state_selectorand@computedselectors accepted both shapes silently, leaving the view deaf to state updates or the value never resolved. - The seams that take their hook as an argument rather than reading it off a
class body kept the narrower check:
Collapsible(reveal=)andsummary=,StateStore.subscribe(selector=),restore_on_dropped_render(rebuild=), and a wizard step'scondition. All refuse the same set now. - A leaderboard rebuild read
get_entries()twice, once for the change signature and again for the page build, and stamped the signature from the first read while rendering the second. PaginatedRegion.set_page()resolved a negative index against the page count it had at the time of the call, butshow_page()seeks and then re-renders, and the host loads fresh items during that render. A list that grew across aper_pageboundary therefore leftshow_page(-1)on the old last page, so the row that prompted the jump rendered off-screen under a cursor reporting a later page. The index now resolves against the items that arrive; an explicit move drops a pending one.- A state notification queued before a view's teardown could arrive after it, and the torn-down view still rebuilt. Cross-view fan-out is fire-and-forget, so the gap is ordinary rather than rare: the rebuild rendered into a view that could no longer be interacted with, and read attributes the teardown had already cleared, which surfaced as an ERROR and a traceback from inside the subscriber wrapper rather than as anything the user could act on. Finished views now skip the rebuild.
- The
v2_leaderboardexample sorted only its real guild members, so a board padded with demo rows rendered out of order beneath a footer stating "Rankings sorted by MMR". The assembled board is now sorted.
[3.10.0] - 2026-08-10¶
Breaking¶
- A custom backend serving the registry namespace declares
Capability.OPEN_ROWSorCapability.RAW_SQL. This release ships the library's first schema migration, so the migration runner needs to know whether a backend can alter its own table or has nothing to alter. DeclareOPEN_ROWSif rows are open mappings (unknown columns round-trip throughrow_upsert/row_selectand a missing one reads asNone), orRAW_SQLwith the raw-SQL surface implemented so the migrator can run theALTER. A backend declaring neither is rejected atPersistenceMiddleware.initializewithPersistenceConfigErrornaming both remedies, rather than accepting the version bump and then failing on the first registry write carrying a column its table lacks. Every built-in backend already qualifies:SQLiteBackendandPostgresBackenddeclareRAW_SQL,InMemoryBackenddeclaresOPEN_ROWS. A backend with no migration pending is never asked for either flag, so a fresh install is unaffected whatever it declares.
Added¶
- Registry rows that stay unreachable now carry an age, and an operator can
act on it. Keeping an unreachable row is what stops a permission change
during startup from deleting a live panel, and the cost is that a channel the
bot will never see again is re-fetched at every boot forever. The first failed
fetch stamps
first_unreachable_at; the stamp clears the moment a fetch succeeds, and records the first failure rather than the latest so the age grows across boots instead of resetting.PersistenceManager.unreachable_sincereads the backlog andprune_unreachable(older_than_days=)acts on it, re-checking every candidate against Discord first: a row that answers is kept and cleared whatever its age, a definitive 404 goes regardless of age, and the rest are deleted only past the cutoff. A stamp alone is one observation, and a host that has not restarted for a month carries a month-old stamp from a single failure./cascadeui unreachablelists the backlog and takes an optional cutoff to run the same prune. Thepersistent_viewsschema migrates to v2 at startup; a migration that fails raisesPersistenceSchemaErrornaming the table, the version step, and the underlying error, and leaves the on-disk version alone so the next start retries. PostgreSQL needs table ownership forALTER TABLE, which the documented grants do not confer. prune_registrytakesreason=, labeling theREGISTRY_PRUNEDdispatch so a subscriber can tell an operator giving up on a row from a boot finding a- Unset, it keeps the value the method already computed.
refresh()andreload()say what happened to the edit. Both returnedNone, so a caller that had to know its render reached Discord inferred it from the absence of an exception, and areload()that returned at the throttle gate without attempting anything was indistinguishable from one that landed. They now return aRenderOutcome: rendered, skipped as unchanged, deferred to the throttle boundary, dropped in transit, or no message left to edit. Members compare equal to their string values, and a caller ignoring the return is unaffected.PaginatedRegion.hostandCollapsible.host. Both composites document hooks whose stated purpose needs the host they render into, and the only way there was the private_view. The read-only accessor mirrorsLeaderboardLayoutView.bot, which exists for the same reason. It readsNoneuntil the host's first render captures it.- A note on Section accessories in the components guide: a Section carries one accessory, so a row cannot hold both a thumbnail and its own button, and the two layouts that get closest are named.
Changed¶
- An empty leaderboard keeps its masthead. The empty-state page returned
before the masthead composed, so a board rendered its
bannerandtitlewhile it had entries and dropped both while it had none, and the banner reappeared on its own once the first entry landed. The masthead now composes above the empty-state page, and above it rather than inside it so an override ofon_leaderboard_emptyinherits the board's identity instead of having to know it was lost.build_titlereturning[]renders no masthead on that page, as on any other.titledefaults to"Leaderboard", so a board that never set one gains an## Leaderboardheading while it is empty.title=Nonerenders no heading on any page; to bare only the empty page, return[]frombuild_titlewhileranked_entriesis empty. An override that composes the banner or title itself now renders them twice; drop that composition, or return[]frombuild_title. - The leaderboard's page frames run on the empty page.
build_headerandbuild_footerwere skipped there, so an override that needed a frame on an empty board had to know it was lost and recompose the library's own return-type placement rule to get it back. Header content renders above the masthead and footer content below the empty-state card, each in the order returned. Two consequences worth checking on upgrade: an override returning frame content unconditionally now renders it on an empty board, and one that computes aggregates fromranked_entrieswithout guarding an empty slice raises during the empty-page build, where before it never ran.
Fixed¶
- Pruning re-reads a row before deleting it. Every reachability verdict
costs a Discord fetch, so on a real backlog the snapshot behind one can be
minutes old by the time it is acted on. A panel re-posted under its stable
key in that window writes a fresh row the verdict knows nothing about, and
deleting by key alone removed the live panel because the message it replaced
answered 404. Both destructive paths now confirm the row still points at the
message that was judged, and report a rewritten one as kept rather than
pruned. A backend that raises while that confirmation is read no longer
takes the whole reattach pass down with it: the key is reported rather than
acted on, never deleted unconfirmed, and the pass still schedules its warm
repaint. A prune that raises at the same seam is contained the same way,
where before it left restored panels unrepainted and let a later
reattach()re-register rows it had already restored. - A pruned registry row leaves this process's copy too.
prune_registrydeleted from disk and left the row in memory, so a laterreattach()walked rows whose messages were already gone and spent one fetch per dead row per pass. That is the cost the unreachable stamp exists to stop paying. The mirror is kept honest in the two other cases that move a row underneath a pass: one re-posted under its key is refreshed to its new coordinates rather than left pointing at the message it replaced, and one deleted out from under the pass is dropped. Neither is stamped unreachable, since one is live and the other no longer exists. - Panels sharing a channel repaint one at a time. Discord buckets message
edits per channel, and message writes carry sub-limits that response headers
do not report, so the concurrent post-ready
on_restorepass opened several edits into one channel's bucket at once and collected 429s no header-paced client can pre-empt. Panels that share a channel now repaint serially, in registry row order; panels in distinct channels keep the concurrent repaint underrestore_concurrency, so a deployment spread across channels boots as before. The reattach fetches stay concurrent: read buckets report their limits in headers, so the HTTP layer paces those itself. - A registry table whose version record is missing migrates instead of being recorded as current. No version row was read as a fresh install, which was safe while the table had only ever had one shape. Now that a migration exists, a store whose version record was lost (a partial restore, a hand-edited schema table) would be stamped at the current version while still shaped as the old one, and every write to a column that version claims would fail from then on. Rows are the discriminator: a table with rows predates the record and migrates, an empty one is a genuine fresh install. The check runs only on the boot that writes the record.
- A migrator passed to
migrators=that collides with one already registered now says so. The decorator path raises on a duplicate; this path skipped silently, so a consumer's migrator for a table and version the library had claimed was discarded without a word. InMemoryBackendsaid it declared every capability flag. It has never declaredRAW_SQL, so the docstring sent anyone reading it in an editor tooltip toexecute()andtransaction(), which raise on that backend.- A leaderboard that empties stops reporting the entries it used to hold.
ranked_entrieswas assigned after the empty-board short-circuit, so a board going from populated to empty kept the previous slice. Abuild_headerreading it for aggregate stats rendered totals for entries that no longer exist, above a card saying there are none. It is cleared before the empty page composes. - A leaderboard build that raises retries on the next rebuild. The entry
signature was stamped before the pages were built, so a hook that raised
once (an avatar resolver, a frame hook) left the board on its previous
pages, and the short-circuit then skipped every rebuild until the entry data
changed again. The signature now stamps only after the build returns, so a
transient failure recovers on the next rebuild without
force=True. - A second ephemeral send no longer lets the first one's timer take the new panel early. Both sends stamp their own token clock, but the first send's arm timer was already asleep against the older one, so it woke as much as thirteen minutes before the live token needed anything and swapped the working panel's children for a Continue Session button, freezing it against further state changes. A timer that wakes to find the deadline re-stamped stands down, and the second send's own timer arms on the new schedule.
- A view re-sent publicly no longer offers to reopen the public message.
Re-sending the same instance without
ephemeral=Truecancelled nothing and cleared nothing, so the first send's arm timer woke against a message that was no longer ephemeral and swapped the view's children for a Continue Session button. It stands down on waking now, when the view no longer manages an ephemeral message. Ephemeral navigation chains and reopens still arm. auto_refresh_ephemeral = Falseset after send is honored. The handoff timer read the flag on the way in and slept through most of the token's life without re-reading it, so a view pinning the handoff off mid-session was armed anyway.auto_refresh_ephemeralis honored on a view reached by navigation, in both directions. The arming deadline records when the message's webhook token expires, but it was written only when the sending view wanted the handoff, so the navigation gates read its presence as the policy. Presence cannot tell "derive this" from "explicitly off", nor "explicitly on" from "never written": a view pinning the handoff off was armed anyway the moment a push reached it and offered a Continue Session button around thirteen minutes later, and a view pinning it on stayed silent when the original send had declined. Every ephemeral send now stamps the deadline, since the clock belongs to the message rather than to any view on it, and each destination is judged on its own flag:Truearms against the original send's window,Falsestays off, and theNonedefault inherits the effective policy of the view it was pushed from. A pop hands the restored view back the resolution it held when it was pushed away from, so a departing child's declaration never travels up the chain. A rolled-back navigation re-arms only a source whose handoff had engaged. A control that arms on one press and executes on the next is the shape the off case reaches: a reopen rebuilds it from constructor kwargs, which is not where the record of an already-completed action lives.auto_refresh_ephemeralreads back what its author declared. Resolving theNonedefault wrote the derived answer onto the attribute itself, so a class declaring nothing reportedTrueorFalseafter its first send, and nothing could tell an author's explicit choice from the library's computed one. The frozen answer could not re-derive either: a second ephemeral send, or atimeoutchanged between sends, carried the first one. The declaration is now input the library never writes, and the resolution rides privately beside the arming deadline, re-derived at every ephemeral send, inherited down a push chain, and handed back on pop. Nothing else about when the handoff engages changed.- The ephemeral handoff no longer claims to preserve all state. It
reconstructs from constructor kwargs plus
get_nav_state(), so an attribute assigned after__init__is lost unless that hook names it, and the loss is invisible until a reopen fires. The guide said "preserves all state" and never pointed at the hook. - Overlapping
reload()calls on one view run one at a time. Twoon_loadbodies could interleave at any await inside them and corrupt each other's half-built render state: a forced leaderboard rebuild parked at its avatar fetch could resume into entries a transient empty reload had already cleared, drop its masthead on a populated page, and then stamp a signature that made every later unforced reload short-circuit onto it. The library reaches this itself, from the avatar backfill task a caller cannot serialize from outside, while the two sibling entry points into the same state were already guarded. A reload arriving mid-fetch now waits and re-fetches, so the last to run renders the freshest data. Areload()called from inside its ownon_loadraises instead of recursing, aforce=Truefolded into a throttle window is no longer dropped by a later unforced reload, and a reload gated while the deferred render task was mid-flight is no longer lost. card()rejects a Container child at the call. A Container is never a legal child of a Container, and the composition was accepted silently and rejected later by the placement validator, naming component indexes rather than the call that built it. On a pushed screen that surfaced as a failed navigation. The error names the child's position and points at placing it as a sibling.alert()andstats_card()compose their own children and admit no caller Container, so this iscard()alone.
[3.9.1] - 2026-08-03¶
Added¶
refresh_degradedreports a dropped render. Read-onlyboolon every view,Truewhen the lastrefresh()was dropped by a transport failure. Read it when the caller changed something before the render that should not stand if the render never landed.restore_on_dropped_render(*attributes)rolls back a dropped render. Context manager that snapshots view attributes and rebinds them when the render inside it was dropped. A control armed on one press and executed on the next used to collapse into a single press when the arming render failed: the button on screen still looked unarmed, so pressing it again executed rather than armed. That has been true of the in-place arm-then-confirm shape for as long as it has existed; the library now offers the rollback rather than leaving each caller to remember it. The snapshot holds each attribute's value, so flags and cursors come back and a collection edited in place does not. Passrebuild=to recompose the tree from the restored values: a V2 tree is the content, so rebinding the attribute alone leaves the screen describing a value that was rolled back, and the next refresh that does not rebuild first ships it.
Changed¶
- An aborted batch announces what it committed instead of discarding it.
Reducers run inline, so the dispatches before a raise have already changed
state; dropping the queue reported nothing while state had moved, and left
that change with no undo entry able to revert it. The committed prefix now
fires one
BATCH_COMPLETEand lands on the undo stack, and the exception still propagates.batch()remains a notification gate rather than a transaction: a block that must not leave anything behind rolls back itself, which the library's own pipelines now do. - A
BatchContextcannot be entered twice. Re-entering one after it closed collected onto a buffer that had already flushed, where the entries were never announced.store.batch()returns a fresh context per use; reusing a stored one now raisesRuntimeError. - Restored persistent panels repaint concurrently. The post-ready
on_restorepass ran one panel at a time because batch state was shared, giving a repaint tail linear in panel count on views that were already interactive. It now runs under the existingrestore_concurrencyceiling (default 8), which bounds both restore phases. - Dispatch cost no longer tracks how much data the store holds. Two
comparisons walked structures they could have skipped by identity. The
built-in reducers shallow-spread, so a slot an action did not write is the
same object on both sides of the undo diff, yet dict equality has no identity
shortcut and compared it entry by entry: every undo-tracked action paid for
the whole application namespace, measured at 493 microseconds against one
untouched 20,000-entry slot and now 2.3. A subscriber whose selector
returns a whole bucket was compared the same way on every dispatch, 20.8
milliseconds at 200 subscribers over 5,000 scoped keys and now 0.15. Views
never paid the second one, since their selector is wrapped in a tuple and
tuple comparison does shortcut identical elements; it fell on direct
store.subscribecallers. A batch commit also rebuilt its set of batched action types once per subscriber instead of once.InMemoryBackend's batched upsert rescanned every stored row for each incoming one, so a 200-row flush against 2,000 stored rows cost 167 milliseconds where the same batch into an empty namespace cost 8; it indexes the batch once and now costs 1.3. That backend is the reference implementation, so the shape it models is the one a new backend inherits. - The copy a custom reducer is handed is about twice as cheap. State is
dicts, lists and scalars, because it round-trips through
json.dumpson the persistence path, andcopy.deepcopycannot assume that: it consults__reduce_ex__and the copy dispatch table at every node. Walking the two container shapes directly and delegating anything else takes a dispatch against 2,000 scope keys from 5.8ms to 2.9ms. A memo is still carried, so a self-referential value terminates and a reference appearing twice in the tree stays one object on the other side. The contract is unchanged: the reducer receives its own copy and mutates it freely. - A reducer that forgets to return names itself. The store assigns whatever
comes back, so falling off the end of a reducer installed
Noneas the entire state and the failure surfaced at whichever unrelated read came next. A non-dict return now raises where the mistake is, naming the reducer, the action, and the missingreturn state; the store's own reducer guard logs it and keeps the previous state, so one dispatch is lost instead of the session. - The circular-attachment error names which views. It reported the two class names, and attaching two instances of one view class is the ordinary case, so it named the same type twice and said nothing. It now carries each view's id, the chain it walked, and what to do about it.
Fixed¶
- A dropped connection no longer surfaces as an error card. A request
that never reached Discord raises from aiohttp and carries none of the HTTP
types, so it escaped every handler: a reset during a page turn unwound out
of
refresh()intoon_errorand rendered a failure card over content that was fine.aiohttp.ClientErrorjoined the shared catch-tuple as a third sibling. Each surface degrades and logs atWARNINGrather than raising:refresh()re-ships on the next state change, the post-send message re-fetch keeps the message it just sent, andrespond()/open_modal()drop the undelivered notice instead of retrying it on the followup path, where a duplicate reply would be worse. Navigation tries the channel endpoint before giving up and otherwise rolls back, since a swap the user never saw must not tear the source view down. Every paging pattern rewinds its own cursor (page, wizard step, active tab, and both V2 composites), so a dropped turn no longer leaves the reader a position behind and makes the next press skip past content. Role toggles route their failures throughon_role_errorrather than escaping a dynamic button that has no handler beneath it. aiohttp's connect and socket timeouts read as transport rather than as a stalled edit: they inheritasyncio.TimeoutErrortoo, so the timeout clause saw them first, and with discord.py passing no session timeout they are the likeliest transport failure of all. The full per-surface table is in the known-limitations guide. (The umbrella isaiohttp.ClientErrorrather thanOSError:ServerDisconnectedErroris not anOSError, andasyncio.TimeoutErroris one from 3.11 but not on 3.10.) - An ephemeral view keeps trying to arm its refresh button. The handoff swaps the view's children for a Refresh button at T+810s and then drops every state notification, so that one edit is the only thing that can put the button on screen. A rate-limited attempt re-queues itself, but a dropped one gave up after a single retry and left the panel frozen with no button and most of the 90-second window unspent. It now retries for as long as the token can still carry an edit.
card(color=...)andstats_card(color=...)accept the int form their signatures document. discord.py coerces an int inEmbed.colour's setter but stores one verbatim onContainer.accent_colour, so a hex literal that had always themed a V1 embed reached the render digest as a bareintand raised after the message was already sent. Both builders and every colour style onThemecoerce todiscord.Colour, and the digest reads either form, so a Container built without a builder works too. A theme declaringprimary_coloras an int was the widest way in:accent_colourdefaults to it, and every themed card takes its accent from there. An out-of-range int andTrueare rejected where they are written. One read-back consequence:Theme.get_style()returns thediscord.Colourfor a style written as an int, so code comparing that value against the literal it passed needs.value.- A failure after the message was sent no longer reports the send as
failed.
send()'s rollback path ends at the Discord call, so anything raising past it left the view registered and the message live while telling the caller neither happened; a caller retrying on that answer posted a second copy, and the registration stayed behind permanently, holding aninstance_limitslot no live view occupied. Post-send bookkeeping now degrades and logs what is inactive on the message, and the same contract covers a persistent view whose registry write fails. A circularparent=chain, the other way into that window, is rejected before the send where the rollback still applies. - A raising hook no longer strands the view it was building.
send()registers state before runningseed_initial_state, andpush()quiesces the source before constructing the destination; neither rolled back if that caller code raised. A raising seed hook left a registered view with no message, invisible but counted by the instance limit, which underinstance_policy="reject"locked the owner out of the view class until the process restarted. A raising destination__init__left the source on screen with buttons that no longer rendered, because it had already unsubscribed. Both now run the rollback they already own and re-raise, and a constructor that raises aftersuper().__init__()no longer leaves its store subscriber behind.push()'s rollback runs inside its batch, so an aborted navigation no longer paints the destination onto the live message before destroying it. Both seams catchBaseException, since a cancellation strands exactly what a raise does. - Undo history survives actions that change nothing. Every dispatch from
an undo-enabled view pushed an entry, including ones that wrote no
application slot and left
shared_dataalone: a selection change, a view-local toggle, a re-render.undo_limitbounds the stack, so those entries evicted the ones a user was trying to reach, and four of them cleared a stack of three. A snapshot that can put nothing back is no longer pushed, on the per-dispatch path and at batch commit. The test is whethershared_datachanged, not whether it holds anything, because a session gaining its first shared data records an empty pre-value that is precisely what an undo has to restore. - A batch belongs to the task that opened it.
_batch_depthand the queued-action list were plain attributes on the store, so two tasks batching at once were indistinguishable from one batch nested inside another: the second never flushed its own, and whichever exited last fired a singleBATCH_COMPLETEfor both under onesource_id. Worse without any concurrency of the caller's own making, a dispatch from a background task landing while an unrelated view was sending or navigating was absorbed into that view's batch, reaching subscribers late and under the wrong action type; if that batch then aborted, the queued actions were dropped and the background action's notification went with them, so state had changed and no subscriber was ever told. Batch membership now follows the task, and nesting inside one task absorbs exactly as before. Undo diffs are captured per action and merged at commit rather than diffed against live state, which had pulled an overlapping batch's slot writes into another view's undo entry; a slot a batch writes and then restores leaves no entry at all, and a batch holding undo records but no actions of its own finalizes them rather than discarding a snapshot for a change that committed. Profiling frames were shared the same way: withperfon, overlapping dispatches took each other's edit frames and a batched reducer's time landed on whichever unbatched dispatch was in flight. - A closing card composed before teardown reaches the message. The V2
teardown edit shipped only when the freeze disabled something, which is
right for a display view that has nothing to disable and wrong for a view
that clears its tree and composes a farewell card first: that view has
nothing left to freeze either, so
exit()andon_timeout()dropped the card and left the original controls on screen looking live. The next press reached a stopped view and Discord reported it as failed. The edit now also ships when the tree no longer matches the last render, and the no-op PATCH the guard exists to prevent is still skipped. Both challenge prompts in the examples expired this way, and both now print their deadline as a live Discord countdown timestamp instead of a fixed second count that was wrong the moment it was sent. - Four examples now key shared state per guild.
v2_battleship.py,v2_computed.py, andv2_dashboard.pyeach wrote every guild's data into one slot, and the battleship one decides hit-or-miss from that state, so a player in two matches at once had one overwrite the other's fleet.v2_pagination.py's two commands shared a view class and itsinstance_limitslot. Worth re-reading if one was used as a starting point.
[3.9.0] - 2026-07-30¶
Security¶
ToggleButtonacceptedowner_only=Trueand never enforced it. The gate lives in the callback wrapper thatStatefulButtoninstalls, andToggleButtonreplaced that wrapper with one of its own after construction, so the flag was stored and never read. Any user could operate a toggle meant for the host, and the view'son_unauthorizednever fired. Present since the per-component gate shipped in 3.2.0. The toggle now runs inside the shared wrapper, which also restores the three other guarantees it had been missing: no dispatch once the view is finished, the acting interaction bound so the refresh takes the one-request fast path, and a synchronous callback accepted. Routing a self-mutating component through the shared wrapper also moved where its value is read:COMPONENT_INTERACTIONnow records the state the toggle landed on rather than the one it was clicked in. Selects and plain buttons are unaffected, since neither changes its value during its own callback. Anyone usingowner_only=on a toggle should treat it as having been open to everyone.
Added¶
confirm_styleandcancel_styleonconfirm_section(). The builder exposed labels, emoji, andcustom_idbut hardcodedsuccessfor confirm anddangerfor cancel, so a destructive prompt rendered a green Delete beside a red Keep, and its own docstring example pairedconfirm_label="Delete"with a red card while teaching exactly that inversion. Both default to the values they replaced, so nothing that worked changes colour. Every builder that takes a style now also rejects a value that is not adiscord.ButtonStyle: a bare"danger"used to construct cleanly and fail at send with an attribute error naming neither the builder nor the parameter, which the class-attribute validator has always caught on the equivalent class attributes.id=on the V2 builders. Discord gives every component an optional 32-bitid, unique per message and auto-assigned sequentially when omitted, and discord.py surfaces it onContainer,Section,Thumbnail,MediaGallery, andTextDisplay. None of the builders forwarded it, so composing a view from them was the one path that could not set an id at all: reaching a documented upstream field meant dropping to rawdiscord.uifor that node.id=names the component a builder returns, so the nineteen that return exactly one take it and the two that return a list do not:confirm_sectionyields a text display and a row of buttons,button_grida row per grid row, and neither has a single node for an id to mean. Assign.idon the returned components for those, or set it per button insidebutton_grid'scell_factory, which already owns every other per-button attribute.- Component ids are checked before the message is sent. An id must be a
whole number from 1 to
MAX_COMPONENT_ID(2147483647, exported from the package root), and no two components in one message may share one -- Discord's rules, previously discoverable only as an HTTP 400 with a form body that named a numeric path rather than a component. The builders reject a bad value where it is written, naming the builder; the uniqueness walk runs at the same three seams as the placement check (initial send, refresh, navigation edit) and covers V1 and V2 alike, since both carry ids. It can only refuse what Discord already refuses, so a view that sends today still sends. nav_depthreads how many views sit beneath this one. Zero on a view opened directly, one on the first push. This release disables a Back button with nowhere to go, but a screen reachable both by a push and by its own command usually wants that button absent on the root entry rather than present and greyed, and deciding that needs the stack the library already holds:make_nav_row(back=bool(self.nav_depth)). Without a read of it the caller carries its own root flag, which duplicates the stack and lives on whoever constructs the view, so a class that builds its nav row in two branches has to remember the flag in both. Safe to read insideon_load, since the stack is assigned before the load hook runs. Named for theundo_depth/redo_depthpair it sits beside.
Changed¶
PaginatedRegion.set_pagetakes a negative index.set_page(-1)is the last page, counting from the end the way Python indexing does. It is the only way to name the last page without first knowing how many there are, which is what made "add a row, then show it" cost two reads: asking the region for its page count needs the data loaded, and the jump then re-renders and loads it again.await pager.show_page(-1)does the whole gesture in one read and one edit, since it seeks and re-renders together.set_pagemoves the cursor only, for the seams with no tree to re-render yet, and a seek stays invisible until something rebuilds.- The
{label: callback}builders accept a sequence of pairs.button_row,tab_nav,key_value,choice_row, and both tab views read their argument with.items()or.keys(), so the same data written as[("Save", on_save), ("Cancel", on_cancel)]failed on anAttributeErrornaming a method rather than a parameter. The pair form is the same information in the order it was written, so it is converted rather than refused, and anything that is neither a mapping nor a pair sequence now names the parameter it was passed to. Mappings other thandictwere already accepted by most of these and now are by all of them. - Type hints that named less than the code accepts. Several parameters
advertised a narrower type than they have ever taken, which matters more
than a documentation slip: the obvious guard to write against a
listannotation isisinstance(items, list), and that would have rejected the tuples, ranges, and stringsfrom_datahas always paged.itemsisIterable[Any], which is what it reads.MediaInputnamesdiscord.UnfurledMediaItem, which every media builder has always passed through. The builders that now take a sequence of pairs say so rather than namingDict, and each saysMapping, since aUserDicthas always worked.
Fixed¶
- A non-string
label,value,content, orplaceholdercrashed the placement validator. discord.py stores these fields unvalidated, so a caller can pass an int and it reaches the payload unchanged. The character and empty-string guards calledlen()on the raw value, so an intSelectOptionvalue raisedTypeError: object of type 'int' has no len()from inside a pre-flight check instead of the send it was meant to protect. All six guarded fields now measure only strings. Present since 3.6.0, when the length caps landed. from_data()validated none of whatfrom_cursor()validates. The two constructors take the same page size and the same formatter, and the cursor one rejects a non-callable and a non-positiveper_pagewith directed messages. Its sibling checked nothing, soper_page=0surfaced asrange() arg 3 must not be zeroand a string page size as an indexingTypeError, whileper_page=-1raised nothing at all and built a view with zero pages. Both now reject the same mistakes in the same words. A generator of items is consumed rather than refused, and tuples, ranges, and strings keep working as they always have despite the annotation naming a list. One input changes meaning:per_page=Truepreviously paged by one, since a bool is an int, and is now rejected the way its sibling has always rejected it.- The paginated views ignored an async formatter unless it was a plain
coroutine function. All three seams that format a page asked
inspect.iscoroutinefunctionbefore deciding to await, which answersFalsefor an object whose__call__is async, so the formatter's coroutine was stored as the page and rendered as a repr. It affected the eager build, the cursor mode's page fetch, andrefresh_dataalike.validate_fielddocuments that same object as a supported shape. All three now await the result rather than interrogating the callable, which resolves every shape any of them accepts. - A synchronous post-event hook logged as though it had failed. The
wrapper that runs
on_page_changed,on_tab_switched,on_step_enteredand their siblings awaited the hook unconditionally, so an override writtendefrather thanasync defran correctly, returnedNone, and then failed on awaiting thatNoneinside the wrapper. The failure was caught and logged as a raising override, which named the user's hook for a fault in the caller. Both shapes are accepted now. - A
Collapsiblewhoserevealorsummarywas async slipped its own check. The constructor rejects a coroutine function, but that predicate recognises only the object itself, so an instance with an async__call__passed it and returned a coroutine into a synchronous render. The two halves then failed differently: a revealed coroutine reachedadd_itemand raisedexpected Item not coroutineon the caller's line, loud but unnamed, while a summary coroutine was truthy, became aTextDisplaybody, cleared the placement validator, and surfaced only as a JSON serialization error at send, naming neither the parameter nor the class. Both are caught at the render call now with the message the constructor would have given. Relatedly, a wizard step condition written as an async generator, one strayyieldaway from a correct predicate, was neither awaitable nor falsy, so its step rendered with nothing reported; it warns. dispatch()accepted an action where it wanted an action's type. The Redux idiom most callers arrive with isdispatch(action), and reducers here receive exactly that dict, so handing one todispatchis the natural mistake. It reached the reducer lookup and failed oncannot use 'dict' as a dict key, which names neither the parameter nor the shape. A non-string type was quieter: nothing raised, and an action no reducer or subscriber could ever match was recorded against a type likeNoneor5. Both are rejected at the entry point now, and the dict case says how to split it.dispatch_scoped_asand the view-leveldispatchroute through the same seam.dispatch("")raisedTypeErrorfor what is a value problem. An empty action type is the right type carrying a wrong value, which is where the two stdlib exceptions divide. It raisesValueErrornow; a non-string still raisesTypeError.- A wizard step or form field written as a dict escaped the checks its
typed form has always run.
WizardStepandFormFieldvalidate at construction; the raw-dict alternative both patterns document was passed through untouched, so the same mistake behaved differently depending on which spelling was used. Mostly it stayed quiet: a step whose builder was not callable crashed at render, but one whose condition was not callable was swallowed by the visibility guard and rendered anyway, and a field with an unrecognisedtypeproduced no control at all, so it simply went missing from the form. The dict form stays the looser of the two, which is its purpose. It reads onlybuilder,validatorandcondition, and a step with none of them is a supported shape that renders its navigation alone. What it no longer accepts is a value under one of those keys that cannot be called, or a field type nothing knows how to draw. - A leaderboard's entries were read for their shape without being
checked for it. Both the
entries=kwarg and theget_entries()hook feed a signature helper that unpacks each entry and reads the second item as a mapping, so[(user_id, score)]and{user_id: stats}, the two most natural guesses, failed with'int' object has no attribute 'items'andcannot unpack non-iterable int objectfrom inside a generator expression that named neither the parameter nor the shape. The failure fires duringsend(), so nothing surfaced until the board was displayed. Entries are checked where they enter now, naming the source and the offending index. A mapping of id to stats and a one-shot iterable are the same data in another container and are converted; lists of lists and tuples of tuples keep working as they always have. - Toggle labels were read by index without being checked. Both toggles
take an on/off pair and read
labels[0]andlabels[1], so a one-item sequence raisedIndexErrorfrom inside the builder. A bare string was worse: it indexes without complaint, solabels="Enabled"rendered a button captionedEin one state andnin the other, with nothing raised anywhere.cycle_buttonhad rejected a mismatched label list all along; the toggles now check their pair the same way. - A cell factory was type-checked on its first cell only.
button_gridvalidated the first button it received and appended the rest untouched, so a factory returningNonefor one position, the natural way to leave a gap, failed insideActionRowon an attribute the caller never wrote. Every cell is checked now, and the error names the row and column. choice_rowrejected the values its own docstring promised.Choice.valueis documented as any Python object, but active values were held in a set, so a list or a dict raisedcannot use 'list' as a set elementon the containment test, even with nothing selected. Active values are a list now and compare by equality. Options cap at 25, so the scan costs nothing and unhashable values work as documented.- Numbers, separators and single-item arguments reached operations that
assumed their type.
progress_barcompared and divided its arguments before checking them, so a string bound failed on the operator rather than the parameter.EmojiGridcheckedrows,colsandfillbut notcell_seporcorner, which reachstr.joinduring construction.Theme(styles=...)read its argument by key, so a sequence of pairs failed onlist indices must be integers, and now converts the way the builders do. AModalgiven a single input rather than a list failed onnot iterable; it now says which it wanted. - The media builders disagreed with each other and with
banner=.gallery,image_section, andfile_attachmentshare oneMediaInputunion, and passing adiscord.Assetto it behaved three ways:galleryrefused it at construction through discord.py's own check, while the other two accepted it and crashed at send inside the payload build with an attribute error.LeaderboardLayoutView'sbanner=had always coerced the same objects, somember.display_avatarworked there and nowhere else, despite being one attribute away from the.urlform every docstring example shows. All four now resolve an Asset, and all four reject an unusable value at construction naming the builder and the argument that carried it, down to whichgalleryitem was wrong. Adiscord.File, a URL string, and anUnfurledMediaItemare unchanged. - Option lists accepted entries that were not options.
CheckboxGroup,RadioGroup, andDropdownconverted dicts and appended everything else untouched, so a list of plain strings became a list of plain strings and reached Discord as options carrying neither a label nor a value. Passing a single option dict without its list was worse: iterating a mapping yields its keys, sooptions={"label": "A", "value": "a"}built two options namedlabelandvalue, which the one-to-ten count check then counted and approved. Both surfaced only when Discord rendered the component, as an attribute error from inside discord.py and "This interaction failed" on screen. Entries are now checked where they are read, naming the index, and a mapping passed in place of a list says so.StatefulSelectis checked too.Dropdownis the seam that accepts dict shorthand, and its base class took the same shapes without converting them, so the three failures above reached Discord unaltered through it. It now names the offending index and points at the sibling that does the conversion. - Three guards failed on the inputs they existed to screen. A modal
title or label that was not a string either crashed inside the length
check with
object of type 'int' has no len()or, when it happened to have a length of its own, passed both tests and reached Discord as a list or a bytestring. A numeric bound that was not an int either crashed on the comparison or slipped through as a float or a bool, which Discord rejects at modal-open. And a menu category that was not a mapping died inside the category validator on'tuple' object has no attribute 'get', while one missinglabelorviewsurfaced later as a bareKeyErrorfrom whichever builder read it first. All three now name the parameter, the type they got, and the shape they wanted. Twelve call sites share the two input helpers, and the category check runs once per entry with the index in the message. Mappings other thandictkeep working. - A V1 form's dropdown showed the wrong selection on the edit that
recorded the right one. The option marks are stamped when the controls
are built, and V1 answers a pick by shipping an embed edit rather than
rebuilding its controls, so Discord re-rendered the select from a payload
still carrying the seeded marks. The user chose B, the summary read B, and
the dropdown beside it snapped back to A. A multi-select was worse: every
tick cleared on the very edit that confirmed it. The same stamps went
stale on a pop, where restored entries rendered over controls built before
the values arrived. Both paths re-derive from the form's values now, using
the
set_selectedhelper the library already shipped for exactly this and had never called. V2 was unaffected, since it rebuilds its controls on every update, which is the parity gap that hid this. - A Back button with nowhere to go destroyed the panel it sat on.
make_nav_row()defaults toback=True, so a view that is sent rather than pushed rendered Back against an empty stack, and pressing it took the empty-stack path, which froze every component on a V2 view and stripped them on a V1 one. The only recovery was running the command again. Two things change. Back is disabled while the stack is empty, the way the paginated and wizard controls beside it already derive their state from a cursor, and the empty-stack path acknowledges the press without touching the message. The disabled state is resolved at the render seams rather than when the button is built, because a pushed view is constructed before its stack is assigned: reading it at build time would disable a working button on any view that composes its tree in__init__. Both paths share one implementation now; the V2 freeze override is gone. A view that wants Back to close the panel overrides_clear_on_empty_back, thoughexit()and the Exit button are the surfaces built for that. - Anything you write for the library had to be
async def, or the library failed on your behalf. Every seam that runs your code awaited its result unconditionally, so a synchronous function ran, returned a value, and then failed on awaiting that value. Fifty-nine seams were affected, and between them they covered most of the surface you write against: everyon_*override on a view (on_load,on_submit,on_state_changed,on_error,on_finish,on_pre_send,on_unauthorized,on_restore,on_message_deleteand the rest), theseed_initial_statepreload hook, plus store subscribers andstore.on()hooks, custom reducers, component callbacks, thewith_loading_state/with_confirmation/with_cooldownwrappers,with_retryandwith_error_boundary, wizard and tab builders and validators,choice_rowandcycle_buttonandtoggle_buttonhandlers, and the paginated cursor's fetch function. What surfaced varied by seam and none of it named the cause: a wizard builder gave'list' object can't be awaitedat render, a subscriber logged an error against the user's own callback, and a view whoseon_loadwas missing itsasyncfailed to send at all. A custom reducer was the quietest of them: the store caught the failure and logged it, so the action completed and the state never changed. These now test the result withinspect.isawaitable, which is what the rest of the library already did, and take either shape. A wizard step'sconditionis the inverse case: it was never awaited, and a coroutine is always truthy, so an async predicate rendered its step regardless of the answer, with nothing raised and nothing logged.WizardStepnow rejects a coroutine function at construction, matching howCollapsibletreatsreveal, and the visibility check recognises an awaitable answer, warns, and shows the step. Both are needed: a step declared as a raw dict never passes throughWizardStep, and neither construction check sees an object whose__call__is async. - A
build_uithat returned a coroutine had the library's own work done against a tree it had not built.__init_subclass__wrapsbuild_uito set the ambient theme and stabilizecustom_ids, choosing a sync or async wrapper by inspecting the function. Several shapes answer "not a coroutine function" and still return a coroutine (a callable instance with an async__call__, apartialaround one, a plain function returning one), so they took the sync wrapper, which stabilized ids and tore the theme down before the body ran. The ids therefore kept the random hex discord.py assigns, which changes on every rebuild and churns the dispatch table that stabilization exists to keep still, and acard()built with no explicit colour missed the view's theme. The sync wrapper now checks what it got back and, holding a coroutine, returns one that re-enters the theme and stabilizes once the body has resolved. It stays synchronous otherwise, because three classes callbuild_ui()from__init__. - An async
build_uion a pattern that builds in__init__did nothing, quietly.DisplayLayoutView,MenuLayoutViewandRolesLayoutViewcompose their tree in the constructor, which cannot await. Anasync def build_uithere was called and discarded: the view constructed, its tree stayed empty, and the only signal was a "never awaited" warning most bots never surface. The mistake then arrived atsend()as a placement error naming "no top-level components" -- the symptom, nowhere near the cause. All three now refuse it where it happens, naming the class and pointing aton_load(), the hook the library awaits before every render. The refusal covers the shapes aniscoroutinefunctioncheck misses, since it reads whatbuild_uireturned rather than what it looks like. - A wizard step validator's answer was unpacked without being read. The
documented return is
(valid, error), and the code took it apart on the spot. A bareTrue, the obvious near miss, raisedcannot unpack non-iterable bool objectand reached the user as "Something went wrong." Worse was the shape that did not raise: any two-element iterable unpacks, so a two-character string or a two-key dict handed back a truthy first element and the wizard advanced past the step the validator was rejecting. A bare bool is now read as the answer it plainly is, a pair is read as documented, and anything else is refused with a message naming the step and the shape it owes. - A component interaction recorded its value nested inside itself.
ActionCreators.component_interactioncollectedvalue=into a keyword bag and then stored the bag undervalue, so every click wrote{"value": {"value": True}}intostate["components"].valueis now a named parameter and records what it was given; any other keyword lands beside it under its own name. Nothing in the library read the nested shape, but a subscriber that dug through the extra layer needs to stop. - A computed value could cache the wrong answer permanently. The memo
compared the selector's output against the previous output, but held
that previous output by reference. A slice mutated in place carried the
stored reference with it, so the check compared the slice against
itself and kept returning the stale result. A later correct replacement
did not recover it either: the aliased reference already matched the new
value while the cached result predated it.
access_slotmutates in place by design andseed_initial_statehands it live state, so a computed read before another view seeded its slot stayed wrong for the life of the store. The memo now keeps its own copy, and recomputes every time rather than trust an input it cannot copy. - Constructing a
Themeedited the dict you constructed it from. The six style defaults were seeded into the caller's own mapping, so passing a dict toThemesilently added keys to it, and two Themes built from one base dict shared a single live mapping where restyling either restyled both. The styles are copied before the defaults are applied. - A failed cosmetic edit could cancel the action it was decorating.
with_loading_stateshows its loading state before running the wrapped callback. On a plaindiscord.ui.Viewthat pre-edit caught only the already-answered case, so a deleted message or a transient 5xx propagated and the click did nothing -- while the branch three lines above, for stateful views, had always swallowed the same failure. The two branches agree now. - Three exception types Discord raises are siblings, and half the
library caught only one of them.
RateLimitedandInteractionRespondeddo not inherit fromHTTPException, soexcept discord.HTTPExceptionmisses both.RateLimitedreaches user code whenever the bot passesmax_ratelimit_timeoutto its client, and the escapes were not cosmetic: the ephemeral-reopen cleanup skipped itsexit()and left the replaced view registered holding its instance-limit slot, a participant-limit rejection skipped the send rollback and leaked a registered view,with_confirmationskipped the confirmed action its own comment promised to run, and a rate-limited acknowledgement during navigation became a full rollback and an error embed. Every seam in the view base, navigation, the interaction helpers and the component wrappers now catches what it meant to, and says which of the three happened rather than printing two question marks where aRateLimited'sretry_afterbelongs. - A refresh past the ephemeral cliff reported an error nobody could act
on.
exit()andon_timeout()both read the 401 an expired 15-minute webhook token returns as ordinary lifecycle and log it at debug.refresh()re-raised it instead, so every state dispatch reaching such a view surfaced an ERROR and a full traceback from the store's subscriber wrapper, for a condition the library treats as normal at every other edit seam. It is absorbed at the same level as its siblings now. Navigation inherits the change: an edit onto a message no token can reach is no longer a reason to roll a push or pop back to its source. - A
slot_propertydeclared wrong returned its default forever. Thekey=callable was never checked at construction, and errors raised by the callable itself were swallowed by the same handler that absorbs a store that is not wired yet, sokey="user_id"(a string, not a callable) andkey=lambda self: self.usr_id(a typo) both read as a permanent default that looks correct in every test. A non-callablekey=is now refused where it is declared, and one that raises is reported instead of being folded into the ordinary empty read -- once per class, since a descriptor is read on every attribute access and a line per read buries the one that matters. ToggleGroupbuilt collidingcustom_ids. Ids came from the option label alone, so two groups in one view that shared a label sent Discord a duplicate id and the message was rejected. Akey=prefix disambiguates them, matchingchoice_row'scustom_id=. The id is otherwise built exactly as before, so a persistent panel already on screen keeps the ids its buttons are registered under.CompositeComponent.add_to_viewtook arowand ignored it. The parameter has always been in the signature and never read, so components landed wherever discord.py placed them. It now sets the row it was given.state["components"]disappeared once a view was destroyed. Two reducers removed the key entirely when the last entry was filtered out, even though it is one of the four keys the initial state establishes. A subscriber that indexed it directly worked until the first teardown and then raised. It is emptied now, not removed.- A reducer registered for
BATCH_COMPLETEsilently never ran. The batch commit fires that action straight at subscribers and hooks, bypassing dispatch, so no reducer could ever see it -- and the collision guard did not list it, so registering one looked like it worked. It is reserved now, and@cascade_reducersays so at decoration time. - An async subscriber selector was accepted and did the opposite of its
job. The change check runs inline in dispatch and cannot await, so an
async defselector handed back a fresh coroutine on every call. A coroutine never equals the previous one, so the subscriber was notified on every single action (precisely what passing a selector asks the store to avoid), and each unawaited coroutine printed a warning from the bot's own console.subscribenow refuses one where it is passed, including the two shapes a plainiscoroutinefunctioncheck misses: an object with an async__call__, and afunctools.partialaround a coroutine function. - The selector guard reached one of the three places a selector is
supplied.
subscriberefuses an async selector, but it only ever sees what it is handed, and a view'sstate_selectoroverride arrives wrapped in a lambda that is never a coroutine function whatever it closes over. Anasync def state_selectortherefore sailed past the check and the view went silently deaf: the store compared one fresh coroutine against the last, they never matched, and the notification was skipped on every dispatch.@computed's selector was not checked at all, not even for being callable. Both are refused now, where they are declared, and both catch the shapes a plainiscoroutinefunctionmisses. - Restoring persistent views warned about the pattern it documents.
A view class not yet imported when
initialize()runs is the state the two-pass design exists to absorb: the row lands inskippedandreattach()collects it once the cog has loaded, which is what makes import order stop mattering. Each such row was reported at warning level anyway, with advice to import the module beforeinitialize()-- the one thing the sanctioned pattern deliberately does not do. A bot with a dozen panels logged a dozen wrong warnings on every boot, which teaches an operator to skim the level. That detail now sits at debug, where the summary's own comment already said per-view detail belonged, and the warning is saved for a class still missing after areattach()pass, when it is a real problem. Unreachable channels got the same treatment: one warning naming the count rather than one per row, since the count is what an operator acts on. - A broken selector was silent forever. A subscriber selector that raised was swallowed with no log at all, on every dispatch, degrading to notify-on-everything -- which is the safe answer, and indistinguishable from a subscriber that legitimately wants every action. It reports once per subscriber now. Three other silences got the same treatment: an attached child that failed to exit left no trace before the list was cleared, a gateway wait that failed skipped the post-ready re-render without saying so, and a failed ephemeral reopen blamed a "refresh factory" on the path where the caller never supplied one.
SlotPolicy(persistent=True)never persisted anything. Declaring a slot persistent inApplicationPersistence.slots, or throughregister_slot_policy, registered its retention policy and not the slot itself. The middleware scans an opt-in set that neither route wrote to, so it skipped the slot entirely and a setup copied from the persistence guide put nothing on disk and said nothing about it. Both routes now register the slot the waypersistent_slotsandaccess_slot(persistent=True)do. Slots declared this way begin persisting, and rehydrating on restart, as soon as you upgrade, which is what declaring them always claimed.- The missing-aiosqlite error named a package that does not exist. The
zero-config path told you to run
pip install 'cascadeui[sqlite]'; the distribution ispycascadeui, which the two backend modules had right all along. The name is written by hand at each hint, so a test now walks the source and fails on any that stops matching the distribution. - A shutdown could discard the writes it was shutting down to save.
The flush drains its dirty rows into a local batch before handing them
to the backend, and the retry that puts a failed batch back caught
Exception, whichCancelledErroris not. So a cancel arriving while the write was in flight lost the batch outright: buffers empty, nothing committed, nothing retried.flush_allopened exactly that window on every shutdown, cancelling in-flight flushes before its own final drain, which is the one pathcloseexists to guarantee. A cancelled batch is now returned to the buffers under the same both-sides guard the retry uses, so the drain that follows finds it. - The attachment example taught a one-image technique without its bound.
refresh(attachments=[...])replaces the message's whole attachment list, which is correct for the single-image swap the example demonstrates and wrong the moment a tree references two. Adapting it to paged content ships each page's reference with only that page's bytes attached, and every other page renders as a permanent loading placeholder. The example now states that the list must carry every file the tree references, and shows the multi-image shape.
[3.8.0] - 2026-07-27¶
Breaking¶
MenuLayoutView._build_header()/_build_footer()removed. The underscore names were deprecated in v3.4.1 and delegated to the publicbuild_header()/build_footer()since. Rename any remaining overrides; the public hooks take the same arguments and return the same shapes.refresh()rejects edit kwargs that only some of its endpoints accept.refresh()picks between the interaction, webhook, and channel endpoints at runtime, andsuppress,suppress_embeds, anddelete_afterare each accepted by only one or two of them, so a call carrying one worked only while the ack race kept landing on a compatible path. All now raise aTypeErrornaming the portable set (content,embed,embeds,attachments,allowed_mentions). Editview.messagedirectly for a one-off that needs a non-portable field. The same guard applies to the dict arebuild=callback returns.
Added¶
allowed_mentionson views. A class attribute governing mention behavior for a view's own message, plus anallowed_mentions=parameter onsend()that overrides it per message. Applies to the initial send and to every refresh and navigation edit, so a panel that re-renders cannot re-ping the users it names.None(the default) defers to the bot's client-level rules. Reach for it on rosters, leaderboards, and turn announcements; pass the parameter when a one-off notice genuinely should notify.custom_idon the interactive V2 builders.button_row,confirm_section,cycle_button,toggle_button, andtab_navaccept a base id, suffixed per button ({custom_id}_0,{custom_id}_confirm). Without one, builder-produced buttons carry ids that change every restart, which made all five unusable inside aPersistentLayoutView.image_section()accepts extra text lines.image_section(primary, secondary, url=...)renders a two-line entry beside its thumbnail, the shape leaderboard rows previously hand-built aSectionfor. Discord's three-children cap is enforced at construction.link_section(disabled=...),gallery(spoilers=...), andstats_card(spoiler=...), matching the parameters their sibling builders already took.PaginatedRegion.show_page(). The async jump-and-re-render counterpart to the view-sideset_page(). The region's ownset_page()stays synchronous and render-free for the pre-attach restore path.DynamicPersistentButton.open_modal(). The sibling of the button'srespond()for the one response type that cannot follow a defer. A persistent button's click arms an ack backstop beforeon_clickruns, so opening a modal directly raced it; both now share the view side's guard.StateStore.scope_key(scope, *, user_id=None, guild_id=None). The single writer of the scope-key format, returningNonewhen the scope's required ids are missing. The scoped-state readers, the instance-limit index, and the sync availability pre-check all route through it, so the format is defined once.0is a legitimate Discord id and is never treated as absent; a caller that wants falsy ids treated as missing normalizes withor Nonefirst.view.validate(). Raises if the view's tree is one Discord would reject, running the same custom_id and placement checks the library runs before every send, plus the auto-generated-id check on a persistent view (the one that catches a panel coming back with dead buttons after a restart). The point is testing a view with no Discord connection: compose withon_load()(orbuild_ui()), count withwalk_children(), and validate, all offline. Previously the first and third steps had no public entry, so a test asserting a panel still builds had to reach into private methods.- A warning when a navigation step changes
exit_policy. The policy is declared per class but push and pop edit one message in place, so a stack whose screens disagree tears the same message down differently depending on how deep the user went. Each class is individually valid, so nothing at definition time can see it. Declare the policy on a shared base when every screen should agree; a destination that deliberately differs still works.
Changed¶
LeaderboardLayoutViewsuppresses mentions by default. Entries without adisplay_namerender as<@id>, so a stock leaderboard notified every ranked player on send and again on every refresh. Rows still render as mention links; they no longer ping. Overrideallowed_mentionson a board that wants the notification.- The lobby, battleship, and tic-tac-toe examples suppress their own mentions. Each renders player mentions in a body that rebuilds on every interaction, so a full game re-notified both players once per move.
- Button labels and emoji are validated at class-definition time. The
paginated, wizard, and form patterns already checked the
*_stylemember of each button triple; the*_labeland*_emojimembers are now checked too, matching whatPaginatedRegionenforced. nav_rebuildis validated at class-definition time. A bare function or lambda assigned in a class body binds as a method and receivesselfwhere the destination view belongs, which previously surfaced as an arityTypeErrorat navigation. It now raises at import naming thestaticmethod(...)fix.functools.partialis rejected on every supported Python rather than only where it behaves as a descriptor.- The navigation example adopts
nav_rebuild. It repeated an identical rebuild callback at six push and pop call sites; the destinations now name their own once, and one call site keeps an explicitrebuild=to show the override winning.
Fixed¶
exit_policyhad no effect on the exit controls the library ships.make_exit_button,add_exit_button, andmake_nav_roweach passeddelete_message=Falseexplicitly, which is the one value that stopsexit()from consulting the policy, so a view declaringexit_policy = "delete"froze on close instead of deleting, with nothing to indicate why. All three now default toNoneand defer to the policy; an explicitTrueorFalsestill wins. A view left at the"disable"default is unaffected.StatefulLayoutView.add_exit_button()silently swallowed unknown keywords, including typos and the V1-onlyrow=. The signature is closed now, so a wrong argument raises at the call site.exit_policywas documented as governingon_timeoutand the exit-button helpers. It never governed the former and no longer fails to govern the latter. A timed-out view freezes regardless of the policy, because an expiry is not a close gesture; the guides say so, andon_timeoutis the override seam for deleting instead.- Persistent views accepted components whose ids change on restart.
_stabilize_custom_idsanchors rewritten ids on the view instance, and the rewrite cleared both signals_validate_custom_idsused to recognize a missing id, so a panel built from V2 builders passed validation, shipped, and came back with dead buttons after the next restart. The rewrite is now marked and rejected at validation. - Custom-id stabilization stamped ids onto display components. Every
discord.ui.Itemsets the attribute the walk was gated on, soTextDisplay,Container,Separator,ActionRow, andSectionwere all being rewritten. The walk discriminates by type instead. - A composed
custom_idcould exceed Discord's 100-character cap. The builders append a suffix to the caller's base, and the composites and the id stabilizer compose their own, so a legal input could be pushed over the limit by a string the caller never sees. The builders reject at construction naming the length to trim to, the stabilizer folds the overflow into a digest (it runs inside everybuild_uiand must not raise), and the placement validator backstops every remaining path including hand-built ids. - An empty
TextDisplayfailed the entire message. Discord requires non-emptycontentand rejects the whole payload, so a formatter hook returning""for one entry took down every component beside it. The condition is data-triggered: a leaderboard renders for nine players and fails when a tenth arrives whose optional fields all happen to be absent.image_section()now skips empty lines (a Section with one text child and an accessory is legal, so the entry still renders), the leaderboard's no-avatar fallback skips an empty half instead of joining it into a dangling newline, and the placement validator rejects empty content pre-flight for hand-assembled trees. The validator previously enforced TextDisplay's upper bound and every container's lower bound, so the empty case was the one gap in an otherwise symmetric set. - An empty
SelectOptionlabel or value failed the whole select, the same shape and the same data-triggered trigger. Both are rejected pre-flight now. card,action_section, andtoggle_sectionaccepted an empty string and shipped the same doomedTextDisplay. All three reject at construction now, naming the builder and the parameter, which points at the formatter that produced the blank rather than at the primitive that carried it.- A
MenuLayoutViewcategory without adescriptioncould not be sent. The field is optional, but the empty string reached aSection, which Discord rejects for having no text. The category label renders as the section text when no description is given. stats_cardwith an empty title rendered a bare##. It now renders no heading at all, matching how the leaderboard'sbuild_titletreats one.- Modal titles and input labels over Discord's 45-character cap, or empty,
failed at modal-open. Both are stored unchecked by discord.py, so a label
built from a schema field or a record name failed only for the data that
happened to be long. Both are now construction-time
ValueErrors, and the form's grouped edit label (which doubles as the modal title) falls back to its generic form rather than composing a title the caller never typed. - Refreshes on the channel endpoint ignored mention rules.
Message.editforwards the client-levelAllowedMentionsonly whencontentis supplied, which a V2 view never does, so the same view shipped a different mention payload depending on which of the three endpoints the runtime chose, and a bot that configured suppression globally got it on send and lost it on any refresh that took the channel path. All three endpoints now agree, falling back to the client's rules when neither the class attribute nor an explicit argument is set. - Teardown freezes ignored the view's own mention rules.
on_timeout,exit()'s V2 branch, the empty-stack back clear, and the reopen fallback each re-ship the same mention-bearing treerefresh()does, so the last edit a view ever made was the one edit that dropped itsallowed_mentions. validate_placementcould not be validated on five V2 pattern classes. Each pattern mixin extends the class-attribute tables by naming_StatefulMixindirectly, and the mixin precedes the concrete V2 class in the MRO, so the entryStatefulLayoutViewcontributes was dropped, andvalidate_placement = 0silently disabled the pre-flight validator with no definition-time error. The tables are resolved across the whole MRO now.PersistenceManager.flush_all()andclose()were permanent no-ops. The manager's middleware handle was never assigned, so the Inspector's "Flush to Disk" button,/cascadeui flush, and/cascadeui reseteach reported a write that never reached the debounce buffers.InMemoryBackend.row_upsert_manycommitted rows from a failed batch. The SQL backends roll back; the reference implementation did not, and the middleware's retry re-enqueues the whole batch on failure.PersistenceSchemaErrorwas documented but never raised. The schema-ahead-of-library and missing-migrator conditions raisedPersistenceInitError, so theexcept PersistenceSchemaErrorhandler the guide shows could not fire. Both now raise the documented type; it shares thePersistenceErrorbase, so catching the family is unaffected.user_id = 0disabledowner_onlyon a restored persistent view and skipped its session re-derivation, the same falsy-versus-absent confusionscope_keyabove resolves.- A raising
on_instance_limitoverride leaked the rejected view. The rollback ran after the hook rather than in afinally, so an override that propagates (a documented shape, and what the default hook itself does when there is no interaction to answer on) left the view subscribed and never stopped, permanently undertimeout=None. - A raising
on_page_changedoron_toggletook down the render. The V2 composites awaited their post-event hooks bare, so a user override that raised left the cursor advanced and the display stale, with the click reported as failed. All five call sites acrossPaginatedRegionandCollapsibleroute through the same fire-and-forget wrapper the view patterns already used, logging the override's error and continuing. respond(delete_after=...)raised on the followup path. Onlysend_messagetakes the argument natively, so the same call failed whenever the ack backstop had already consumed the response slot. It works on both paths now.respond()andopen_modal()raced the same ack backstop. Both readinteraction.response.is_done()and then send, and the two are not atomic: a backstop armed outside the interaction lock can take the slot in between, so the check passing did not mean the send would.open_modal()then raisedInteractionRespondedout of the callback against a docstring promising a fallback instead. Both now catch it, and Discord's own report of the same race (HTTP 40060), and deliver through the followup path.reload()rebuilt over an armed ephemeral refresh button. Between the arming edit and the token cliff, an out-of-band reload replaced the button, and the armed flag then dropped every notification that could restore it._safe_deferpropagatedInteractionRespondedon Python 3.10 and 3.11. It is a sibling ofHTTPException, not a subclass, so the handler could not see it; on those versionswait_forwidens the window enough for the auto-defer timer to ack inside the call, turning a benign race into a failed navigation. The docstring already promised a failed ack is never propagated.RateLimitedescaped three handlers. Also a sibling rather than a subclass: it could abort the post-send message re-fetch (leaving a successful send reported as a failure with no_message), bypass theon_role_errorhook, and misroute a restore fetch into the never-retriedfailedbucket.- Twenty-two public names were unreachable from their own subpackage.
from cascadeui import setup_loggingworked whilefrom cascadeui.utils import setup_loggingraisedImportError, for a name no less public than the thirteen that package did re-export. The same gap hid the grid, composite, andchoice_rowbuilders incascadeui.components,@computedincascadeui.state, and the roles views and typed schemas incascadeui.views. Each subpackage now re-exports every public name defined under it, in both directions. - Corrected
with_error_boundary,RetryConfig, andsafe_executein the API reference. All three documented signatures that raiseTypeErroras written, andwith_error_boundarywas described as swallowing exceptions when it logs and re-raises. - The lobby example claimed a 10-per-Container cap that does not exist.
The only limit is the 40 components per message the library already enforces
at
add_item. ChannelSelectdocumented its input coercion but not its callback value. WhereRoleSelectandUserSelecthand back fullRoleandMemberobjects,ChannelSelectyields discord.py'sAppCommandChannelpartials, which have nopermissions_for(). Its.permissionsattribute holds the invoking user's permissions rather than the bot's, so the obvious repair answers a different question and passes for the admin it should refuse. The docstring now names the callback type and theresolve()/fetch()idiom.- Ack diagnostics named the clock they measure against.
elapsed_sincesubtracts an interaction's Discord-derived creation time from the local clock, so the printed elapsed carries the host's skew. A host running behind reported under three seconds beside a message about a missed three-second deadline, sending the operator after the wrong cause. Discord enforces the window on its own clock, so only the log line changes. - The missed-ack warning omitted its likeliest cause. It named event-loop
congestion and slow pre-callback work, both of which point at the caller's
own code. discord.py sleeps on an exhausted rate-limit bucket inside
HTTPClient.request, so an earlier HTTP call can hold the interaction with nothing at the call site to show it. The message names that third cause now.
[3.7.0] - 2026-07-21¶
Added¶
ack_firstview flag. Opt-in per-view acknowledgement before the access checks and the callback run, for views whose callbacks do synchronous work that can stall the event loop. Trades the one-request acting-view refresh path for a guaranteed early ack.auto_defer_delayis now a tunable onModalandDynamicPersistentButton. Both carry the ack-backstop delay views already have (default 2.5s), and both validate it at definition time, so a subclass setting it to a non-positive or non-numeric value fails when the class is defined.respond()helpers forDynamicPersistentButtonandModal, plus a publicrespond_safe. These auto-defer-armed surfaces now expose anis_done()-aware responder, so a reply sent from anon_click, aModal.on_submitoverride, or a roles event hook (on_role_assignedand its siblings, viarespond_safe) falls back to a followup instead of raisingInteractionRespondedwhen the ack timer has already fired.respond()warns when it is handed a stateful view. Passing a CascadeUI view as a rawview=kwarg skips that view's ownsend(), leaving it live but unregistered: invisible to the inspector, instance limits, and state cleanup, and its timeout later fires a destroy for a view that was never created. The warning names thesend()call that replaces it.avatar_backfillfor section-mode leaderboards. Opt-in flag that renders Discord default avatars immediately, then resolves the real avatars off the render path and reloads when they arrive, avoiding both a wrong-avatar first render and a per-row fetch storm on large guilds. Pairs with an overridableresolve_avatar_urlshook.LeaderboardLayoutView.botread-only property. Exposes the client passed viabot=(or injected byon_bind) so aresolve_avatar_urls/get_avatar_urloverride resolves avatars throughself.botinstead of reaching into a private attribute.FormViewandFormLayoutViewexposetext_edit_modal_auto_defer_delay. The grouped text-edit modal these patterns build internally now takes its ack backstop from this class attribute (default 2.5s), so a form subclass with a slow async field validator can raise it without reconstructing the modal.- Public error setters on
FormView/FormLayoutView.set_form_error(msg)andset_field_error(field_id, *msgs)write the error state and re-render the form so it shows. They replace the previously documented approach of setting the private_form_error/_field_errorsand callingrefresh(), which set the state but never rendered it. Called from anon_submitoverride, they reject a cross-field rule and keep the form open (a per-field validator sees only its own field, so a constraint spanning fields belongs inon_submit). set_page(n)onPaginatedView/PaginatedLayoutView. Jumps to a zero-based page, clamps to range, fireson_page_changed, and re-renders. Settingcurrent_pagedirectly does not re-render;set_pageis the supported cursor move.refresh_content()on the tab and wizard patterns. A public in-place re-render for a subclass callback that mutated data and needs the active tab or step redrawn without a re-fetch. On V1 it rebuilds the embed; on V2 it recomposes the tree.allow_reselectonchoice_row. Single-select disables the active option by default (re-picking is a no-op); setallow_reselect=Trueto keep it clickable so a re-pick fireson_selectagain, for a control whose callback has a side effect beyond selection (re-opening the active option's editor). Ignored in multi-select, where active options already toggle.- Five public names now import from the package root.
RetryConfig(the config object for thewith_retrydecorator),Transaction(the raw-SQL transaction protocol a backend'stransaction()returns), andColorScheme,FormatTemplate,JSONFormatter(thesetup_loggingcustomization types) were reachable only via deep module paths; each is now exported fromcascadeui.
Changed¶
- A component-less display view tears down without a wasted edit. A static
DisplayLayoutView(a card of text and images, no interactive components) previously shipped one no-op PATCH per teardown:on_timeoutandexit(delete_message=False)froze the tree and re-sent an identical message. The freeze now reports how many components it disabled, and the cosmetic edit is skipped when nothing froze, so a posted-and-forgotten notice self-cleans for free. Views with interactive components are unaffected (the disable edit still ships).exit()is documented as the teardown seam: barestop()cancels the timeout but leaves the view in the active-view registry. - Library logging is now non-blocking.
setup_loggingroutes console and file output through aQueueHandler/QueueListener, so a log call drops the record on an in-memory queue and a background thread performs the file/console I/O -- the event loop no longer blocks on logging, which matters most at DEBUG. For the built-in console and file formatters the output is byte-identical; levels, colours, file rotation, and the action stream are unchanged. A repeatsetup_logging()call now reconfigures cleanly instead of double-logging, andsetup_logging(handler=...)now also installs the action stream (the custom-handler path previously skipped it).
Removed¶
- The unused
AsyncLoggerclass. Its async-queue mechanism now lives insetup_logging(see Changed).AsyncLoggerwas never exported from the package root orcascadeui.utils; code that reached it viacascadeui.utils.logging.AsyncLoggershould callsetup_logging()instead.
Fixed¶
- Component clicks with slow access checks no longer expire under load. When
a view's
interaction_checkoverride does I/O (an uncached member or role lookup on a busy bot), the interaction could cross Discord's 3-second acknowledgement deadline before the click was acked, surfacing as an interaction-failed (10062) storm on later, unrelated buttons. The auto-defer safety net now arms before the access checks run, so a slow check keeps its ack backstop; a rejected check still shows its message via followup. - Modal submissions no longer expire under a slow access check, a slow
validator, or a raising handler. A modal acknowledged only inside
on_submit, so a slowinteraction_checkoverride (which Discord runs beforeon_submit) or a slow validator could cross the 3-second deadline, and a validator or callback that raised left the interaction unacknowledged entirely. The modal now arms its ack backstop across the whole submission dispatch, and a validation-error message routes through the followup when the ack has already landed. - Role panels and other dynamic buttons acknowledge before their handler
runs. A
DynamicPersistentButtonclick (role-reaction panels included) ran its handler, the role add/remove requests and all, with no acknowledgement timer, so a slow mutation on a busy panel dropped the click. Dynamic buttons now arm an ack timer before the handler. - Views sent from a slash command survive a slow preload. A view's
on_loadand setup ran on the interaction clock duringsend(), so a slow preload could expire the interaction before the send acked it. A send-scoped ack timer now covers the pre-send work. - Owner-only DevTools commands defer before bulk work. The
/cascadeuicommands that do bulk or I/O work (exit,exitall,flush,purge,reset) could exceed the acknowledgement deadline on a busy store; they now defer up front. - Missed acknowledgements are diagnosable. When the auto-defer timer's own
ack fails because the interaction already expired, it logs at warning with the
elapsed time since the interaction was created (the sign of a congested event
loop) instead of a silent debug line. A view whose
on_state_changedoverride overruns the ack budget while an interaction is in flight now warns once per class, matching the existingon_loadwarning, and the persistent-view restart repaint logs its duration. auto_refresh_ephemeralhandoff survives push/pop navigation. A long-lived ephemeral view lost its refresh handoff at the firstpush()orpop(), so a multi-step flow crossed the 900s webhook-token cliff with no "Continue Session" button and errored on a later, unrelated click. The arming deadline now rides the navigation chain and re-arms on the destination once the edit confirms.- Reopening an ephemeral view keeps its navigation identity and session. A
reopened view rebuilt from constructor kwargs alone, so it lost its
post-construction selection, navigation stack, reopen factory, and undo/redo
timeline, and its
Backbutton degenerated. It now carries all of these, rejoins its original session soshared_datasurvives the swap, and no longer deletes its own attached child views while reopening. - A non-ephemeral
send()clears a stale ephemeral flag. A view instance reused for a public send after an ephemeral one kept its ephemeral marker, which routed its refreshes through a slower edit path and misread real permission errors as token expiry. - Attached child views survive navigation. A parent view orphaned its
attached children the moment it navigated, and a child that navigated escaped
its parent's cleanup. Children now re-parent onto the destination across
push()andpop(). - Pushing a pre-constructed view instance binds the acting interaction. A
later navigation from a
push(instance)destination that fell back to the stored interaction took a no-edit path; the instance now binds the acting interaction the same way the class path does. - Late-imported
DynamicPersistentButtonsubclasses recover viareattach(). A dynamic button defined in a cog loaded aftersetup_middlewarewas never wired into dispatch, so its clicks silently never routed.reattach()now re-drives dynamic-item registration, matching the recovery already available to late-imported persistent views. - Reattached persistent views restore their original session. Restart
re-derived a suffix-free session key, so two panels of the same class opened by
the same user collided on one session. The
session_idcaptured at registration is now restored, keeping each view's original session identity. reload()re-renders on the V1 tab, wizard, form, and paginated patterns. It shipped an edit with noembed, so a V1reload()re-fetched viaon_loadbut never updated the visible embed. Each V1 pattern now routesreload()'s render step through its embed-carrying rebuild.- Form controls route through the stateful callback wrapper. Every select,
boolean button, text-edit button, and submit button on
FormViewandFormLayoutViewhad its callback replaced after construction, which dropped the component-interaction dispatch (form clicks never reached the action history or the inspector) and left the acting interaction unbound, so each field change paid two Discord round-trips instead of one. choice_rowin dropdown form honors its no-op re-pick contract. Its docstring states that re-picking the active option is a no-op, and the button form disables the active option to enforce that; the dropdown form (6 or more options) firedon_selecton a re-pick anyway, so the control's behavior flipped atbutton_threshold. The dropdown now swallows a single-select re-pick of the active value unlessallow_reselect=True(see Added).
[3.6.0] - 2026-07-17¶
Breaking¶
refresh_cooldown_msno longer throttles interaction-driven edits. It paces the re-renders the library starts (a panel reloading on its own) and exempts edits made in direct answer to a click on the view's own message. It was never a spam guard: it is view-wide, so it slowed every viewer of a shared panel for one person's clicking, and on a panel that also reloads out of band the window stayed armed, taxing page turns by up to its full length. Migration: to throttle one control per clicker, wrap it withwith_cooldown, which now survives the component being rebuilt.reload()is unchanged and still defers itson_load()fetch inside the window: that gate protects your data source, not Discord. The two throttles are now documented together, keyed on the question being asked, andv2_battleshipdemonstrates the button-level guard.TabLayoutView,WizardLayoutView, andPaginatedLayoutViewbuild their content inon_load(). Theirsend()overrides are gone. A subclass that overrideson_load()must now callsuper().on_load(), or a tab or wizard renders its nav row above nothing and a cursor-mode paginator never leaves "Loading...". Subclasses that override neither are unaffected.
Added¶
get_nav_state()/restore_nav_state(). A view can name the state that should survive apop(). Reconstruction replays constructor kwargs and re-runson_load(), so data returns fresh, but anything selected since construction was never a kwarg and reverted to its default, silently, with the next write landing on a row the user never opened.restore_nav_state()runs beforeon_load(), so a preload reads the restored selection rather than fetching twice to correct it. The mapping rides the navigation stack and is never serialized, so it may hold live objects. Defaults to{}. The built-in patterns name their own cursors, so their fix below is automatic; the V2 composites do not, by design: aPaginatedRegion's page and aCollapsible's expanded state are the host's to name. The guide now states the reconstruction boundary: what returns fresh, what reverts, and which ofget_nav_state(),shared_data, orrebuild=carries which.nav_rebuild. The rebuild a view supplies for its own navigation edits, used whenever the caller passes none. A V2 view is its component tree and needs nothing here. A V1 view's content is its embed, andpop()has norebuild=to pass, so a V1 view names its own withnav_rebuild = staticmethod(lambda v: {"embed": v.build_embed()}). An explicitrebuild=still wins.with_cooldown(key=...). Names the deadline a component reads, for controls a name cannot tell apart. The default reads thecustom_idwhen you set one and the wrapped callback's qualified name otherwise; buttons built in a loop share their factory's name, so those take acustom_id=or akey=. A rejected click checks whether the controls sharing that name call different callbacks, and logs one warning per view class when they do, so a loop that needed a name says so instead of throttling silently.secondsis typedfloat: sub-second guards always worked, and the rejection notice already reported the remainder to one decimal, but the annotation said otherwise.is_snowflake(value). Reports whether an integer is shaped like a real Discord ID, by decoding the creation time Discord packs into it. A database row ID or a match number leaves those bits near zero and decodes to Discord's epoch day, so it fails. Sits besidecoerce_snowflake_id, which accepts any integer by design.- Six names that were public but unreachable now import from the package
root.
is_snowflake,coerce_snowflake_id,coerce_snowflake_id_set, andcoerce_snowflake_match(coercion was the one utility module the root never re-exported), plusAction, which pairs with the already-exportedStateDatain every reducer signature, andStatefulComponent. Each was already public in its own subpackage, so the subpackage paths keep working. secretform field option. A field markedsecret=Truemasks its value in the form display as fixed dots, for a password or token. Discord modals cannot mask the input itself, so this covers the form's own display; the entered value still reacheson_submitand validators normally.
Changed¶
- A rate-limited edit is retried instead of dropped. Every 429 seam stamped the backoff window and returned, leaving nothing to ship the edit; views recovered only on their next state change, and an armed ephemeral view (which drops notifications by design) never recovered at all. The backoff now queues the edit to ship at the window boundary, through the same single task the cooldown uses, and a retry that is rate-limited again schedules its own successor.
Fixed¶
- A throttled refresh was dropped, not delayed, on views without
build_ui. The deferred render delegated toon_state_changed, whose default did nothing when there was nobuild_uito run, so tab switches and wizard steps onTabView/TabLayoutView/WizardView/WizardLayoutViewwere swallowed outright. Not opt-in: the 429 backoff engages this path on any view. - The 429 backoff always waited exactly one second. It read a
retry_afterattribute thatdiscord.HTTPExceptiondoes not carry, so every rate-limit fell through to the fallback. The delay now comes from theRetry-Afterheader, and a header-less 429 (which discord.py raises only for a Cloudflare ban) backs off minutes rather than knocking once a second on an IP block. discord.RateLimitedescaped every edit seam. It subclassesDiscordException, notHTTPException, soexcept discord.HTTPExceptionnever caught it, and it is the only rate-limit type that carries a realretry_after. Now handled wherever a 429 is.refresh_cooldown_mscould defeat the ephemeral refresh handoff. The arming edit queued behind the cooldown window and the deferred render then rebuilt over the refresh button, leaving a frozen panel with no way back and no notification able to repair it.- A refresh was lost when its backoff window grew mid-flight. The waiting task woke, found the window still active, saw itself registered as the pending retry, declined to schedule a replacement, and cleared the last reference to itself on the way out.
- A deferred render answered to the click that spawned it. Task creation copies the caller's context, so a background render read a spent interaction and edited through a response slot whose window had closed.
- A theme change did not reach views whose selector tracks their own
content.
state_selectordecides whether a view re-renders, and a theme is a render input that appears in no view's data, so a panel watching its own toggles went deaf to a theme switch and kept painting the old accent, while the panel that made the switch repainted. A theme resolved throughget_theme()now rides the selector. A fixed theme yields a constant and notifies no more often than before; a view that sets its own colors rebuilds once and stops at the render hash, shipping no edit.settings_menulooked its theme up privately rather than returning it fromget_theme(), so it now uses the override the theming guide teaches andv2_settingsalready used. - A V1 pattern's first message shipped no content.
TabView,WizardView, andFormViewsent their controls over an empty body: V1 content is an embed, and onlyPaginatedViewcomputed one insend(). The embed each pattern already builds for apop()now renders the first message too, andMenuViewsupplies itsbuild_embed()without the caller passing it. An explicitembed=orcontent=still wins. - A V1 wizard step with no builder froze the display. The step advanced and the nav row relabelled, but the edit was skipped whenever the step contributed no embed, leaving the previous step on the message. The edit now ships either way, as it already did on V2.
- A popped view lost its place.
PaginatedView/PaginatedLayoutViewcame back on page one,TabView/TabLayoutViewon the first tab,WizardView/WizardLayoutViewon step one (now snapped to a visible step), andFormView/FormLayoutViewwith the typed values gone. - A popped form came back with no fields at all.
FormViewandFormLayoutViewtake their__init__from a plain mixin, and the kwargs capture only installed on classes declaring their own, so a form reconstructed bypop()had no fields, no title, and no schema. - A popped V1 view kept the child's embed. The navigation edit shipped
components alone unless the caller passed
rebuild=, andpop()has nothing to pass: the back button is library code. V1 content lives in the embed, so the parent's buttons rendered over the child's content. Every V1 pattern (PaginatedView,TabView,WizardView,FormView,MenuView) now names its own edit through the newnav_rebuildclass attribute, and any V1 view can do the same. - A popped V1 tab or wizard kept the first tab's buttons. The tab row and
the wizard's Back button are built during
__init__against the first tab/step, so restoring the cursor left the third tab's content under a row still highlighting the first, and step three's under a Back button disabled as though the user had never left step one. - Clearing an optional form select crashed the interaction. An optional
select lets Discord deliver an empty selection, and the callback read the
first element without checking, so clearing a choice raised
IndexErrorand the user saw "This interaction failed". An empty selection now clears the field to "not set". - A form revealed its errors one submit at a time. A single field that failed to parse (an age outside its range, a malformed date), or a blank required field, short-circuited the submit, so validator errors on other fields (a bad email, a short password) stayed hidden until the first was fixed and the form resubmitted. Parse errors, blank-required errors, and validator errors now all surface together, with validators still skipping any field whose raw value never parsed and any field already flagged as required.
- Changing one form field cleared every field's validation message. A form showing errors wiped all of them the moment the user touched any other field, so picking a select or toggling a boolean erased still-accurate messages on unrelated fields. A field change now clears only that field's own error; the rest stay until they change or the next submit re-checks them.
- A V1 form silently dropped fields past its row budget. A form with more
select and boolean fields than Discord's five action rows hold discarded the
overflow with no error, leaving a required field unfillable. Construction now
raises, naming the field that does not fit and pointing at
FormLayoutView. - Two form fields with the same label crashed on the Edit click. Modal input ids derive from the label, so two fields labelled alike collided when the modal opened. The clash is now rejected at construction, naming both fields.
- A form field's
defaultwas ignored outside the modal. A declareddefaultreached only the modal prefill, so a required field with a default still displayed "not set" and blocked submission, and select defaults never rendered. Defaults now seed the form's values at construction. - A form's integer field could submit the raw text you typed. When a typed
field failed to parse, the raw string was written into the form's values, and
any later field change cleared the error that blocked submission, so an
integer field could submit
"twenty". Unparsed input is now held apart from the values; the modal still prefills what you typed, and the values carry only parsed results. - A rejected modal value was written back before validation.
Modalpopulated each input wrapper's.valuebefore running validators, so a caller reading it after a failed submit saw the rejected input, contradicting the documented "populated after validation passes" contract. The write-back now follows validation. - A validator on an optional form field made it secretly required. Most
validators reject a blank value, and the runner ran them over every field, so
an optional field left empty failed its own validator. Blank optional fields
now skip validation; the required-check still owns the blank-required case,
and
0andFalsecount as values, not blanks. - A validator that returned the wrong shape crashed far from the mistake. A
validator that forgot to return a
ValidationResultraised a bareAttributeError, and an object with an async__call__(a database-backed uniqueness check, the documented awaitable shape) was called but never awaited. The runner now awaits any awaitable result and raises a directedTypeErrornaming the validator and field on a wrong return. - A form field written as a dict with no
typerendered no control. TypedFormFieldentries default totext, but a hand-written dict passed through untouched, so a field with notypehad no input and, if required, left the form unsubmittable. A missingtypenow fills totextto match. - A numeric form field accepted
nanandinf.float()parses both, and a NaN compares False to every bound, so a field limited to 0-100 accepted a value that was neither, displayed "nan", and would have written invalid JSON on persistence. Float parsing and themin_value/max_valuevalidators now reject non-finite numbers. - A menu category pointing at a pattern view crashed on click. Both menus
forced their own render shape onto every push:
MenuViewcalledbuild_embed()andMenuLayoutViewcalledbuild_ui()on destinations that define neither, raisingAttributeError. Every pattern was affected in both versions, so eight of the ten menu-to-pattern paths were dead. A destination that names its ownnav_rebuildnow keeps it, one that renders through another seam is left alone, and a plain view still takes the menu's. - A menu category naming a cross-version view failed on click. A message carries its component version one way, so a V1 menu can never reach a V2 destination. The category list names every destination at construction, but the mismatch waited for the push and reached the user as a dead button. Both menus now reject it where the category is declared.
- Wrapping a component twice stacked the wrapper.
with_loading_state,with_confirmation, andwith_cooldowneach wrapped the previous callback, so a build method that wraps on every render nested without bound: three renders meant three confirmations for one click. - A
functools.partialcallback crashed every V2 render. Stabilizing a component'scustom_idreads the callback's qualified name, which a partial does not carry, so a button wired to one raisedAttributeErrorinsidebuild_uiunless it also passed an explicitcustom_id. with_cooldowndid nothing on a rebuilt component. Deadlines lived in the wrap call, and an accepted click triggers the rebuild that discards them, so the cooldown never fired. They now live on the owning view, named after the callback you wrote: each wrapper records that callback before burying it, so stackingwith_confirmationorwith_loading_stateunderneath does not collapse a view's controls onto one deadline.- A view that names an owner other than the clicker warned on every run. The
notice claimed an explicit
user_idis re-derived from the interaction on push/pop and diverges after navigation; navigation carries the value forward unchanged, and naming an owner who is not the clicker is a supported shape the game examples are built on. The check ran before the subclass assignedallowed_users, so it could not tell that shape from an application id passed under a reserved name. It now runs at send and fires only when the id is not a Discord ID and the author it locks out is the one who built the view, so handing ownership to a real user (a game the challenger owns, an admin posting a panel for someone else) is silent. - The Inspector showed two clocks. Actions stamped their time from the host's local zone while the Inspector's own stamps read UTC, so the History tab mixed both and a daylight-saving change rewound the action log for an hour. Every action now stamps UTC.
- The 40-component error contradicted itself. An oversized card added to an empty view reported that the limit was exceeded "already at 0 components". It now reports what the view holds, what the item adds, and the sum.
- An oversized
TextDisplayfailed at Discord instead of pre-flight. The V2 placement validator enforced the MediaGallery item cap but skipped theTextDisplay4000-character limit, so a body over that length passed validation and returned an opaque HTTP 400 at send, far from where it was built. The validator now rejects it at send, refresh, and navigation with a directed error naming the component. - Oversized Button labels, Select placeholders, and SelectOption text failed
at Discord instead of pre-flight. The same validator gap that skipped the
TextDisplaycap also skipped these string limits: a Buttonlabelover 80 characters, a Selectplaceholderover 150, or a SelectOptionlabel,value, ordescriptionover 100 passed validation and returned an opaque HTTP 400 at send. The validator now rejects each at send, refresh, and navigation with a directed error naming the component. - The component wrapper reference had wrong signatures. No wrapper has
keyword-only parameters, all three accept any component (not just buttons),
and
with_cooldown's"user_guild"scope was missing. - The
migrators=bulk-registration form was missing from the persistence guide, which documented only the decorator path. - The
@cascade_componentreference documented a registry that does not exist. The decorator dispatchesCOMPONENT_INTERACTIONfrom a view method rather than storing callbacks, so theget_component()pairing it showed returnedNoneand its module-level snippet could not run.register_component()/get_component()now have their own entry as the V1 composition registry. - Reference gaps. The landing page omitted the PostgreSQL backend, the
examples index omitted
v2_attachments.py, and the built-in theme objects had no entry naming them apart from the theme names they register under.
[3.5.0] - 2026-07-11¶
Breaking¶
PersistenceManager.install_middleware()removed. The legacy manager-driven middleware install path is gone. Wire persistence throughsetup_middleware(PersistenceMiddleware(...))(the canonical path since v3.3.0). No consumer used the manager-driven topology in practice, but it was public API, so its removal is a breaking change.LeaderboardLayoutView.build_summaryremoved. Aggregate stats are now composed content rather than a dedicated hook: read the newranked_entriesproperty insidebuild_headerand return astats_card(...)(or anycard). This collapses the overlapping "content above the rankings" hooks into one and drops thedict-vs-Containerreturn-type ambiguity. Migration: abuild_summary(entries)returning a stats dict or card becomesbuild_header(page)readingself.ranked_entriesand returning astats_card, gated onpage == 0for a page-1-only Overview.
Added¶
PersistenceManager.reattach(). Re-drive persistent-view reattach after the initial pass, so a view class imported aftersetup_middleware(a cog loaded later) attaches without a restart: import order stops mattering. Idempotent: already-restored panels are skipped (no re-fetch, no double registration); transiently unreachable rows are retried. Call it once every cog has loaded.- Construction-time bound validation for selects and modal inputs.
StatefulSelect/Dropdownreject more than 25 options, andCheckboxGroup/FileUpload/TextInputreject out-of-rangemin/maxbounds, with a directedValueErrorat construction instead of a Discord HTTP 400 when the component ships or the modal opens. nav_dividerfor in-card paginators. Withnav_inside_containeron,nav_divider = Truerenders a divider between the page content and the in-card navigation row. Defaults toFalse(the flush look).- Built-in avatar resolution for Section-mode leaderboards.
LeaderboardLayoutViewaccepts abot=kwarg and ships a defaultget_avatar_urlthat resolves each entry's avatar from the bot's user cache (a Discord default avatar on a cache miss), so section-mode boards no longer need a hand-rolled avatar hook. Without abot, the default returnsNoneand the two-lineTextDisplayfallback is unchanged. The persistent variant receives the bot throughon_bind.
Changed¶
reload()respects the refresh throttle. Areload()inside an activerefresh_cooldown_mswindow (or a 429 backoff) now defers the whole reload,on_load's fetch included, and a burst collapses to one fetch + edit at the window boundary with fresh data. Previously only the edit was throttled, so an out-of-band-driven panel ran a fullon_loadfetch per trigger. A coalesced reload replays its keyword arguments at the boundary, so a subclass reload keyword (e.g.force) survives the defer when forwarded tosuper().reload(**kwargs).LeaderboardLayoutView.build_footerplacement is now return-type-driven. A raw component (a caption, link row, or image) folds inside the rankings card below the entries and stays attached to them, while aContainer(card(...)) renders as its own standalone card below the rankings. Previously the default sibling layout floated a raw footer as an orphaned line between the card and the nav row.
Removed¶
- Dead internals: the unused
_add_page_contentshim onPaginatedLayoutViewand the unusedErrorBoundaryutility class. Internal-only, no public surface.
Fixed¶
- Persistence flush no longer drops a re-registered view on a retry. A re-register racing a failed unregister flush could leave the key queued for both write and delete. The next flush then deleted it, so a re-registered persistent view failed to reattach after restart. The retry re-enqueue now preserves the single-buffer-per-key routing invariant.
APPLICATION_SLOTS_PRUNEDpayload is consistent. The TTL sweep and manual prune dispatched disagreeing keys (reasonvscutoff); both now emit a consistent{deleted, cutoff}shape viaActionCreators.- Paginated nav buttons no longer go stale on an out-of-band reload. A view reloaded while parked past the first page redrew its Prev/Next/First/Last buttons in page-one states over later-page content; button state now derives from the current page in every render path.
- Paginated jump buttons rebuild on a data refresh that crosses
jump_threshold.refresh_data/refresh_pageschanging the page count across the threshold now add or remove the first/last/go-to buttons, not just re-sync their disabled state (V1 and V2). - In-card paginators and leaderboard footers coexist. With
nav_inside_containeron, abuild_footerframe renders inside the card above the pager instead of forcing the nav row out. - A raising
on_page_changed/on_tab_switchedoverride no longer desyncs the view. These post-navigation hooks are now fire-and-forget (logged, swallowed) like their wizard/form siblings, so the page turn / tab switch and its refresh always complete. - Placement validation runs after
seed_initial_state. A view that builds its component tree insideseed_initial_state(rather than__init__/build_ui) no longer fails to send with a "no top-level components" error: the pre-flight placement check now validates the tree the hook produced, not the empty pre-seed tree. on_timeoutfrees the instance-limit slot before its cosmetic edit, mirroringexit(): a stalled timeout edit no longer holds the slot for up toedit_timeout.on_unauthorizedroutes throughrespond(), covering the already-acknowledged interaction case its sibling response hooks already handled.with_confirmation's prompt disables its buttons on timeout instead of leaving live-looking buttons that error on a late click;with_loading_statelogs its swallowed edit failures at debug.
[3.4.1] - 2026-07-08¶
Added¶
- Leaderboard page-frame hooks.
build_header(page)andbuild_footer(page)on the leaderboard pattern place optional components above the summary card and below the rankings card (above the navigation row): the seam for a banner image or an attribution footer. Both default toNone, accept a single component or a list, and receive the zero-based page index so a frame can target only the first page.v2_leaderboarddemonstrates both. - Menu header/footer hooks are now public.
MenuLayoutView.build_header()andbuild_footer()replace the underscore-prefixed pair, matching the leaderboard's page-frame hook naming. - Structured modal forms guide. The components guide teaches the modal
input types and the edit-in-place defaults pattern, with
v2_wizardas the live reference. - Option-count validation on modal groups.
CheckboxGroupenforces Discord's 1-10 option bound andRadioGroupits 2-10 bound with a directedValueErrorat construction, replacing a silent acceptance that failed as an HTTP 400 when the modal opened. - Leaderboard card masthead. A
bannerattribute (class attribute orbanner=kwarg; URL string,discord.File, or anything with a string.urlsuch asguild.icon) renders a full-width image at the top of the rankings card, above the title heading when both are set.title=None(or an empty string) now renders no text heading instead of a stray##, so banner-only and heading-free cards are declarative -- with an empty masthead the title divider is skipped. Abuild_title(page)hook replaces the whole masthead for dynamic composition, same shape asbuild_header/build_footer.
Changed¶
v2_wizardexample redesigned. Every step now renders a live character-sheet preview (with a name-seeded portrait) and folds its controls into cards viachoice_rowandaction_sectioninstead of stacked bare selects. Also resolves a bug in the prior version where the Background step could not be advanced. The name and background modals now demonstrate the structured modal inputs: aFileUploadportrait that replaces the preview image, plusRadioGroup,CheckboxGroup, andCheckboxin one form.v2_lobbyexample redesigned. The lobby renders as one status-colored card: a host-avatar header, slot-fill progress bar, a roster that shows its open slots, and the control row inside the card.- Game-example challenge prompts enriched. The
v2_tictactoeandv2_battleshipchallenge cards gain an opponent-avatar header, the game config as akey_valueblock, and a caption naming who can respond and when the prompt expires. The tictactoe board legend now also shows the win condition, which was invisible during play on custom-size boards. - The 40-component-limit error now also suggests trimming content nodes, not only compacting the pager row, since page content is the more common cause.
v2_settingsexample teaches the dynamic-theme idiom. The hub and appearance page overrideget_theme()to read the user's selected theme from scoped state, replacing per-card color plumbing -- every card follows a theme switch automatically.
Deprecated¶
MenuLayoutView._build_header()/_build_footer(). Superseded by the publicbuild_header()/build_footer(). Existing overrides keep rendering (the public hooks delegate to them) and aDeprecationWarningfires at class definition; migrate by dropping the underscore.
Fixed¶
- Empty V2 views now fail with a directed error.
validate_placementrejects aLayoutViewwith no top-level components at send, refresh, and navigation, replacing Discord's terse HTTP 400 for an empty components-v2 message with a build-timeValueErrorthat names the fix. - Empty modals now fail with a directed error.
open_modalrejects a modal with no components before it is sent, replacing a Discord HTTP 400. - Media-only rebuilds now re-render. The render digest hashes media URLs
(
MediaGalleryitems,Thumbnail,File), so a rebuild that changes only an image (a regenerated banner, a new avatar) ships the edit instead of being skipped as an unchanged tree. nav_inside_containerno longer rejects mixed pages. A page combining aContainerwith other top-level items (a rankings card plus a standalone summary card or frame components) previously raised a nested-Container placement error. Such pages now fall back to the sibling layout with the navigation row as a separate row; pages that can wrap still do.- README Hello World example runs as copied. It was missing the initial
build_ui()call in__init__, so a verbatim copy failed on first send. The quickstart now also states the first-render rule explicitly. - Stale modal-input limitation removed. The known-limitations page claimed
structured modal inputs (
Checkbox,CheckboxGroup,RadioGroup) fail with a Discord 400, contradicting the component docs that teach them. The full serialize-and-submit loop verifies against discord.py 2.7.0 and 2.7.1, so the section is gone. - Theme accents apply everywhere, not only inside
build_ui(). Pattern render paths (leaderboard page builds, wizard steps, tab builders, paginated formatters,on_load) now run inside the view's theme context, and cards built without an explicit color re-resolve against the view's live theme at every render seam -- a card renders themed no matter where it was built, and a runtime theme switch restyles managed cards on the next refresh. The theme'sseparator_spacingstyle, documented but previously unread, now drivesdivider()/gap()spacing the same way. Explicit colors and spacing always win.
[3.4.0] - 2026-07-01¶
Added¶
PaginatedRegioncomposable pager. A stateful composite component that pages one slice of aStatefulLayoutView's tree while the host renders the rest -- the V2 sibling of the V1PaginationControls. Setitems, renderpage_items, and addcontrols(self)for the nav row inside the host'sbuild_ui()oron_load(). Each instance holds its own page index, so two regions can share one view (give them distinctkeyvalues). Carries thePaginatedLayoutViewnavigation surface -- first/last jump buttons and a go-to-page modal pastjump_threshold-- with the same class-attribute customization andon_page_changedhook. Fills the gap between a one-shot builder and a full paginated view.control_buttons(self, compact=...)returns the nav buttons unwrapped so a node-tight host fuses them into a row it owns alongside its own Back/Exit buttons;compact=True(also oncontrols) yields a three-button prev/go-to/next set that packs with Back + Exit inside one five-button row -- the shape aper_page=1carousel near the 40-component cap needs.Collapsibleinline disclosure/expander. A stateful composite where a trigger button toggles an inline region of revealed content -- achoice_row, a select, more buttons. The trigger relabels/restyles between collapsed and expanded states;render(view)returns the trigger collapsed or the trigger plus the revealed content expanded. Each instance holds its own state, so two collapsibles in one view stay independent. The host supplies arevealcallable and owns the collapse policy (collapse()after an action, or leave it open); anon_togglehook fires on every open/close. Absorbs the hand-rolled "boolean flag + toggle callback + conditional render" disclosure idiom. An optionalsummarycallable fuses the trigger into a Section beside a line of summary text (anaction_section) instead of a bare button row -- the shape a card-based disclosure wants; it falls back to the bare button when the callable yields nothing.choice_row"pick one/any" control +Choicetype. A builder for a segmented choose-one control -- a row of buttons where the active option is highlighted and (single-select) disabled, all sharing oneon_select-- that switches to a dropdown automatically when the option count outgrows a button row (6-25 options) and raises past 25.multi=Truemakes it a multi-select (toggle buttons, or amax_valuesdropdown). Accepts a{label: value}dict or a sequence ofChoice(which adds per-option emoji and dropdown descriptions). The builder handles the string round-trip Discord forces on select option values, soon_selectalways receives the real Python value.disabled=Truegreys out the whole control (every button, or the dropdown) for a read-only state such as a locked or closed choice. Replaces the hand-rolled "style-if-active + disabled-if-current + per-option callback factory" idiom.action_section/toggle_sectionacceptdisabled=. Render a card-embedded action button greyed out and non-interactive instead of accepting the click and rejecting it inside the callback. Mirrors the rawStatefulButtonAPI; defaultFalsekeeps existing callers unchanged.MAX_SELECT_OPTIONSconstant exported from the package root (Discord's 25-option select cap).choice_rowreferences it instead of the bare integer.on_load()async preload hook +reload(). Overrideasync def on_load(self)to fetch from a database or other async source and build the view's tree against the result. The library calls it automatically before the initial send and before every push/pop edit, so navigating to a child or back to a parent re-reads its source (reload-on-render).reload()is the out-of-band convenience (on_loadthenrefresh) for re-fetching inside a callback. Replaces the hand-rolled "sync__init__+ asyncload_and_build+rebuild=lambda v: v.load_and_build()" idiom with one hook.on_pre_send(interaction)hook -- a pre-send veto gate on every view. Override it to run a permission or data check before the send; returningFalseaborts cleanly (no message, no state registered). It runs with the interaction response slot still open, so an override can respond to the user before the send without a forceddefer. Demonstrated in thev2_lobbyexample.on_bind(bot)hook on persistent views. Inject non-serializable runtime dependencies -- a database pool, the bot, a service client -- that cannot ride the constructor through the persistence round-trip. The library calls it automatically duringsend()(when the bot is derivable from the context) and during restore, beforeon_restore. A non-serializable constructor kwarg now declines the registry write with a directed error naming the offending kwarg and pointing toon_bind, instead of a near-silent failure that dropped the view on the next restart. Demonstrated in thev2_persistenceexample.on_message_gone()view hook. Fires when an edit observes the message was deleted (a 404 fromrefresh()), so a consumer tracking the message in its own store can reconcile that reference. The edit-path counterpart to the gateway-drivenon_message_delete.make_back_button()andmake_nav_row()navigation helpers.make_back_button()returns an unattached Back button that pops the navigation stack (mirrorsmake_exit_button()).make_nav_row()(V2) returns oneActionRowcombining Back and/or Exit, collapsing the common pushed-sub-view footer into a single call. Withon_load()defined, Back reloads the restored parent automatically, so no rebuild callback is needed.back_label/back_style/back_emoji(and theexit_equivalents) customize each button, so a relabeled Back needs no manual composition.- Leaderboard out-of-band refresh is now a public call.
LeaderboardLayoutViewbuilds its pages throughon_load(), so the inheritedreload()re-fetches entries and re-renders the message in one public call -- previously an out-of-band refresh neededrebuild_pages()plus reaching into the render internals. A pushed leaderboard also reloads its data automatically on navigation. Both short-circuits stay intact: an unchanged entry set skips the avatar re-fetch, and an unchanged tree skips the message edit. reload(force=True)andrebuild_pages(force=True)on leaderboard views. Force a page rebuild even when the entry signature is unchanged: for a filter or a select's highlighted option that changed without touching the row data.reload(force=True)is the out-of-band path (re-fetch, re-render, re-store);rebuild_pages(force=True)is the lower-level rebuild.emoji()validator +is_emoji()utility. Discord has no native emoji input, soemoji()(a sibling ofregex()/choices()) gates aModalTextInputon whether the value is a unicode emoji or a custom<:name:id>token;is_emoji(text)is the bare predicate, exported fromcascadeui.utils. An emoji "picker" is then composition -- achoice_rowof your emoji options plus a Custom option that opens a modal with the validator (recipe in the validation guide) -- not a dedicated widget.- Slow-
on_loaddiagnostic. When a view'son_load()preload overrunsauto_defer_delay(default 2.5s), the library logs a one-per-class warning naming the view and the elapsed time. Exposes a render-path HTTP footgun (serial fetches competing with the interaction ack) that otherwise only shows up as a sluggish panel. - Construction warns when an explicit
user_iddiverges from the interaction user.user_idis a framework-managed identity kwarg (re-derived from the interaction on push/pop), so passing a custom value silently diverges after navigation. Construction now logs a warning, once per view class, naming the fix: use a non-reserved kwarg name for application ids. DevToolsCog.is_owner_toolmarker. The dev-tools cog now carries a readableis_owner_tool = Trueclass attribute so a bot that routes owner-only cogs differently (for example, to a control guild) can detect it viagetattr(cog, "is_owner_tool", False)instead of matching the class name. Any owner-gated cog can carry the same marker.- New example
v2_db_navigation.py. A repo-backed task list demonstrating the database-navigation pattern: a stable repo handle passed as a kwarg, rows loaded inon_load(), and reload-on-render through push/pop withmake_nav_row()and norebuild=callbacks. The row list is paged with aPaginatedRegionfed fromon_load(). - Composition cookbook in the components guide. A positive "what nests in what" reference for V2 layouts -- the nesting tree, what goes where, and worked examples for placing selects and collapsible regions inside cards.
Changed¶
- Persistence flush batches all dirty rows into one backend round-trip. The
middleware previously called
row_upsertonce per dirty row; it now calls the newPersistenceBackend.row_upsert_many, so the SQL backends collapse a flush into a single transaction (executemany+ one commit) instead of N connection acquires and N commits. A custom backend that does not implementrow_upsert_manykeeps working -- the flush falls back to per-rowrow_upsert. - Persistent-view restore fetches concurrently at startup. Reattaching
persistent views on
setup_hookpreviously fetched each view's channel and message one at a time, so a deployment with many panels paid an O(N) serial Discord round-trip cost before the bot reached READY. The fetch phase now runs concurrently under a bounded semaphore (restore_concurrencyonPersistenceMiddleware(...), default 8); view registration stays serial and in order. Many-panel bots reach READY substantially faster. REGISTRY_PRUNEDcarries the prunedpersistence_keys, andlast_reattach_summaryexposes them after startup. The action payload gains akeyslist alongside itsdeletedcount. Because the action dispatches only once and code running aftersetup_hookcompletes (such ason_readyhandlers) cannot subscribe in time to observe it, the manager also stashes the reattach result onstore.persistence_manager.last_reattach_summary(restored/skipped/failed/removed/unreachablekey lists), so a consumer can reconcile its own records after startup regardless of subscription timing.- The V2 40-component message cap raises a directed error. When a
StatefulLayoutViewtree would exceed Discord's 40-component limit,add_itemre-raises discord.py's terse "maximum number of children exceeded" with the running component count and a fix pointing atPaginatedRegion.control_buttons(view, compact=True). discord.py still owns the enforcement; the library owns the message. - Expected ephemeral-lifecycle conditions no longer log at WARNING. An ephemeral view that outlives its 15-minute interaction token logs its unavoidable edit-on-timeout failure (and the T+810s refresh-button arming failure) at DEBUG instead of WARNING -- the condition is expected and not operator-actionable. Non-ephemeral edit failures still warn. A persistent-view registry write that races the view's own exit also drops to DEBUG.
DevToolsCogslash commands are hidden from non-admins. The/cascadeuigroup now setsdefault_member_permissionsto none, so Discord no longer shows it in a regular member's command picker -- theis_owner()check already blocked execution; this removes the clutter for bots that sync the cog globally. The prefix form (!cascadeui ...) is unaffected.- DevTools inspector buttons are more responsive. The Refresh, Clear History,
and performance-tab buttons in
/cascadeui inspectnow edit and acknowledge in one round-trip instead of deferring first, removing a per-click pause. The genuinely-slow buttons (Flush, Exit All, Clear Session) still acknowledge first. v2_dashboard.pyenriched into a full V2 builder showcase coveringchoice_row,Collapsible,tab_nav,cycle_button, andlink_sectionacross three tabs, plus a "tabs vs navigation vstab_nav" decision note in the patterns guide.- Modal input
custom_ids now derive through the sharedslugifyrule, so a punctuated field label ("A/B Test") yields a cleaninput_a_b_testid; letter-and-space labels are unchanged.
Fixed¶
- A failed interaction edit during navigation no longer bricks the view. When a
Discord edit failed mid-
push()/pop()(a missed ack, an expired token, a transient 5xx), the message kept showing the previous view while that view was already torn down, so every later click was silently dropped. Navigation is now atomic: the source view's teardown is deferred until the destination edit confirms, so a failed edit rolls back to a live, re-clickable source instead of a dead message. The edit is attempted across the interaction fast path, the deferred response, and the channel endpoint before any rollback. - Fast navigation no longer surfaces an occasional "This interaction failed". When a
view's first render took roughly
auto_defer_delayseconds, the auto-defer timer could acknowledge the interaction in the same instant the fast-path edit ran, andedit_messageraisedInteractionResponded-- a sibling ofHTTPExceptionthe fast path did not catch. Both the navigation and in-place-refresh fast paths now recognize the race and fall through to the deferred edit. - Tab views keep their Back button when used as a navigation rebuild target.
A
TabLayoutViewthat is pushed and rebuilt throughsend()could lose the auto Back button on the rebuild; it is now restored afterward like the other navigation patterns. with_confirmationno longer drops the confirmed action when the prompt edit fails. If editing the confirm/cancel prompt failed (a deleted message, a transient error), the wrapped callback was skipped and the error propagated. The prompt edit is now contained so the confirmed action (oron_cancel) still runs.- Modal submissions no longer error when the trailing acknowledgement races. A modal
whose callback left the interaction unanswered acked it afterward; a dead or
already-acked interaction made that defer raise into
Modal.on_erroreven though the submission had processed. The trailing ack now absorbs the dead-interaction and already-acked cases, matching the view callback's post-callback defer. - Persistent views no longer render with a cold cache on restart.
on_restoreran on thesetup_hookcritical path, before the gateway cache was populated, so a render that readbot.get_user/members/channels painted defaults (e.g. default avatars) that never refreshed.on_restorenow runs afterbot.wait_until_ready()on a background task, so its render resolves real values; interaction routing still registers immediately during reattach. - Persistent leaderboard panels route clicks immediately after a restart.
PersistentLeaderboardLayoutViewbuilds its ranking controls inon_load, so reattach registered only the"No pages."placeholder tree and the real selects and nav buttons dropped clicks until the next state change.on_restorenow re-renders viareload(), whose message edit re-stores the real components in discord.py's view store. - Reattach no longer prunes a persistent view's row on a transient fetch failure. A
ForbiddenorHTTPExceptionduring the startup mass-fetch (a momentary permission change or a 5xx) previously deleted the registry row alongside a realNotFound, so a still-existing panel was orphaned and never reattached on a later restart. Only a definitiveNotFoundnow prunes; transient failures land in a newunreachablereattach-summary bucket and leave the row on disk for the next restart. - Persistent-view reattach logs one aggregate summary, not a line per view. Startup logged an INFO line per reattached view (a flood at hundreds of views) plus an aggregate dumping every key list. Reattach now logs a single INFO summary with counts; the per-view detail moved to DEBUG.
PersistenceMiddleware(migrators=...)now registers the migrators. Themigrators=keyword was accepted but silently ignored -- the value was stashed and never wired into the migration registries. It now takes a dict with optional"schema"and"kwargs"keys (each mapping(name, from_version)to an async migrator) and registers them duringinitialize(), before schema migration and rehydrate run. Registration is idempotent, so re-construction does not raise.subscribed_actionsdeclared on a base class is now inherited. The__init__defaulting checked the leaf class's__dict__instead of the MRO, so a value factored onto a base class was overwritten with an empty set and the view silently subscribed to nothing. It now resolves through the MRO and copies into a fresh per-instance set.TaskManagerno longer leaks a coroutine when a task is cancelled before it starts. A task cancelled in the same tick it was created left its coroutine unawaited, emitting a "coroutine was never awaited" warning. Tasks now schedule their coroutine directly and clean up through a done-callback, so a cancel-before-first-step unwinds cleanly.LoggingMiddlewarehonors its configuredlevelfor emission. The action stream was hardcoded toINFO; it now emits at the configured level and no longer pins the logger threshold, solevel="DEBUG"(orsetup_logging(actions="DEBUG")) keeps action traffic out of INFO logs.level="WARNING"no longer suppresses the stream -- useactions=Falsefor that.setup_loggingno longer prints literal ANSI escapes on a plain console. The console handler emitted color unconditionally, so a Windows console without virtual-terminal processing showed^[[31mcodes while the file handler stayed clean.setup_loggingnow detects color support (delegating to discord.py's detector, honoringNO_COLOR/FORCE_COLOR) and falls back to plain output; a newcolor=True/color=Falseargument forces it either way.Modalvalidation errors now name the field label, not its custom_id slug. A failed validator rendered the field's derivedcustom_id(e.g.input_emojifor a field labelled "Emoji") in the user-facing error line. It now prefixes the field's label instead.- Duplicate component
custom_ids are caught at build time with a directed error. Two components sharing acustom_idpreviously failed with an opaque Discord HTTP 400 at render, and two modal inputs deriving the same id from their label (e.g. two fields both labelled "Name") silently overwrote each other, dropping one field's submitted value. The pre-send validator now walks the component tree (V1 and V2) andModalchecks its inputs, each raising aValueErrorthat names the repeated id and the fix. - Link and premium buttons no longer break a stateful view. A link (
url) or premium (sku_id) button carries nocustom_id, but the custom_id stabilizer treated it as an auto-id button and assigned one, producing a Discord 400 (code 50035, "custom id and url cannot both be specified") whenever such a button sat in abuild_ui()tree. The stabilizer now skips both, and a V1PersistentViewno longer rejects a link button for lacking a custom_id.
[3.3.4] - 2026-06-19¶
Fixed¶
- Select selection changes now re-render. A
StatefulSelectrebuilt with only its selected option changed (viaset_selected()ordefault=) was treated as unchanged and the message edit was skipped, so the client kept showing the old selection and the next interaction submitted stale values. The render check now accounts for which options are selected. - In-callback navigation no longer edits the wrong message. Calling
push()orpop()from inside awith_confirmation-wrapped callback edited the ephemeral confirmation prompt instead of the view's own message, leaving the original message stale. Navigation now edits the view's message when the acting interaction belongs to a different one.
[3.3.3] - 2026-06-18¶
Added¶
/cascadeui inspectguild scoping. The inspector takes an optionalscopeargument: pass a guild id to target one guild, orglobal(orall) to show every guild. View and session state rows now carry aguild_idfield so the inspector can filter by guild.- Convenience components importable from the top level.
PrimaryButton,ToggleButton,Dropdown, and the other button/select subclasses now import directly fromcascadeui(previously only fromcascadeui.components).
Changed¶
- DevTools default to the current guild.
/cascadeui inspect,views,sessions, andexitallpreviously spanned every guild; they now scope to the guild where the command runs, andexitallno longer reaches other guilds' views. Pass/cascadeui inspect globalfor the all-guilds view. - Ephemeral views refresh more responsively. A self-refreshing ephemeral message no longer shows a brief pause after each interaction. The edit now ships immediately and the interaction is acknowledged in the background, removing a per-interaction round-trip.
- Navigation is more responsive.
push()andpop()(and the auto Back button) now edit the message and acknowledge the interaction in one round-trip instead of deferring first, removing a per-step pause on menu and wizard navigation.
Fixed¶
- Ghost views no longer accumulate in the inspector. Finite-timeout and
dismissed views could leak permanently into
/cascadeui inspect(present in state, absent from the live registry) when a teardown step failed partway through. Teardown is now atomic: the state entry is removed before the registry entry, so a failed or cancelled teardown leaves both intact and self-heals instead of stranding a ghost.
[3.3.2] - 2026-06-10¶
Added¶
edit_timeoutceiling on every view. Bounds each Discord edit the library issues after the initial send (refresh, navigation, teardown) withasyncio.wait_for, so a stalled connection is cancelled instead of pinning the view -- discord.py issues edits with no total HTTP timeout. Default60.0seconds; setNoneto restore unbounded awaits.
Fixed¶
- Ephemeral views could freeze under rapid clicking. An ephemeral
StatefulLayoutViewthat refreshed itself in component callbacks could intermittently show "This interaction failed" and go stale under latency. Ephemeral acting refreshes now acknowledge first and edit through the webhook, decoupling the ack from the slower ephemeral edit.
[3.3.1] - 2026-06-09¶
Fixed¶
- Typed select
default_valuesbroke serialization on discord.py 2.7.RoleSelect,UserSelect,ChannelSelect, andMentionableSelectraisedAttributeErrorwhendefault_valueswere supplied; fixed by coercing the type argument toSelectDefaultValueTypeat construction.
[3.3.0] - 2026-05-12¶
Added¶
PostgresBackendfor PostgreSQL persistence via the newpycascadeui[postgres]extra. asyncpg-backed connection pool withLISTEN/NOTIFYfor cross-process scoped invalidation. Configure withPostgresBackend(dsn=...); tuning kwargs and deployment hints in the persistence guide.- Backend extensibility via
Capability.RAW_SQL. SQL-capable backends (SQLiteBackend,PostgresBackend) declare the capability and exposeexecute/fetch/executemany/fetch_one/ asynctransaction()for user domain tables and vendor-specific features.placeholder_styleClassVar reports the parameter syntax for portable SQL.InMemoryBackenddoes not declare the capability. - V2 placement validator on
StatefulLayoutView. Walks the component tree before every Discord round-trip and raisesValueErrorwith a path string + fix on placements Discord 400s on (nesting, accessory misuse, Modal-only types, size bound violations). Opt out withvalidate_placement = False. file_attachment(url, *, spoiler=False)V2 builder. Wraps theFileprimitive for inline attachment cards; completes the V2 media family alongsidegallery().- Local file attachments on
view.send()andview.refresh(). Both V1 and V2 send acceptfile=/files=; mid-session swaps go throughrefresh(attachments=[...]). V2 media builders (gallery,image_section,file_attachment) acceptdiscord.Filedirectly and resolve through.uri. NewMediaInputtype alias (Union[str, discord.File]) exported at the package root. Newcascadeui.fetch_as_file(url, filename, *, session=None, spoiler=False, description=None)helper absorbs the aiohttp + BytesIO + discord.File construction pattern. Newexamples/v2_attachments.pycovers all four shapes end-to-end.
[3.2.0] - 2026-04-30¶
Added¶
DynamicPersistentButtonprimitive. Newcascadeui.components.base.DynamicPersistentButtonclass wrappingdiscord.ui.DynamicItem[discord.ui.Button]. Supports persistent buttons whose handler depends only on IDs encoded in thecustom_id, with no view-level state involved -- each click re-instantiates the class from the matched template regex. Snowflake capture coercion is automatic for groups nameduser_id,guild_id,channel_id,role_id, ormessage_id. Subclasses auto-register at class-definition time;setup_middleware( PersistenceMiddleware(..., bot=bot))callsbot.add_dynamic_items(*subclasses)so every subclass routes correctly after a restart with no additional user setup.coerce_snowflake_match(match_dict, snowflake_keys)helper incascadeui.utils.coercion. Coerces named regex capture groups tointfor known snowflake keys; complements the existingcoerce_snowflake_id/coerce_snowflake_id_sethelpers for theDynamicPersistentButtonfrom-custom_id path.RolesLayoutView/PersistentRolesLayoutViewpattern. New V2 multi-category role-assign panel built on top ofDynamicPersistentButton. Cardinality flags onRoleCategory(exclusive,required, and the four combinations) are enforced inside the pattern; users only declarecategoriesand the pattern handles button rendering, custom_id encoding, click routing, cardinality logic, response messages, and restart re-attachment. Three-tier customization surface: class attributes for static text / hints / colors (title,subtitle, fourhint_*, five*_message, per-categorycolor/button_style/icon/description), classmethod hooks for dynamic rendering (format_category_title,format_category_hint,format_button_label,format_button_emoji,format_button_style), and method override for full layout control (build_category_card). Five event hooks (on_role_assigned,on_role_removed,on_role_swap,on_role_required_block,on_role_error).RoleCategorytyped schema incascadeui.views.patterns.types. Dataclass with__post_init__validation; requirednameandroles(dict mapping role label to role ID), optionalexclusive/requiredcardinality flags,color,button_style,icon,description.SelectDefaultValueadoption on the four specialized selects (RoleSelect,UserSelect,ChannelSelect,MentionableSelect). Newdefault_values=constructor kwarg +set_default_values(values)method on each select; CascadeUI coerces rawintIDs / Discord objects (Member, User, Role, GuildChannel) / pre-builtdiscord.SelectDefaultValueinstances to the discord.py shape with the right type per select class.MentionableSelectinfers type from the object class (Member/User->"user",Role->"role"); rawintIDs are rejected because the type cannot be inferred.- Optional
description=kwarg on every modal input wrapper (TextInput,Checkbox,CheckboxGroup,RadioGroup,FileUpload). Populatesdiscord.ui.Label.descriptionfor an optional secondary helper line beneath the field title. - Four new class attributes on
LeaderboardLayoutViewfor single-line customization of ranking display. Each closes a gap where users previously had to override a whole method to tweak one literal: podium_emojis: Dict[int, str]-- rank-keyed glyphs (default gold/silver/bronze). Override the dict to change podium treatment or extend past rank 3 without overridingformat_rank.entry_separator: str = " -- "-- separator between name and stat columns insideformat_entry.card_color: Optional[discord.Color] = None-- accent color for the rankings card;Nonefalls through to the active theme.show_title_divider: bool = True-- toggle the divider rendered below the title.EmojiInputtype alias incascadeui.components.types, defined asOptional[Union[str, discord.Emoji, discord.PartialEmoji]]. Mirrors the union accepted bydiscord.ui.Buttonanddiscord.SelectOption. Adopted across every typedemoji=slot in the library (button builders, pattern ClassVar attributes, the refresh handoff). Strings, liveEmojiinstances, andPartialEmojiinstances all flow through unchanged.- Custom emoji documentation in the components guide and a
Type Aliasesentry in the API reference covering the three string forms (unicode, custom static, custom animated) and application-owned emojis. nav_inside_containerClassVar onPaginatedLayoutView(V2-only, defaultFalse). WhenTrue, the page content and the navigationActionRoware wrapped in a singleContainerso the paginator renders as one cohesive card with built-in navigation. Items added via_build_extra_itemsremain outside the wrapping Container in either mode. Single-page views render no nav row, so the flag has no effect when only one page is displayed.- Migration guide for users coming from Soheab's CV2 paginator gist and classic paginator gist in the patterns guide, mapping the gist API to CascadeUI's grammar.
push()andreplace()accept pre-constructed view instances in addition to view classes. The instance form pairs with async classmethod constructors (PaginatedLayoutView.from_data,from_cursor) where the view is built before the navigation call. Extra kwargs alongside an instance raiseTypeError-- the instance is already initialized. Backward compat preserved: passing a class continues to construct the view viaview_class(**kwargs).StatefulButtonandStatefulSelectacceptowner_only=Falsekwarg. WhenTrue, mismatched clicks route throughview.on_unauthorized(interaction)instead of the user callback. Pairs with view-levelowner_only=Falseto express open-view + host-only-button -- the canonical shape for lobby Start/Disband buttons, ticket Close buttons, poll End buttons.- Closure-factory subsection in the patterns guide for paginator formatters that need per-instance state.
push()andpop()now edit the Discord message regardless of whetherrebuildis supplied. Previously, omittingrebuildleft the message showing the parent view -- the navigation transition completed in state but the user saw no change. Therebuildkwarg is now an optional pre-edit hook for views that need post-construction setup (V2 views with empty trees that needv.build_ui(); V1 views that return anembed/contentdict for the edit). Views built by async classmethods likefrom_datacome fully populated and need no rebuild. The shared_apply_navigation_edithelper handles the defer + optional rebuild- edit cycle for both
pushandpop. The new view's_messageref preserves the parent's plainMessage(no 15-minute interaction token cliff) -- the edit response is dropped on the floor when a ref is already present. examples/v2_library.pydemonstrating pagination + drill-down navigation with auto back buttons.
Changed¶
- Modal input wrappers now render through
discord.ui.Label(discord.py 2.5+ pattern). Each of the five wrappers (TextInput,Checkbox,CheckboxGroup,RadioGroup,FileUpload) produces aui.Labelcontaining the inner discord.py input viacreate_discord_component(). The label string moves toLabel.text; the newdescription=kwarg populatesLabel.description. User-facing API unchanged: wrapper construction still takeslabel=as the first positional arg, validators still attach to the wrapper,Modal.on_submitstill writes back.value/.valueson the wrapper. Only difference visible to user code:modal.childrencarriesui.Labelwrappers around inputs instead of raw inputs at the top level. CascadeUI internally unwraps via_unwrap_labelduring submit collection. v2_persistence.pyexample rewritten to usePersistentRolesLayoutView. The hand-written cardinality logic collapses from ~200 lines to ~60 with no behavior change.- Every typed
emoji=slot widened fromOptional[str]toEmojiInput. No runtime behavior change -- discord.py was already accepting the wider union at the boundary; only the type annotations were narrower than reality. Markdown-routed sites (LeaderboardLayoutView.podium_emojis,RoleCategory.icon) staystr-typed because they render into TextDisplay markdown rather than piping todiscord.ui.Button'semoji=parameter. WizardLayoutViewnext-button emoji assignment simplified. Previously wrapped the class-attribute string indiscord.PartialEmoji.from_strbefore assigning toButton.emoji. WithEmojiInput, the wider union is assigned directly and discord.py'sButton.emojisetter performs the type discrimination internally._reattach_onebatches the registration dispatches andon_restoreinstore.batch(source_id=view.id). The three startup actions (SESSION_CREATED + VIEW_CREATED + VIEW_UPDATED) plus anyon_restoredispatches collapse into oneBATCH_COMPLETEnotification per restored view; previously each fired its own subscriber fan-out cycle. Linear savings as persistent-view count scales. Also tightens rollback atomicity -- failed reattach no longer leaks partial-state notifications to subscribers.
Fixed¶
- Acting-view fast-path stall no longer falls through to the
channel endpoint. The previous fall-through consumed the
auto-defer timer's ack budget and produced visible "interaction
failed" toasts under Discord-side latency.
refresh()now returns onwait_forcancellation; the timer acks with full remaining budget and the visible UI update arrives on the next state-change refresh. format_rankandformat_entrypreviously hardcoded literals that subclasses could only change by overriding the entire method. Both methods now read class attributes (podium_emojisandentry_separatorrespectively) so subclasses change one literal with a one-line attribute override.LeaderboardLayoutView.send()no longer double-attaches the navigation ActionRow. The send-time tree layout used to call_add_page_content()(which after the_compose_pagination_treerefactor adds the nav row inline) and thenadd_item(self._nav_row)separately, attaching the row twice. Switched the send path to a single_compose_pagination_tree()call matching the pattern in__init__and_update_page.- Back button no longer ships a redundant
edit_original_responsecall. After the push/pop unconditional-edit decoupling,_add_back_button'sback_callbackwas still callinginteraction.edit_original_response(view=prev_view)afterpop()had already routed through_apply_navigation_edit(which performs the same edit). Both V1 (_navigation.py) and V2 (layout.py) back-button callbacks now only edit whenpop()returnsNone(empty stack cleanup); successful pops let_apply_navigation_edithandle the message swap. _reattach_oneregistration order corrected. Persistent view rehydration now registers the view in_active_viewsbefore dispatchingVIEW_CREATEDvia_register_state, mirroring the_send_pipelineordering contract. The reversed order created a window where the view existed instate["views"]but not in the instance index, so concurrentsend()from another shard could bypass the instance-limit check during the brief reattach gap.InspectorView.state_selectorsignature widened to(view_id, message_id, channel_id)tuples per view. The previous ID-only signature equality-skippedVIEW_UPDATEDnotifications at the subscriber gate, so the Views tab'sChannel / Msgcolumns rendered asNone / Noneuntil the user manually refreshed.- Auto back button survives pattern rebuilds. Paginated page
turns, tab switches, form re-layout, menu refresh, role panel
rebuild, and wizard step advance all call
clear_items()and recompose. The auto back button injected bypush()was lost on every rebuild. Added_restore_navigation_artifacts()on_NavigationMixin(idempotent, no-op when no back button is registered); each pattern's rebuild path calls it after recomposing. - Quickstart counter example was missing
subscribed_actions, so the reducer ran buton_state_changednever fired and the message stayed stale. The V2 and V1 examples now declare the attribute, and the data-flow diagram surfaces the subscriber filter step. - Undo + slot-touching reducer chain no longer crashes with
TypeError: argument of type 'object' is not iterable. The undo middleware's_MISSINGsentinel now survives@cascade_reducer's state deep-copy boundary; previously the deep copy invalidated theis _MISSINGidentity check, leaving a bare object as the slot value for the next reducer to read.
[3.1.0] - 2026-04-21¶
Breaking¶
session_startfriendly-name hook removed. TheSESSION_CREATEDaction was previously reachable viastore.on("session_start", cb); the friendly name did not match theview_created/view_updated/view_destroyedgrammar used elsewhere. Usesession_createdinstead. No deprecation alias: the name was a grammar outlier, not a supported surface. Migration:store.on("session_start", cb)->store.on("session_created", cb).
Added¶
StateStore.get_active_views(). Public accessor returning a read-onlyMappingProxyTypeover the active-view registry (view_id -> view instance). The returned mapping is live but rejects mutation, so user code can iterate or count live views without reaching intostore._active_viewsand without risk of corrupting registry invariants.StateStore._build_initial_state(). Single source of truth for the canonical top-level state shape (sessions,views,components,application). BothStateStore.__init__andDevToolsCog.resetconsume it, eliminating the "new top-level key added to__init__but not toreset" drift class.- DevTools command surface expanded from 9 to 17. Eight new
subcommands land under
/cascadeui: - Registry introspection:
/cascadeui persistent(registeredPersistentViewclasses),/cascadeui scoped [slot](scoped bucket contents grouped by scope kind),/cascadeui computed [name](@computedregistrations with cache-primed status), and/cascadeui middleware(installed middleware in dispatch order). - Diagnostics:
/cascadeui history [n](recent dispatched actions),/cascadeui perf [action](toggle perf sampling:on/off/clear/status),/cascadeui trace [action](toggle ViewStore dispatch tracing), and/cascadeui subscribers(active subscribers with action-filter breakdown). DevToolsCoggroup listing auto-derived. The group'sctx.invokefallback now readsself.cascadeui_group.commandsat call time instead of a hardcoded listing, so adding a new subcommand does not require a parallel edit to keep the help banner accurate./cascadeui resetobservability. Reset now invalidates every@computedcache (viaComputedValue.invalidate()), clears subscriber selector memoization (store._last_selected), counts per-view exit failures, and surfaces the failure count in the response. Routes throughStateStore._build_initial_state()so the reset shape matches__init__exactly.
Fixed¶
- Action-registry drift across coupled tables.
INSPECTOR_PURGED_STALEwas missing from_BOOKKEEPING_ACTIONS(persistence middleware) and_SKIP_ACTIONS(undo middleware), and five action types (SCOPED_UPDATE,PERSISTENT_VIEW_REGISTERED,PERSISTENT_VIEW_UNREGISTERED,INSPECTOR_PURGED_STALE,APPLICATION_SLOTS_PRUNED,REGISTRY_PRUNED) had no corresponding friendly-name entry in_HOOK_ACTION_MAP. Internal table consistency; no user-facing API change beyond the now-reachable friendly names.
[3.0.0] - 2026-04-16 -- Stable Release¶
CascadeUI 3.0.0 is the first stable release. The view layer was reorganized
around a five-pillar model (Access Control, Instance Constraints, Lifecycle,
Session Membership, Navigation), the persistence machinery was rebuilt around
a capability-flag backend Protocol with per-namespace isolation, and the
public API was sharpened so every hook and class attribute follows a single
naming grammar (on_<event> for hooks, *_message for static text,
*_policy for behavior switches).
The entries below describe the feature surface of the library at this cut; future releases will document changes as standard Keep a Changelog diffs against this baseline.
View Layer -- Five Pillar Model¶
- Five Pillar refactor. Every view-layer feature now belongs to exactly
one of: Access Control, Instance Constraints, View Lifecycle, Session
Membership, Navigation. Documented in
docs/guide/five-pillars.md. instance_*family (instance_limit,instance_scope,instance_policy,instance_limit_message,on_instance_limit,InstanceLimitError) replaces the oldersession_*capacity vocabulary.state_scopereplacesscopeto disambiguate frominstance_scope.replace_policyreplaceson_replaceto keepon_*reserved for hooks.- API grammar enforcement.
on_<event>for override hooks,*_messagefor static text,*_policyfor behavior switches. Every public attribute follows the three-tier precedence model: class attribute -> method override -> explicit argument. - Render hook rename.
build_ui(no underscore) is the canonical render method.on_state_changed(replacingupdate_from_state) is the public state-change hook; default implementation callsbuild_ui()thenrefresh(). - Session model overhaul.
shared_data(wassession_data),session["members"](wassession["views"]),session["shared_data"](wassession["data"]). Session keys now usemodule.qualnameto avoid short-name collisions. Nav/undo/redo stacks are view-local with forward-transfer on push/pop. session_continuityopt-in. Default auto-derivedsession_idcarries a per-instance UUID suffix, so each view invocation gets its own session, navigation chain, and undo timeline. Views that want repeat-open state coalescing (undo history surviving close-and-reopen, shared_data continuity across gestures) setsession_continuity: ClassVar[bool] = Trueon the class. The opt-in collapses the derivation back to the class-coalesced shape. Navigation inheritance is unchanged -- push/pop chains stay on one session regardless of polarity because_navigate_toforwardssession_idexplicitly.
View Layer -- Capacity, Lifecycle, and Interaction¶
participant_limittrio. Class-level cap on total view occupants paired withparticipant_limit_message(static) andon_participant_limit(dynamic).register_participant()returnsbool;auto_register_participantsflag performs all-or-nothing rollback before any Discord side effects.set_class_attribute()for per-instance policy override of class-level attributes; runs the same validation pipeline as__init_subclass__and rejects descriptor shadowing.check_instance_available()classmethod for sync pre-checks before expensive__init__.attach_child()andparent=kwarg. Parent-local cleanup cascade with optional auto-attachment on successfulsend().protect_attachedexcludes views with active participants or attached children from replacement candidates.- Hook surface expansion.
on_unauthorized/unauthorized_message,on_replaced/replaced_message,on_message_delete,on_reopen_failure/reopen_failure_message,error_messagefor the defaulton_errorembed. exit_policy(default"delete"for replaces) governs whether bareexit()deletes, disables, or leaves the message untouched.send()rollback. Three-tier teardown (instance-limit, participant registration, Discord HTTP) with fullexit()-mirror cleanup. ReturnsNoneon instance-limit rejection rather than raising.- Ephemeral session handling. Timeout derivation is driven by the user's
timeoutvalue. Whentimeout <= 900the view lives inside the 15-minute webhook token and expires normally. Whentimeout > 900the library auto-engagesauto_refresh_ephemeral, installs a refresh button at T+810s, and freezeson_state_changedrebuilds once armed so state notifications cannot clobber the refresh button before the T+900s cliff.on_reopen_failure/reopen_failure_messagecontrol what the user sees when reconstruction fails.exit()distinguishesNotFound(silent), ephemeral401token expiry (DEBUG), and otherHTTPExceptionerrors (ERROR), matching the three-tier precedent established byrefresh(). - Push/pop kwarg auto-capture.
__init_subclass__snapshots constructor kwargs so navigation works transparently without manual wiring. - Message handling.
send()re-fetches the message via the channel endpoint to avoid the 15-minute interaction-token expiry._webhook_messagedual-reference preserves embed-edit capability for V1.refresh()replaces manualmessage.editpatterns. - Interaction helpers.
respond(),open_modal(), and_safe_defer()withis_done()fallback. Auto-defer safety net (timer + post-callback defer) plusserialize_interactions = Truedefault. - Refresh throttling. Rate-limit-aware: reactive 429 backoff is always
on; opt-in
refresh_cooldown_mssets a proactive cooldown window. Deferred refreshes re-enteron_state_changedagainst the latest store state.
View Layer -- Decomposition¶
StatefulViewextracted tocascadeui/views/view.py, mirroringStatefulLayoutViewinlayout.py._InteractionMixin(_interaction.py) and_NavigationMixin(_navigation.py) separate the interaction and navigation concerns from the core mixin.- Shared
_send_pipeline()deduplicates the V1/V2 send logic so rollback and registration are written once. cascadeui/views/patterns/package groups V1 and V2 variants per pattern file, with_Base{Pattern}Mixinextracted in each.cascadeui/exceptions.pyat the package root holds runtime exception types callers catch programmatically (currentlyInstanceLimitError).
View Patterns¶
MenuView/MenuLayoutView-- category-based navigation hub with push/pop drill-down, themed cards, and per-category style customization.LeaderboardLayoutView/PersistentLeaderboardLayoutView-- V2-only paginated ranked display withget_entries(),format_entry(), andbuild_summary()hooks.- Leaderboard Section render mode.
entry_layout = "sections"renders each rank as a DiscordSectionwith splitformat_primary()/format_secondary()hooks and an asyncget_avatar_url()accessory. Falls back to a stacked two-lineTextDisplaywhen the avatar hook returnsNone, so a platform requirement (Section requiresaccessory=) never forces a subclass override.entry_layout = "sections"is coupled toleaderboard_per_page <= 5to stay inside Discord's component caps, validated at class-definition time. PaginatedView.from_cursor()lazy pagination. Classmethod for paginating over an asyncfetch(page_idx) -> PageResultcursor instead of an eager in-memory list. Fetched pages ride an LRU cache that protects the current page from eviction, so navigation away and back never shows "Loading..." on the page the user is looking at.refresh_pages()clears the cache and re-fetches the current page in place.DisplayLayoutView-- one-shot V2 send shorthand that accepts acontainer=kwarg without requiring a subclass.- Pattern customization. Wizard navigation, Tab active/inactive style,
and Pagination navigation each gain customization triples plus
on_finish(),on_tab_switched(), andon_page_changed()method hooks (replacing constructor-parameter callbacks). - Wizard navigation hooks.
on_step_entered(step_index)fires after forward/back navigation settles on a new step;on_step_exited(step_index)fires before the wizard leaves a step;on_validation_failed(step_index, error, interaction)fires when a step validator returns(False, error). Defaulton_validation_failedresponds ephemerally with the error text. - Wizard conditional steps. A step dict accepts an optional
"condition": Callable[[], bool]predicate; Back and Next skip past steps whose condition returns False at navigation time. A condition that raises is treated as visible (safe fallback) and logs a warning. Step-indicator counts andis_lastresolution use the visible-step count, not the declared-step count. - Wizard progress header (V2 only).
WizardLayoutViewrenders a themedcard()containing aprogress_barabove step content when more than one visible step exists. Override_build_progress_headerto customize the container or returnNoneto suppress. Disable globally viashow_progress_bar = False. - Wizard step-builder theme context.
_rebuild_step_contentruns inside the view's theme context, so anycard()call in the user's step builder (or in_build_progress_header) inherits the view's accent colour automatically. - Form field-change hook.
on_field_changed(field_name, old, new)fires on every field transition (select, boolean, modal text). The hook is gated onold != new, so repeated identical submissions do not trigger redundant work. - Form inline validation errors. Validator failures surface on the
form body instead of an ephemeral message.
_field_errorsmaps field id to error list;_form_errorholds a form-level message. V1 renders errors as a red-tinted embed with a warning line under each failing field; V2 renders a top-levelalert()container plus inline warning lines inside each field's card. Errors clear automatically on any field-change gesture, so the UI stays in sync with the latest input. - Form field groups. A field dict accepts an optional
"group": "Section Name"key. Consecutive fields sharing the same group collect into a single run (no merging across interleaved groups, so declaration order is the UI contract). V1 renders each run as a bold-headed embed field; V2 renders each run as its own themedcard(). - Form typed field types.
integer,float, anddatejointext,boolean, andselectas first-class field types. Typed modal fields ride the shared form modal alongsidetext(5-input Discord cap is now measured against the union). Parse failures surface as inline field errors while preserving the user's raw input so the next modal open shows what they typed.min_value/max_valuefield keys clampintegerandfloat;dateaccepts ISO 8601 (YYYY-MM-DD). The submit callback short-circuits when_field_errorsis populated, so validators never fire against unparsed strings. - Form
multi_selectfield type. Renders aStatefulSelectwithmin_values=1when required,max_values=max(1, len(options))by default (override via the optionalmax_valuesfield key). Selected options survive rebuilds viaSelectOption(default=...), and the callback writes alisttoform.values. Required-field checks count an empty list as unset. - Typed form / wizard schemas.
FormField,FormSchema,WizardStep, andWizardSchema(all exported fromcascadeui) give form and wizard patterns a typed construction path with IDE auto-complete and class-definition-time validation. Patterns accept either the existing dict API (fields=[{...}],steps=[{...}]) or the typed variant (fields=[FormField(...)],schema=MySchema()); passing both raisesValueError. Typed entries lower to the same internal dict shape through.to_dict(), so every downstream helper keeps working against one canonical representation. on_category_selected(was_on_category_selected). MenuView / MenuLayoutView pre-push hook now follows the publicon_<event>grammar. No deprecation alias -- override sites rename in place.- V2 button-mutation parity. Wizard / Tab / Paginated V2 variants now rebuild navigation buttons in the component tree instead of mutating individual button attributes.
PaginatedLayoutView._build_extra_items()preserved across page navigation.
Components¶
- Grid helpers.
emoji_grid()returns a liveEmojiGrid(TextDisplay subclass) supporting cell, row, rectangle, and bulk assignment with optional"alpha"/"numeric"axis labels.button_grid()packs a(row, col) -> Buttonfactory into ActionRows enforcing Discord's 5x5 component cap. Seeexamples/v2_grids.pyfor the standalone showcase. - V2 builder expansion.
stats_card()(themed key/value summary panel),progress_bar()(text-rendered bar readable inside any TextDisplay),confirm_section()(Section + confirm/cancel button pair),link_section()(Section +LinkButtonaccessory),button_row()(ActionRow-wrapped button sequence),cycle_button()(button that rotates a state value through a preset list),toggle_button()(one-button on/off toggle), andtab_nav()(tab strip renderer for hand-rolled tab views). All return standard discord.py V2 components and compose cleanly withcard(). - Modal input wrappers.
Checkbox,CheckboxGroup,RadioGroup,FileUpload, plusTextInput(validators=[...])as the canonical validator-attachment shape.Modalauto-collects validators from all five wrapper types and writes submitted values back to the wrapper instances. FormViewnative"text"field support via grouped modal collection (theFormLayoutcomposite is removed as redundant).StatefulSelectgainsset_selected()/get_selected()for state-driven defaults and a disabled-placeholder fallback when options are empty. Select callbacks may declare an optional secondvaluesparameter.
State System¶
@computeddecorator with cached selectors. Module-level registry preserves registrations across store resets so tests that replace the singleton no longer lose computed values.access_slot()auto-vivifiesstate["application"][name][key]with adefault_factory;read_slot()is the variadic pure-read counterpart for selectors and@computed.slot_propertydescriptor reads slots from instance state.persistent=Trueonaccess_slotregisters the slot name for write-through persistence viaPersistenceMiddleware.- Scoped state accessors.
StateStore.get_scoped(),get_scoped_from()(staticmethod for use inside reducers),iter_scoped(),set_scoped(),merge_scoped(). Four-axis scoping (user,guild,user_guild,global) with named-slot routing viascoped_slotclass attribute. seed_initial_state(state)hook on_StatefulMixinfor views that need to seed slots before the first render.@cascade_reducerraises on built-in action collision and warns on same-namespace overwrite.register_reducerexposes the same warning at the store level.- Hybrid subscriber notifications.
_notify_subscribersruns a two-path fan-out keyed onaction["source"]: the acting subscriber (whose id matches the action source) is awaited inline so its refresh rides the interaction's ack cycle, while every other subscriber is scheduled as a background task viatask_manager. State snapshots are passed by argument so every task sees the state that matched its notification.BatchContext.source_idthreads the same contract through batched regimes.store._flush_notifications()drains in-flight tasks for tests; production code never needs to flush. - Acting-view
interaction.response.edit_messagefast path. The acting view's refresh ships as one REST round-trip instead of two (ack + channelPATCH)._CURRENT_INTERACTIONcontextvar bound inStatefulComponent.create_stateful_callbackletsrefresh()route the edit through the interaction response slot when the handled interaction is a component click targeting this view's message and its response is still open. Disqualified cases (modal submits, cross-view dispatches, missing message, already-deferred responses) fall through to the channel endpoint with no behavior change; 429 arms the reactive backoff window; non-429 HTTP errors fall through to the channel path so a transient interaction-endpoint failure never loses the refresh. batch()is transitive.store.dispatch()queues actions when a batch is active; nested batches absorb into the outer batch. Per-action profiling samples are suppressed inside batches and one syntheticBATCH_COMPLETEaction carries the rolled-up sample withbatch_size.- Library uses
batch()internally in_send_pipeline,_navigate_to, and_cleanup_attached_children. - Undo coverage expanded to include
dispatch_scopedandupdate_session. Snapshots store a per-slot diff of theapplicationkeys the action actually touched (paired with the session'sshared_data) rather than a wholesale copy, using a_MISSINGidentity sentinel for added slots. Sibling views writing to their own slots survive this view's undo path, closing a cross-view contamination class that wholesale snapshots could not. UNDO/REDO bypass subscriber action filters so cross-view reactivity works without explicit subscription. subscribed_actionsdefault is now an empty set (subscribe to everything by default).- StateStore public/private boundary. Registration plumbing
(
_register_reducer,_register_computed,_register_view,_register_participant,_add_middleware,_unsubscribe, and their counterparts) is single-underscore-prefixed; the public surface isdispatch,subscribe,batch,on/off,has_middleware, the scoped accessor family, and thestate/computedproperties. TheBatchContext.dispatch(...)legacy shim is removed -- usestore.dispatch(...)insideasync with store.batch(). The livePersistenceManagerstashed byPersistenceMiddleware.initializeis now published asstore.persistence_manager(previouslystore._persistence_manager); the public name matches the rest of the store's read surface and is the documented path for manual prune, flush, and reattach-summary access.
Persistence¶
- Two-namespace persistence. Registry and application each write as
an independent stream with its own debounce window. Scoped data rides
under the application namespace -- the middleware routes scoped writes
through the same application-diff pipeline, so per-user/guild buckets
persist when a view opts its scoped slot in via
persistent_slots. PersistenceBackendProtocol withCapabilityflags (KV,RELATIONAL,SCHEMA_META). Built-in backends:InMemoryBackend(always available, reference implementation; reused as the default testing seam) andSQLiteBackend(optional viaaiosqlite).- Per-namespace configs (
RegistryPersistence,ApplicationPersistence) govern slot policies and debounce windows per namespace. Configured once atPersistenceMiddlewareconstruction; shorthandbackend=fills any namespace the caller leaves unconfigured. The registry is always persisted; application slots (including scoped) are opt-in via thepersistent_slotsclass attribute orSlotPolicy(persistent=True)at setup, so nothing is retained by accident. - Typed persistence exceptions.
PersistenceErrorbase plusPersistenceConfigError,PersistenceInitError,PersistenceSchemaError, andPersistenceRehydrateErrorfor the four failure classes (bad construction config, backend init failure, schema migration failure, view rehydration failure). Exported from the package root. - Schema migration registry.
register_migrator(namespace, version, fn)for payload-shape migrations between schema versions;register_kwargs_migrator(view_cls, fn)for rewriting captured constructor kwargs when a view's__init__signature changes. PersistenceMiddlewarereplacesDebouncedPersistencewith identity-diff dirty tracking, max-age ceilings, retry backoff on backend failure, and observability hooks. Skips bookkeeping actions and dispatch-only actions whose state reference is unchanged.- Unified middleware install.
setup_middleware(*middlewares, store=None)installs every middleware through one async helper: add to the dispatch chain (guarded by class so repeat calls are no-ops), then await each middleware'sinitialize(store)if present.PersistenceMiddlewareis now constructor-configurable (backend=,registry=,application=,bot=,migrators=) and owns its own seven-phase startup pipeline; the old top-levelsetup_persistence()entry point is gone. Bot-type validation fires at construction so misuse points at the user's call site. setup_logging(actions=True)auto-installsLoggingMiddlewarefor observability without a separateadd_middlewarestep.- Restore-time hardening. Ghost
views/sessions/components/modalsentries pruned on load.PersistentViewre-derivessession_idafter identity restoration. Messageable guard on orphan cleanup avoids crashes onCategoryChannel/ForumChannel.
DevTools and Performance¶
InspectorViewrebuilt as aTabLayoutViewwith six tabs (Overview, Views, Sessions, History, Performance, Config), self-filtering to avoid observer-effect noise, and live auto-refresh viaVIEW_CREATED/VIEW_DESTROYEDsubscriptions. Uses@computedinternally for the Overview aggregations.- Interactive controls. Purge Stale, Flush to Disk, Clear History, Exit Selected / Exit All, Clear Selected.
/cascadeuihybrid command group with nine owner-only subcommands (inspect,views,exit,exitall,sessions,clear,flush,purge,reset).- Profiling tab with reducer / middleware / notify sample breakdown,
per-subscriber timing inside the notify fan-out, per-dispatch edit counter,
and split
middleware_ms/reducer_mscolumns. - Render-hash short-circuit in
refresh()skipsmessage.editwhen the rendered tree digest is unchanged. - Reducer shallow-copy replaces
copy.deepcopyin the dispatch path. - Persistence no-op when state is unchanged.
- Leaderboard rebuild short-circuit. A semantic
_entries_signature_forguard skips the page-list rebuild when the source entries have not changed, andasyncio.gatherresolves avatars concurrently during a single page build so the Section render mode does not serialize per-entry CDN fetches. - Stable
custom_ids across rebuilds._stabilize_custom_ids()runs at two seams -- after everybuild_ui()and at the top ofrefresh()-- so pattern rebuilds that bypassbuild_ui()still emit the samecustom_idfor the same logical component across re-renders. Prevents Discord'sViewStorefrom dropping in-flight clicks when a rebuild swaps in a new button instance. - Automatic message-deletion cleanup via gateway listeners
(
on_raw_message_delete,on_raw_bulk_message_delete).
Theming¶
- Theme context propagation via
contextvars.ContextVar. Builder functions likecard()andstats_card()auto-read the active view's theme as a fallback when no explicitcolor=is passed. - Class-level
theme = my_themepreserved alongside the kwarg path; validated in__init_subclass__. get_current_theme()returns the active theme inside a view context.- Removed unused theme methods, style keys, and the "Powered by CascadeUI" footer default.
Defensive Input Handling¶
- Class-attribute validation.
__init_subclass__validates enum, int, bool, and float class attributes at subclass-definition time. Catchesinstance_policy = "rejct"orowner_only = 1before any user clicks a button. - Snowflake coercion at
__init__, theallowed_userssetter, andregister_participant. Accepts eitherintordiscord.abc.Snowflake; raisesTypeErrorfor genuinely unrecognizable values. Helper lives incascadeui/utils/coercion.py. set_class_attribute()guards._INSTANCE_DATA_ATTRSrejects snowflake-domain data; descriptor walk rejects shadowing methods or properties.attach_child()invariants. Self-attachment and circular-chain attachments raiseValueError; re-parenting detaches cleanly from the old parent.
Examples¶
New examples introduced in 3.0.0:
v2_hello_world.py-- the canonical minimal example. A single-button counter showingstate_scope = "user",subscribed_actions, the defaulton_state_changed(), and the smallest viable CascadeUI cog.v2_grids.py-- standalone showcase foremoji_grid()andbutton_grid(), exercising axis labels, bulk assignment, and the eight preset variations in/grid_gallery.v2_battleship.py-- 10x10 two-player game. Debut platform foremoji_grid()(live cell mutation),auto_register_participants,@computedaggregations,user_guildscope, and cross-view reactivity through ephemeral fleet panels.v2_tictactoe.py-- configurable board size (3x3 to 5x5) with thebutton_grid()debut, configurable win length (minimum corrected to 3), and per-player scoped stats viauser_guildscope.v2_lobby.py-- open-join Werewolf-style flow keepingauto_register_participants=Falsefor the documented exception case.v2_computed.py-- memoized derived state demo using the@computedregistry.
Project¶
- Test suite expanded to 1509 tests, all green, covering the new view-layer decomposition, persistence rebuild, computed selectors, scoped state accessors, refresh throttling, and the multi-user participant model.
- Python 3.10, 3.11, 3.12, 3.14 support continues; discord.py 2.7+ remains the only runtime dependency.
Pre-stable history¶
The releases below predate the 3.0.0 stable cut. They are kept for historical reference. New users should pin to 3.0.0 or later.
[2.1.0] - 2026-04-05¶
Added¶
-
allowed_userson_StatefulMixin--Optional[Set[int]]attribute that overridesowner_onlywhen set. Provides declarative access control for multi-user views (games, polls, collaborative tools). Supports runtime mutation for "join this game" patterns. Precedence:allowed_users>owner_only> allow all. Reusesowner_only_messagefor rejections. -
Participant-aware sessions --
register_participant(user_id)andunregister_participant(user_id)on views. Participants get their own scope keys in the session index so thatsession_limitapplies to all users in a multi-user view, not just the owner. Always-reject policy for participants (never exits someone else's view to make room)._enforce_session_limitnow only replaces views owned by the same user.SessionLimitErrorgains optionalblocked_user_idfor cog-level error handling. Participants propagate on push/pop, cleared on replace. Scope key deduplication for guild/global scopes prevents duplicate index entries. -
TicTacToe example (
examples/v2_tictactoe.py) -- two-player V2 game demonstrating challenge acceptance flow, dynamic board size (3x3 to 5x5), configurable win length (e.g. 3-in-a-row on a 5x5 board), Discord mentions, mutual rematch agreement, participant session integration, forfeit tracking, and a custom game statistics reducer.
Changed¶
-
card()accepts mixed children --card()now takes*childreninstead of a separatetitleparameter. Strings anywhere in the argument list are automatically wrapped inTextDisplay. This allows building a list of components and unpacking it (card(*items)) without worrying about whether the first item is a string orTextDisplay. Fully backward compatible with existingcard("## Title", ...)usage. -
_enforce_session_limitreplace policy refinement -- under replace policy, only views owned by the current user are replaceable. Views where the user is a participant (owned by someone else) are never replaced. Previously irrelevant because participant scope keys didn't exist; now load-bearing with participant sessions. -
Documentation updates -- API reference covers
allowed_users,register_participant,unregister_participant, andSessionLimitError.blocked_user_id. Views guide adds "Multi-User Access Control" and "Participants and Multi-User Views" sections. Examples page includes TicTacToe. README adds Developer Tools showcase and multi-user feature bullet.
Removed¶
- Unnecessary
on_state_changedstubs -- removed ~14 redundantpassoverrides from library pattern views (TabView,WizardView,TabLayoutView,WizardLayoutView) and examples. The base class_StatefulMixin.on_state_changed()is already a no-op.
[2.0.0] - 2026-03-31¶
Added¶
-
V2 component system support -- full support for Discord's V2 message components (Container, Section, TextDisplay, MediaGallery, Separator, Thumbnail, File) alongside the existing V1 (View/embeds) system. Both coexist per-message; V1 is not deprecated.
-
StatefulLayoutViewbase class extendingdiscord.ui.LayoutViewwith all the same state management features asStatefulView: subscriptions, navigation stack, undo/redo, session limiting, auto-defer, owner_only. V2 views carry their display content as children (no content/embed/embeds parameters). -
PersistentLayoutViewfor V2 views that survive bot restarts. Shares the same persistent view registry asPersistentView. Useswalk_children()for custom_id validation in the V2 component tree. -
V2 pre-built patterns:
PaginatedLayoutView-- pages as V2 component trees with the same nav controls, go-to-page modal,from_data()factory, andrefresh_data()as V1FormLayoutView-- Container+TextDisplay display with the same validation pipelineTabLayoutView-- button-based tab switching with async buildersWizardLayoutView-- multi-step with back/next navigation, step validators, andon_finishcallback
-
V2 convenience helpers (
cascadeui.components.v2_patterns):card(),action_section(),toggle_section(),key_value(),alert(),divider(),gap(),image_section(),gallery(). Assembly shortcuts for common V2 patterns, all returning standard discord.py V2 components. -
V2 theming:
accent_colourandseparator_spacingproperties onTheme.apply_to_container()method for applying theme accent color to V2 Containers. All built-in themes includeaccent_colour. -
Navigation version enforcement:
push()/pop()between V1 and V2 views raisesTypeErrorbecause Discord'sIS_COMPONENTS_V2flag is one-way per message.replace()is allowed for cross-version transitions. -
_freeze_components()on_StatefulMixin-- single method that disables all interactive items, handling both V1 flat children and V2 recursive tree traversal. -
Cross-view reactivity documentation in the state management guide, explaining
dispatch()vsdispatch_scoped()for multi-view UIs. -
V2 examples:
v2_counter.py,v2_dashboard.py,v2_settings.py,v2_form.py,v2_pagination.py,v2_wizard.py,v2_persistence.py-- covering all V2 patterns with session limiting and V2 helpers throughout. -
rebuild=callback onpush()/pop()-- optional kwarg that auto-defers the interaction, calls the callback with the new view, and edits the message. V2:rebuild=lambda v: v.build_ui(). V1:rebuild=lambda v: {"embed": v.build_embed()}. -
Interaction serialization (
serialize_interactions = Trueby default) --asyncio.Lockin_scheduled_taskserializes rapid button clicks, preventing racingmessage.edit()calls. Auto-defer runs outside the lock. -
slugify()utility for converting display strings to safecustom_idfragments. -
DevTools V2 rebuild:
InspectorViewis now aTabLayoutViewwith 5 tabs (Overview, Views, Sessions, History, Config), self-filtering, and live auto-refresh viaVIEW_CREATED/VIEW_DESTROYEDsubscriptions.
Changed¶
-
_StatefulMixinextraction: ~840 lines of view-agnostic state management extracted fromStatefulViewinto_StatefulMixin.StatefulViewis now_StatefulMixin + View;StatefulLayoutViewis_StatefulMixin + LayoutView. No public API changes for V1 users. -
Session isolation: Auto-derived
session_idnow includes the class name (e.g.MyView:user_123) so independent view hierarchies get separate nav stacks and undo history. Pushed/popped views inheritsession_idfrom their parent. -
Button consistency: All interactive buttons (library internals and examples) use
StatefulButton(callback=...).StatefulButtonskipsCOMPONENT_INTERACTIONdispatch whenview.is_finished(), preventing extra state noise on exit/back. -
Message propagation:
_navigate_to()automatically transfers the message reference to pushed/popped views soon_state_changed()can edit the message without manual wiring. -
V2 exit behavior:
exit()freezes V2 views and edits with the frozen view (preserving visual content) instead ofedit(view=None)which would produce an empty message. V1 behavior unchanged. -
Settings examples (V1 and V2) now use
dispatch("SETTINGS_UPDATED")across all sub-pages for consistent live updates on the hub view. -
@cascade_reducerauto-deepcopy: The decorator now deep-copies state before passing it to the reducer function. Custom reducers no longer needimport copyorcopy.deepcopy(state). All example reducers updated to usestatedirectly. -
Component module naming: Version-specific files renamed to
v1_composition.py,v1_patterns.py,v2_patterns.pyfor clarity. Shared files have no prefix. -
DebouncedPersistencedouble-write fix: Store's built-in per-dispatch_persist_state()is automatically skipped whenDebouncedPersistencemiddleware is installed, preventing redundant disk writes. -
Session cleanup on view destroy: Empty sessions (no views, no nav stack) are automatically deleted when the last view exits.
-
Documentation overhaul: All guide and API reference pages rewritten V2-first with tabbed V2/V1 examples. Fixed
@cascade_reducerexamples that incorrectly showed manualcopy.deepcopy(). Added Known Limitations page.
[1.0.0] - 2026-03-23¶
First public release. CascadeUI is a Redux-inspired UI framework for discord.py that provides state management, component composition, theming, and persistence.
Core Architecture¶
- StateStore singleton with pub/sub subscriptions, action filtering, and state selectors for fine-grained notification control
- Unidirectional data flow: action -> middleware -> reducer -> state -> UI
- Custom reducers via
@cascade_reducerdecorator - Action batching with
batch()context manager for atomic multi-dispatch operations with a single subscriber notification - Event hooks via
on()/off()for lifecycle observation - Computed state with
@computeddecorator andComputedValuefor cached derived values that invalidate when dependencies change - Middleware pipeline with chain composition; built-in
DebouncedPersistence(batched writes with configurable interval) andlogging_middleware - 14 built-in action types:
VIEW_CREATED,VIEW_UPDATED,VIEW_DESTROYED,SESSION_CREATED,SESSION_UPDATED,NAVIGATION_PUSH,NAVIGATION_POP,NAVIGATION_REPLACE,SCOPED_UPDATE,COMPONENT_INTERACTION,MODAL_SUBMITTED,PERSISTENT_VIEW_REGISTERED,PERSISTENT_VIEW_UNREGISTERED,UNDO,REDO
Views¶
- StatefulView base class extending
discord.ui.Viewwith state integration, message lifecycle management, automatic cleanup on exit/timeout - Navigation stack with
push(),pop(), andreplace()for multi-level view hierarchies; shared cleanup path via_navigate_to() - Per-user and per-guild state scoping via
scope="user"orscope="guild"withscoped_stateproperty anddispatch_scoped()method - Undo/redo via
UndoMiddlewarewith configurable history depth per view session - Session limiting with declarative
session_limit,session_scope("user","guild","user_guild","global"), andsession_policy("replace","reject"); active view registry with O(1) scope lookups;SessionLimitErrorfor reject policy and PersistentView protection; session origin tracking through push/pop navigation chains - Interaction ownership with
owner_only(defaultTrue) and customizable rejection message;PersistentViewdefaults toowner_only = False - Auto-defer safety net that automatically defers slow interactions after a configurable delay (default 2.5s), preventing "This interaction failed" errors; safe with all wrappers and manual defer calls
- State selectors via
state_selector()override for efficient re-rendering; views only receive notifications when their selected state slice changes
View Patterns¶
- TabView: Button-based tab switching with active tab highlighting
- WizardView: Multi-step form with Back/Next/Finish navigation and per-step validation
- FormView: Declarative form with field definitions, built-in validation,
and submit callback; supports
"select"and"boolean"field types - PaginatedView: Page navigation with first/last jump buttons and go-to-page
modal for large datasets (controlled by
jump_threshold, default 5);from_data(items, per_page, formatter)async factory; supports Embed, string, and dict pages with mixed embed + content;refresh_data(items)for live re-pagination;_build_extra_items()hook for subclass components on rows 1-4 clear_row(n)utility on StatefulView for row-level component management- Transparent kwargs auto-capture via
__init_subclass__-- all subclass constructor kwargs are automatically preserved forpush()/pop()navigation reconstruction without any manual effort from subclass authors
Persistence¶
setup_persistence()single entry point for all persistence; call once insetup_hook; supports data-only mode (no bot) or full view re-attachment- PersistentView subclass for views that survive bot restarts; forces
timeout=None, requires explicitcustom_idon all components, auto-registers subclasses via__init_subclass__ - Storage backends:
FileStorageBackend(JSON with.bakbackup),SQLiteBackend(aiosqlite, WAL mode),RedisBackend(redis.asyncio) migrate_storage(source, target)utility for moving state between backendsstate_keyfor stable data identity across view lifetimes (vs ephemeral UUID view IDs)- Identity persistence:
user_idandguild_idstored in persistent view registry and restored on bot restart so session limiting works across restarts - Duplicate state_key cleanup: Two-tier orphan handling when re-registering
a
state_key: exits live view instances via the active registry, falls back to message-only cleanup for cross-restart orphans - Stale entry handling: Deleted messages/channels cleaned from state on restore; missing view classes skipped but kept for next restart; non-messageable channels detected and removed
on_restore(bot)hook for post-restore setup on PersistentView
Components¶
- StatefulButton and StatefulSelect extending discord.py UI components
with automatic
COMPONENT_INTERACTIONaction dispatching - CompositeComponent for grouping related components with a registry for reusable compositions
- ConfirmationButtons: Confirm/Cancel button pair with callbacks
- PaginationControls: Previous/Next with page tracking and boundary handling
- FormLayout: Renders form field definitions as interactive components
- ToggleGroup: Radio-button-like selection with on_select callback
- ProgressBar: Text-based progress indicator for embed fields
- Modal and TextInput with optional validation via
validatorsparameter; exported from top-level package - Component wrappers:
with_loading_state(visual loading feedback),with_confirmation(confirmation dialog before action),with_cooldown(per-user rate limiting)
Theming¶
- Theme class with colors, button styles, and embed styling
- Global registry with
register_theme(),get_theme(),set_default_theme() - Per-view theming via
theme=kwarg on StatefulView with fallback to default - Built-in themes:
default_theme,dark_theme,light_theme
Validation¶
- ValidationResult dataclass for structured pass/fail results
- Built-in validators:
min_length,max_length,regex,choices,min_value,max_value validate_field()andvalidate_fields()supporting sync and async validators- Integrates with FormView and Modal for per-field error reporting
DevTools¶
- StateInspector generates paginated embeds showing state overview, active views, sessions, action history, and store configuration
- InspectorView for browsing inspector pages (plain
discord.ui.Viewto avoid polluting state) - DevToolsCog with
/inspectcommand gated behind@is_owner()
Utilities¶
@cascade_reducerdecorator for registering custom reducers@cascade_componentdecorator for component registration@with_error_boundaryand@with_retryfor resilient callbackssafe_execute()for protected async execution- TaskManager for background task tracking with proper cleanup/cancellation
- AsyncLogger with color-coded output and file rotation
Documentation¶
- MkDocs Material site at hollowthesilver.github.io/CascadeUI/
- 18 pages: installation, quick start, state management, views, components, persistence, theming, middleware, devtools, examples, and API reference
- 8 example cogs: counter, themed form, persistence, navigation, state features, undo/redo, advanced settings menu, production-style ticket system
- README with visual-first showcase and GIF demos; detailed tutorials on the documentation site
Project Infrastructure¶
- GitHub Actions CI pipeline: pytest matrix across Python 3.10, 3.11, 3.12, 3.14; Black and isort formatting checks on push and PR
- CONTRIBUTING.md with development setup, code style, and bug reporting guidelines (including log file guidance)
- SECURITY.md with vulnerability reporting instructions
- GitHub issue templates (bug report with structured fields, feature request) and pull request template
- CHANGELOG.md following Keep a Changelog format
Compatibility¶
- Python 3.10, 3.11, 3.12, 3.14
- discord.py 2.7+
- PEP 561 typed package (
py.typedmarker) - PyPI classifier: Production/Stable
- 225 tests across 22 test files