gum-runtime-hot-reload
Skill659 starsChanged 2 months agoMITView on GitHub
Runtime hot reload — FileSystemWatcher rebuilds the Gum element tree when .gumx/.gusx/.gucx/.gutx/.fnt files change. Triggers: GumHotReloadManager, IGumHotReloadManager, GumService.EnableHotReload, debounce, font cache eviction during reload.
In this repository69 other files it gives its agents.
- CLAUDE.mdCLAUDE.md
- debuggingSkill
- frb-build-verificationSkill
- frb-pixel-harnessSkill
- gum-architecture-layersSkill
- gum-bundleSkill
- gum-cliSkill
- gum-cross-platform-unificationSkill
- gum-docs-writingSkill
- gum-file-pathsSkill
- gum-forms-behaviorsSkill
- gum-forms-controlsSkill
- gum-forms-default-visualsSkill
- gum-forms-itemscontrolSkill
- gum-forms-theme-importSkill
- gum-iconsSkill
- gum-issue-creationSkill
- gum-kernsmith-integrationsSkill
- gum-layout-engineSkill
- gum-layoutSkill
- gum-localizationSkill
- gum-monogame-renderingSkill
- gum-monthly-releaseSkill
- gum-project-versioningSkill
- gum-property-assignmentSkill
- gum-raylib-renderingSkill
- gum-releaseSkill
- gum-runtime-animation-chainsSkill
- gum-runtime-bindingSkill
- gum-runtime-fontsSkill
- gum-runtime-syntax-versionSkill
- gum-runtime-systemmanagers-initSkill
- gum-runtime-topologySkill
- gum-runtime-variable-referencesSkill
- gum-samplesSkill
- gum-serviceSkill
- gum-source-linked-projectSkill
- gum-themingSkill
- gum-tool-animationsSkill
- gum-tool-codegenSkill
- gum-tool-copy-pasteSkill
- gum-tool-delete-logicSkill
- gum-tool-dialogsSkill
- gum-tool-errorsSkill
- gum-tool-file-watchSkill
- gum-tool-font-generationSkill
- gum-tool-import-from-gumxSkill
- gum-tool-loggingSkill
- gum-tool-outputSkill
- gum-tool-pluginsSkill
- gum-tool-save-classesSkill
- gum-tool-screenshotsSkill
- gum-tool-selectionSkill
- gum-tool-tree-viewSkill
- gum-tool-undoSkill
- gum-tool-variable-gridSkill
- gum-tool-variable-referencesSkill
- gum-tool-viewmodelsSkill
- gum-unit-testsSkill
- gum-variable-deep-diveSkill
- The first 60 shown.
The file
We split this skill into the rules it gives an agent
3 rules. About 0 are common, 1 is distinctive, and 2 are very specific to this project.
≈0
Common · estimate
Many files like this have a rule of this kind.
≈1
Distinctive · estimate
This author's own choices. Worth a look.
2
Very specific
Tied to their project's names, files or tools. Probably skip.
- Common
- Distinctive
- Very specific
- Very specific: line 66
If a matching design-time child exists, compare its visual's ElementSave.Name against the new BaseType.
- Distinctive: line 67
If a same-named non-design-time child exists, leave it alone (runtime owns that slot).
- Very specific: line 110
Prefer injecting a custom IGumHotReloadManager rather than adding game-specific logic to GumHotReloadManager.
≈ “Common” is an estimate: at least 1 in 5 of the 372,429 skill files we read have a rule of the same kind, not the same words. “Very specific” is our guess from the words: it names a file, a command, a setting or the project itself.
Files
Runtime Hot Reload Reference
What It Is
Hot reload lets a running game pick up changes saved in the Gum tool without restarting. GumService.EnableHotReload(absoluteGumxSourcePath) starts a FileSystemWatcher on the source project directory; file changes trigger a debounced rebuild of GumService.Default.Root's children from freshly loaded save data.
User-facing docs: docs/code/debugging/hot-reload.md. User docs are the source of truth for the public API; keep them in sync when behavior changes.
Key Files
| File | Purpose |
GumCommon/HostServices/GumHotReloadManager.cs | IGumHotReloadManager + GumHotReloadManager; host-specific steps (texture filter, animation load, cache eviction) come in as constructor delegates |
MonoGameGum/GumService.cs, Runtimes/SkiaGum/GumServiceSkiaBase.cs | EnableHotReload, per-frame Update, Uninitialize stop |
docs/code/debugging/hot-reload.md | Public documentation |
Platform Gating
The entire file is wrapped in #if !IOS && !ANDROID. The EnableHotReload method on GumService is likewise gated. The file is shared by every runtime through GumCommon. Any new API surface must respect both gates.
Source vs Bin Paths — Critical Distinction
The watched path is the source .gumx (the file the Gum tool edits), not the bin/Content copy. Two directories matter:
_projectSourcePath/sourceDirectory— where files change, whereFontCache/is read from_binGumDirectory— snapshot ofFileManager.RelativeDirectoryatStart(); where fonts are copied to and where the runtime loads from
During PerformReload, animations are reloaded by enumerating *Animations.ganx under the source directory through a LooseFileGumFileProvider rooted there (via GumService.LoadAnimationsFromProvider). FileManager.RelativeDirectory is not swapped — the provider's root is the source directory. (This replaced an older approach that swapped RelativeDirectory and probed FileManager.FileExists per element.) If you add asset-resolving logic to the reload path, root it at the source directory yourself rather than relying on a global-state swap.
Reload Pipeline
FileSystemWatcher event
→ HandleFileChange filters by extension (.gumx/.gucx/.gusx/.gutx/.fnt/.ganx)
→ sets _pendingReload + _lastChangeTime
→ (.fnt paths also appended to _changedFontFiles under _fontFileLock)
GumService.Update → _hotReloadManager.Update(Root)
→ if _pendingReload && 200ms elapsed since last change → PerformReloadThe 200 ms debounce coalesces the Gum tool's multi-file save burst into one reload. Don't shorten it without testing against a real tool save — partial saves will otherwise rebuild against an inconsistent on-disk state.
PerformReload — What Actually Happens
CopyAndUnloadChangedFonts()— for each changed.fntanywhere in the project (FontCache/or aCustomFontFilefolder), copies it plus the pages it names (and<basename>*.png) to the same relative place under the bin folder, thenLoaderManager.Disposes each under the path the game loads it by. A file already at its destination (Preview, or a build folder under the project) is not copied (CopyUnlessCurrent) but is still evicted. A source.fntwhose bin copy has another write time or length counts as changed even with no watcher event (copies keep the source's write time). A changed.pngthat a neighbouring.fntnames re-queues that font. When any font was evicted,ReapplyFontsruns afterApplyDiffand callsUpdateToFontValues()on every Text, because the diff only touches Text whose font variables changed.GumProjectSave.Load+Initialize; swap intoObjectFinder.Self.GumProjectSave.- Reload animations: enumerate
*Animations.ganxunder the source directory via aLooseFileGumFileProviderand load each throughGumService.LoadAnimationsFromProviderinto the new project (noRelativeDirectoryswap — the provider is rooted at the source dir). ApplyDiff(roots, newProject, SystemManagers.Default)— applies the in-place reconciliation walk described below.- Fire
ReloadCompleted(only when the reload applied), thenReloadFinishedwith aHotReloadResult(every attempt, applied or not). See "Reload Result" below.
ApplyDiff — In-Place Reconciliation Walk
Defined on GumHotReloadManager and exposed public static for direct test use; the four-argument overload takes the old project (PerformReload passes the one the finder held), and tests of "unchanged variable keeps its value" must pass it, since a builder that shares a standard element's default state between projects reads as edited in place. It first runs newProject.ApplyAllVariableReferences(), so a reader of a reference that is itself fed by a reference (control -> Styles.Primary -> Styles.Brand) sees the end of the chain even when only the last file was edited and the files between still hold their saved copies (HotReloadReferenceChainTests). References and base types resolve through ObjectFinder, so ApplyDiff sets ObjectFinder.Self.GumProjectSave to the new project for the call and puts the previous one back in a finally. It then walks every root and, at each visual whose ElementSave.Name matches an element in the new project:
- Re-point
element.ElementSaveto the new project's element. - Structural diff against the new
Instanceslist (DiffDesignTimeChildren). That list already holds every inherited instance: load and reload both runRepairMissingDefinedByBaseInstances(GumProjectSaveExtensionMethods.cs), which copies a base element's instances into each derived element withDefinedByBaseset, so a base edit reaches derived visuals through this same diff (HotReloadInheritedInstanceTests).- Partition the visual's
ContainedElementsplusChildreninto design-time (those withTag is InstanceSave) and everything else (runtime-added or Tag-cleared). Matching must useContainedElements: an instance with aParentvariable (a ListBoxItem inside a ComboBox) is not inChildren, and missing it duplicates the instance on every reload. - For each existing design-time child not present in the new
Instances:Parent = null,ElementGueContainingThis = null,RemoveFromManagers(). - For each new
InstanceSave:- If a matching design-time child exists, compare its visual's
ElementSave.Nameagainst the newBaseType. Mismatch → remove+recreate (retype). Match → refresh theTagto point at the newInstanceSaveinstance. - If a same-named non-design-time child exists, leave it alone (runtime owns that slot). Do not create a duplicate.
- Otherwise call
instance.ToGraphicalUiElement(systemManagers)and attach viaParent = parent+ElementGueContainingThis = parent.
- If a matching design-time child exists, compare its visual's
- Partition the visual's
SetChangedVariablesRecursively(element, newEs, context)— applies the default-state values the project changed, layer by layer down the base types: a variable is set only when its value differs from the old project's (ReloadContext.OldByName, from theoldProjectargument or the visuals' ownElementSaves), the old project has no such variable, or an earlier layer or rebuilt instance in this reload reset it (ReloadContext.Applied/Recreated); every other variable keeps its runtime value (#6980). A layer with no old version, or edited in place, is applied in full.ResetRemovedVariablesruns per layer. Qualified-name variables (MyInstance.X,MyInstance.Parent, etc.) flow into the children byName, which also handles reparenting and animates new instances into position.- Then
ReorderDesignTimeChildrenreorders, per container (the element, or any instance an instance is parented to), only the slots held by this element's own instances (matched byInstanceSavereference againstnewEs.Instances), sonewEs.Instancesorder wins. It runs after variables soParenthas settled. A move inside an ItemsControlInnerPanelrelies on the control syncing its collections (seegum-forms-itemscontrol).
- Then
- Recurse into runtime-added children (no
InstanceSavetag). Design-time instances are recursed into before step 3, at any depth, so an edit to a component's own default state or instances reaches every instance of it, and this element's qualified-name overrides then win over the component's defaults. Standard-element instances are not recursed into. A design-time child is only diffed against the element that owns itsInstanceSave(ParentContainer.Name): a screen instance parented under a component instance sits in that visual'sChildrenbut belongs to the screen.
Reload Result
HotReloadResult / HotReloadIssue / HotReloadIssueKind (GumCommon/HostServices/HotReloadResult.cs) are what ReloadFinished raises, forwarded by GumService.HotReloadFinished. Each place that used to print a problem now adds a HotReloadIssue and prints its Message: the walk adds them to ReloadContext (Report/ReportOnce), and TryLoadProject, HandleFailedReload and TryReload add the rest. A new problem kind is a new enum value plus its MatchesRestart rule, not a bare ReportError.
A stale-forever edit (a component's base type, its exposed variables, a standard element's default) is not applied by the diff: ReportDefinitionChanges / ReportStandardChange list it with MatchesRestart false, and ReloadMemory.BuiltShapes remembers what the visuals were built with (base type, exposed variables) so later reloads keep listing it. Any change of an element's own base type is listed, with no hand-picked comparison of what the bases contain (that kept missing real differences). The one exception is a pure rename (IsPureRename): the old base is gone, the new one is new, and the two serialize to the same text once their names are replaced. An element whose file is missing (MissingElements) only gets the MissingFile issue. Events are raised per subscriber inside try/catch; an attempt that will be retried raises nothing.
Landmine: _reportedProblems is the memory for printing only. It must never filter what goes into a result, or a subscriber misses a state that is still stale. Only PrintIssues reads it.
Non-Obvious Behaviors / Gotchas
Tagis the design-time marker.InstanceSave.ToGraphicalUiElementsetsTag = instanceSave(GumRuntime/InstanceSaveExtensionMethods.GumRuntime.cs:39). If user code nulls or replaces thatTag, the diff treats the visual as runtime-owned: not removed, not retyped, not duplicated. Variable application viaNamestill works. Documented limitation, seedocs/code/debugging/hot-reload.md.- A visual whose element is gone from the new project is kept and reported once.
ApplyDiffRecursiverecords it inReloadContext.Problems(keyedgone:<name>) whenbyNamehas no match and it is not a standard element: a renamed, moved or deleted shown screen (no identity survives a rename), or a code-added component visual. The message says "screen", "component" or "element" byKindOf; screens and components get the same message.ReportProblemssays it throughReportErrorat the end of the walk; the manager's_reportedProblemskeeps it from repeating on every later save and clears it when the element comes back. The public staticApplyDiffhas no memory and reports every time. Edits to the old screen or its replacement do not arrive (the message says so). Tests:HotReloadGoneElementTests. - An instance whose
BaseTypeis no longer in the project is removed. The tool keeps such an instance in the owner's file; a restart cannot build it (InstanceSave.ToGraphicalUiElementreturns null).DiffDesignTimeChildrenchecksObjectFinder.GetElementSave(BaseType)before the retype comparison, which would otherwise match the visual to its own old element name and keep it. A removal is reported once (the next reload finds nothing to remove), and because the instance is gone beforeApplyDiffRecursiverecurses, the "element is gone" report above never fires for it: exactly one message per removal (HotReloadDeletedComponentTests). Contrast: a shown screen or component is kept, an instance of a deleted component is removed. Tests:HotReloadDeletedComponentTests. - The walk stops at instance loops with the build's own guard.
ApplyDiffRecursiveholdsElementSaveExtensions.EnterBuild(newEs)while it walks a visual, so an instance created below it of a component already above it is skipped byIsCircularInstance, exactly as a restart skips it (#7468). Without it each reload grew the tree a level per level walked until the stack overflowed (#7988). The skip is routed into the result asInstanceLoop(ReportCircularInstancesTo) instead of printed separately. Any new path that builds instances during the walk must stay inside that scope. Tests:HotReloadInstanceLoopTests(MonoGame, and Skia throughPerformReload). - Retype detection uses
ElementSave.Name, not the oldTag.BaseType. This is the visual's actual built-from type, which stays stable across diffs whether the caller passed a fresh project or mutated the existing one in place — important for tests. Root.Childrenand any roots passed toUpdate(IEnumerable<GraphicalUiElement>)are the reload surface.PopupRoot/ModalRootare untouched.ApplyDiffrunsRefreshStyles's three passes. It saves Forms runtime properties, applies the diff, then re-applies the categorical states code drove by name (_appliedCategoryStatesonGraphicalUiElement) and runsUpdateState+ApplyRuntimePropertieson each Forms control. A new restore need goes in a control'sSaveRuntimeProperties/ApplyRuntimeProperties, not in the diff. Values set in code on any other visual are left alone unless the project changed that variable (below).- Re-applying a category state puts the containers' values for that instance back (#8108).
ReapplyAppliedCategoryStatesRecursivefollows each state that was applied while the instance had no container yet (a build-time state, not a Highlighted-style runtime state, which keeps beating the container) withReassertContainerOverrides: a build applies the state first and the containing elements' values (a ListBox'sVerticalScrollBarInstance.Height, a screen'sBox.VerticalScrollBarInstance.Height) after it, so a re-applied state (the ScrollBar'sOrientationCategoryState= Vertical, 128 px Absolute) must not leave its own values on top. Tests:ThemedScrollBarHotReloadTests. - Forms-property variables (
BehaviorFormsPropertyApplier) follow the same rule as other variables: the project wins when it changed the value, code-set values stay otherwise (#6980).ApplyDiffcallsReapplyChangedFormsPropertiesRecursivebefore the restore pass;ReapplyChangedwrites only properties whose effective value (instance override, then component default) differs between the old and new element. A removed value returns to the behavior default, else to what the control held when it was created (SnapshotInitialValues). Without this the build-time write recorded as code-assigned (TextBox.Placeholder) won over the edit (#7470). - A visual keeps the
StateSave/category objects it was created with (Categories/Statesdictionaries).RefreshStatesAndCategoriesre-points them at the new element whenApplyDiffswapsElementSave; without it the first state change after a reload applies the pre-edit state values. - Children added with no
Tag(or with aTagthat isn't anInstanceSave) are runtime-owned and preserved. This includes ItemsControl-generated rows and anything the user constructed programmatically. - Reparenting flows through the qualified
<instance>.Parentvariable — there is no explicit reparent step in the diff. The parent state'sFoo.Parent = "Bar"line is what re-attachesFoounderBarduringSetVariablesRecursively. This is why both old and new parent visuals must exist before that step runs. - A variable the file stops setting is reset, not left alone.
ResetRemovedVariablesinGumHotReloadManager.cscompares the old and new default-state save objects (never the visuals, so values assigned in code are untouched) and restores each dropped variable's default fromGetValueRecursive. "Dropped" includes a variable still present withSetsValuebut no value, which is how the tool saves a detachedFoo.Parent. A droppedFoo.Parentis detached directly, becauseSetProperty("Parent", "")is a no-op. A dropped categorized-state assignment is not undone. A project edited in place has no old state to compare, so tests of this must build a second project object (HotReloadRemovedVariableTests). - A variable a reference row wrote is applied from the file again, whatever the old file held. The live value came from the row, not the file, so an unchanged stored value would otherwise keep it after the row is removed, retargeted or becomes part of a loop (a restart skips looped rows and shows the stored value, #6871).
GetRowTargets(LoadOrderRowsof the old state) feedsCreateChangedStateandResetRemovedVariables; tests:PreviewAccuracy2CircularReferenceTests.cs(classPreviewAccuracy2Tests). - A project that cannot be read skips the reload.
PerformReloadloads the whole project into a temporary viaGumProjectSave.Load(path, out result)before touchingObjectFinderor the tree. A parse error, locked file or empty file (ErrorMessage, or a thrown deserialize exception) retries once after the debounce (_failedAttempts, reset by any newNotifyFileChanged), then reports once throughElementSaveExtensions.ReportPropertyAssignmentErrorand leaves everything unchanged.MissingFilesalone (git checkout) is reported and the rest reloads. A throw after the load (ApplyDiff) restores the finder and is reported, but cannot roll the tree back. Tests:HotReloadUnreadableFileTests. .ganxis only re-read by enumerating the source directory into the new project'sElementAnimations(viaGumService.LoadAnimationsFromProvider). A non-Gum file goes to_changedOtherFilesand is matched againstGraphicalUiElement.AssignedSourceFile(recorded inSetProperty("SourceFile"), because the visual keeps only the texture)..achx/.achjedits evict the cache entry, copy source to bin if they differ, and assignSourceFileagain; chains are reassigned only whileIAnimationChainRenderable.AnimationChainListis still the cached list (code-assigned chains are left alone), and a playing chain the new file lacks is reported asReloadFailed. A changed image a visual showed before the reload (or a frame image its chain file names, found withChainTexturePaths) is reported asReloadFailed, never applied, and stays in_staleImagesso every later result lists it.- Shader files are matched by reference, not extension (#7034). A changed file that is not a Gum/font file goes into
_changedOtherFiles; after the debounceReassignShaderFileswalks the roots and, for each container whose recordedShaderParameterVariables.GetShaderFileresolves to that file, evicts the cached effect and re-setsSourceShaderFile. No reload or rebuild.#included files count too: the MonoGame/KNI/FNA and Skia ShadowDusk loaders record each compile's included files (also a failed one) inShaderIncludeTracker(GumCommon) through the linkedReportingIncludeResolver, andReassignShaderFilesmatches a changed file against both the shader and its recorded includes. Not tracked: raylib, Slangimport, extensionless includes (the watcher ignores them). - A changed
.ttf/.otfis reported, not applied. Which generated fonts came from it is unknown here, soReportChangedFontSourcesqueues aFontSourceChangedissue (MatchesRestartfalse) that rides the next result, or is raised alone when no reload is pending. - Copying a font can make the file watcher report the source file as changed (seen on macOS). A change event for a font whose load-folder copy has the same length and write time is the manager's own copy and is dropped (
IsCopyCurrent; copies keep the source's write time), and a copy that is a no-op evicts nothing. Events inside a load folder nested under the project folder are ignored, and so is that folder in the rescan._changedFontFilesis a set, a reload copies at mostMaxFontsPerReloadfonts, and afterMaxFontOnlyReloadsreloads asked for by fonts alone the manager reports oneReloadFailedand ignores font events until a project file changes. A failed font copy is reported once, retried by the next reload, then dropped. A queued font that is gone and has no load-folder copy (an editor's hidden temp file) is dropped without a report, and hidden or~names are never queued. - Localization files are reloaded, but not through the extension list. A changed file that is not a Gum file goes to
_changedOtherFiles; after the debounceUpdaterunsPerformReload(roots, otherFiles)(project also changed) orPerformFileReload(alone).ReloadLocalizationreplaces the database when the new project'sLocalizationFileslist differs from the old one orProjectLocalizationLoader.IsLocalizationFilematches a changed file, thenRefreshLocalizationre-translates and lays out the roots. The service comes from the host throughLocalizationServiceProvider(a static onCustomSetPropertyOnRenderable, unreachable from GumCommon); a manager built without it skips localization. An unreadable file is retried once (_failedFileAttempts), then reported;PerformFileReloadcatches everything becauseUpdateruns on the game thread. _changedFontFilesis mutated off the game thread (watcher callback). It's protected by_fontFileLock; any new shared state added must be similarly synchronized.Stop()is idempotent-safe but does not reset other state —GumService.Uninitializejust nulls the manager reference afterward.- Font cache path is built with
FileManager.Standardize(..., preserveCase: true, makeAbsolute: true). The loader's cache keys are case-preserving absolute paths; any eviction added must match that exact shape or it will silently miss.
Extending
- For new watched extensions: add to
HandleFileChange's extension check. If the asset type has a cache, add eviction toPerformReload(follow the font pattern — copy source→bin, thenLoaderManager.Disposethe standardized path). - Prefer injecting a custom
IGumHotReloadManagerrather than adding game-specific logic toGumHotReloadManager. (CurrentlyEnableHotReloadhardcodesnew GumHotReloadManager()— if a test/custom manager seam is needed, add an overload accepting anIGumHotReloadManager.) - Subscribe to
ReloadCompletedfrom game code to reapply runtime state after a rebuild, or toReloadFinishedto react to what the reload could not do. Tool/GumPreviewis the in-repo example: onMatchesRestart == falseit rebuilds the shown element from the project the reload loaded (PreviewReloadPolicy, once per reload that reports MatchesRestart == false, and after every finished reload while the tool has a state selected: Preview applies that state itself, a reload only compares default states, so a value a removed, deleted or renamed state set would stay;PreviewSelectedStateReloadTests). Rely onMatchesRestart, never on specific issue kinds.
Does it work?
Reviews from people and from AI agents that ran it: what they used it for, and whether it worked.
No reviews yet
People and AI agents can review whether this works in practice. Say what you used it for, and whether it worked.
- It worked
- Partly
- It didn't
Using an agent? It can post a review for you after it has run the file: the MCP tool registry_write, action report. How to connect one.
Your trail
Files you open will collect here, so you can find them again.
Open two or more, and you can remix the rules you like from each into one list. Kept in this browser only.
Now do this for your own.
Bring your CLAUDE.md, AGENTS.md or skills. agentleFS shows which of your rules are common, which are yours and which only fit one project, and keeps one version your agents read everywhere.

