Saving and Loading
This page follows a save from the moment the player presses Save to the moment a slot brings the game back. It goes one level below Architecture: which function runs, in what order, what lands in the browser’s storage and under which key, and what each action must do so that what it showed comes back. State, Storage and Rollback describes the three stores a save is made of; read it first.
What it’s for
A save is a copy of the engine’s three stores (state(), history() and storage()), plus a name, a date, an image for the thumbnail and, when Screenshots is on, the key of a screenshot. It goes into a storage space: an Artemis Space (or, for desktop builds, a FileSystemStorage) that the engine keeps in monogatari.Storage. The same space holds the player’s preferences under the key Settings.
Loading does the opposite, in three moves: it resets the game, writes the saved stores back, and asks every action to draw again what the state says it was showing (its onLoad() hook). Then whoever started the load runs the saved statement, and the game goes on from there.
This subsystem sits between the save and load screens (Components and Screens) and the stores (State, Storage and Rollback). Every action that shows something takes part in it, through reset() and onLoad() (Statements and Actions).
The files
| File | What it does | Cypress specs |
|---|---|---|
src/engine/persistence.ts |
gameObject(), saveTo(), nextAutoSaveSlot() and autoSave(), resetGame(), upgrade(), storageName(), setupStorage(), openStorage(), loadFromSlot() (with the v1 save format conversion) |
components/save-screen.spec.js, components/load-screen.spec.js, components/save-screen-screenshots.spec.js, storage.spec.js, autosave.spec.js, actions/end.spec.js |
src/migrations/index.ts |
migrate(): runs every engine migration, in order, on every save that is loaded |
none directly; the load tests in the action specs load saves through it |
src/migrations/20200310-add-pause-state-to-media-state.ts |
Turns media state entries saved as strings into { statement, paused } |
none |
src/migrations/20211223-add-previous-statement-to-show-history.ts |
Turns character history entries saved as strings into { statement, previous } |
none |
src/monogatari.ts |
The Storage property, the three screenshot callbacks, preference()/preferences() (they write Settings), setup() (opens the storage with openStorage(), reads Settings, records storageStructure), init() (sets up storage when nothing did, starts the autosave timer), onLoad() (runs every action’s onLoad() by loadingOrder), and the public wrappers of the functions in persistence.ts |
main_menu_after_load.spec.js |
src/engine/ui.ts |
showScreen() takes the screenshot when the save screen opens; captureGameScreenshot() |
components/save-screen-screenshots.spec.js |
src/engine/assets.ts |
screenshotSpace(): the IndexedDB space the default screenshot callbacks use |
components/save-screen-screenshots.spec.js |
src/lib/FileSystemStorage.ts |
A storage space that sends every operation to a desktop host and waits up to 5 seconds for its answer, then falls back to IndexedDB; runs the upgrades when it opens | none |
dist/engine/desktop/storage.js |
The desktop hosts’ side of FileSystem: one JSON file per key, in the app’s data folder |
none |
src/lib/DesktopBridge.ts |
getDesktopBridge(): window.electron, else window.electrobun, else null |
none |
src/components/save-screen/index.ts |
The name field, the save listener |
components/save-screen.spec.js |
src/components/load-screen/index.ts |
A slot container for saves, and one for autosaves when AutoSave is on |
components/load-screen.spec.js |
src/components/slot-container/index.ts |
Lists the slots of one label; loads a slot, or asks to overwrite it; follows the space’s create, update and delete callbacks | components/save-screen.spec.js, components/load-screen.spec.js |
src/components/save-slot/index.ts |
One slot: reads it, shows its thumbnail, name and date; the delete button and the delete-slot listener |
components/save-screen.spec.js, components/load-screen.spec.js, components/save-screen-screenshots.spec.js |
src/actions/Scene.ts, ShowBackground.ts, ShowImage.ts, ShowCharacter.ts, ShowCharacterLayer.ts, Play.ts, Video.ts, Canvas.ts, Particles.ts, HideTextBox.ts |
The actions with an onLoad(): each one replays the statements its state key recorded |
the “after load” tests in actions/show_scene.spec.js, show_image.spec.js, show_character.spec.js, play.spec.js, pause.spec.js, show_video.spec.js, show_canvas.spec.js, dialog.spec.js, conditionals.spec.js |
src/lib/types/index.ts, src/lib/types/Monogatari.ts |
SaveGameData, LegacySaveData, SaveSlot, StorageInterface |
none |
cypress/support/commands.js |
cy.save(slot) (saveTo('SaveLabel', slot)), cy.load(slot) (loadFromSlot('Save_' + slot), then run the statement), cy.clearStorage() |
all of the above |
How it works
Setting up the storage space
monogatari.Storage starts as new Space(): a LocalStorage space with no name. setupStorage() in persistence.ts replaces it with the one the settings describe. It runs once, from whichever of these comes first:
preferences(object), when the space has no name yet. The starter’sjs/options.jscallsmonogatari.preferences({...})right aftermonogatari.settings({...}), so in a game made from the starter, storage is set up insideoptions.js, beforestorage.js,script.jsandmain.jsrun.init(), when the space still has no name.
setupStorage() reads three settings at that moment and never again: Name (made into a slug by storageName(), which uses Artemis Text.friendly(), so My Visual Novel becomes my-visual-novel; a name with no Latin letters or digits keeps its own letters, 物語, and one made only of symbols is named after their code points), Version, and Storage (Adapter, Store, Endpoint). Then it:
- picks the adapter from
Storage.Adapter; - asks the browser to keep the data (
navigator.storage.persist()), except in desktop apps and Cordova, and logs a warning when the browser says no; - builds the space:
new Space(adapter, { name, version, store, endpoint, props }), unless the adapter wasFileSystemand a desktop bridge exists. An IndexedDB space whoseVersionreads as less than 1 (0.0.0, empty) is opened at version 1, the lowest IndexedDB accepts; - hands every upgrade registered with
monogatari.upgrade()to the space (see Migrating saves).
It doesn’t open the space. The first operation does, and setup() makes that openStorage(), before it reads Settings. By then js/main.js has set the debug level, so its dialogs show. openStorage():
- shows
engine:storage:filesystem_no_bridgewhenAdapterisFileSystemand there was no bridge; - with IndexedDB, shows
engine:storage:invalid_versionfor aVersionbelow 1, and opens the space. When the open fails and the database already exists at a higher version (Versionwent down), it opens the space at that version (adapter.numericVersion) and showsengine:storage:version_lowered. When the database doesn’t have theStore(it changed after release) and has one store, it goes on with that store and showsengine:storage:store_not_found; - with LocalStorage, copies the unprefixed keys a 2.8.1 game with a non-Latin
Namewrote (see below), and when keys of a higher version exist, configures the space with that version and showsengine:storage:version_lowered; - shows
engine:storage:upgrade_failedwhen a game’s upgrade threw, andengine:storage:open_failedfor any other failure.
An IndexedDB connection stays open for as long as the page is, and a newer Version opened in another tab or window can only upgrade the database once every other connection is closed. openStorage() handles both sides of that, with the bar at the top of the game that also announces new content ([data-ui="broadcast"]):
- The older tab. Once its space is open, a
versionchangelistener on theIDBDatabasecloses the connection and shows theStorageUpdatedstring, asking the player to reload; a click on the bar reloads. That tab’s engine can’t write into the upgraded database anyway. - The newer tab. A tab with an engine from before 2.9.0 has no such listener, so the newer tab’s open is
blockeduntil it closes. Artemis’s adapter makes its open request itself, sowatchBlockedOpen()wrapsindexedDB.openfor the space’s database name whilespace.open()runs, shows theStorageBlockedstring when the request is blocked, and removes it when it succeeds.
cypress/e2e/storage.spec.js covers both, holding a connection from the spec as the other tab would.
The recovery keeps the players’ saves: a lowered Version or a changed Store makes the game go on with the data it has, and the dialog tells the developer what to change back. The database a version check reads is opened without a version, and its upgradeneeded aborts, so a check never creates one.
Where the data ends up depends on the adapter. The keys below are the ones the starter game produces with Name: 'My Visual Novel', Version: '0.1.0' and Store: 'GameData':
Storage.Adapter |
Where | What a key looks like | When Version changes |
|---|---|---|---|
LocalStorage (the engine’s default) |
window.localStorage |
my-visual-novel::GameData::0.1.0_Save_1795891427822 |
On the first read, every key of the older version is copied to the new prefix and the old one removed; upgrades run after the copy |
SessionStorage |
window.sessionStorage |
The same as LocalStorage | Nothing is copied; upgrade() logs a warning and does nothing |
IndexedDB (what dist/js/options.js sets) |
A database named my-visual-novel, opened at version 100000000 (0.1.0 as a number), object store GameData with keyPath: 'id' |
A record { ...value, id: 'Save_1795891428792' } |
The same database is opened at the higher version; the records stay. Upgrades run inside the version change |
RemoteStorage |
An HTTP API at <Endpoint>/<Store>/ |
POST/PUT/GET/DELETE <Endpoint>/GameData/Save_1 |
The client can’t upgrade; upgrade() rejects |
FileSystem |
A desktop host, through window.electron or window.electrobun. The starter’s hosts write <app data folder>/Storage/my-visual-novel/GameData/ |
A file per key: Save_1795905110677.json, Settings.json |
On the first operation, the upgrades from the version in the __monogatari_storage_version__ entry to the new one run once, in order, and the entry takes the new version |
| Anything else | IndexedDB | As IndexedDB, without the id key path |
As IndexedDB |
The adapters come from Artemis 0.6 (node_modules/@aegis-framework/artemis, its Space and SpaceAdapter/*). The version number is versionToNumber() from Artemis: the first three parts of the version times 10¹², 10⁸ and 10⁴. A LocalStorage key prefix is <name>::<store>::<version>_ when all three are set.
FileSystem wraps the bridge in a FileSystemStorage. Every operation sends a message on a monogatari:storage-* channel (get, set, update, remove, get-all, keys, contains, clear) with a requestId, the storage’s name and store, and waits for a monogatari:storage-response carrying the same requestId and either data or error. The hosts answer with dist/engine/desktop/storage.js (Electron’s main process listens on each channel; Electrobun’s view script forwards them as one storage-request RPC request). When an answer takes more than 5 seconds, as with a host from before 2.9.0, the storage shows engine:storage:filesystem_no_answer once and sends every operation, that one included, to an IndexedDB space with the same name instead. With no bridge, the engine falls back to IndexedDB, and openStorage() shows engine:storage:filesystem_no_bridge. Before 2.9.0 setupStorage() showed it, while js/options.js ran with the debug level still at 0, so it never appeared in a game made from the starter.
A Name with no Latin letters or digits gave 2.8.1 an empty slug. IndexedDB refused to open without a name, and LocalStorage kept the keys with no prefix (Settings, Save_1, the way v1.4.1 and an empty Adapter do). The first time such a game opens in 2.9.0 with LocalStorage, openStorage() copies Settings and the <SaveLabel>_<n> and <AutoSaveLabel>_<n> keys into the named space, when it has no Settings yet, and leaves the originals.
The player’s preferences: the Settings key
Preferences (language, volumes, text speed, auto-play speed) are not part of any save. They live under their own key, Settings, in the same space:
setup()readsStorage.get('Settings')before it registers any component, and merges what it finds into the defaults. When the key is missing (the first time the game opens), it sets the global_first_runand writes the defaults. A multi-language game with the language selection screen waits instead, and writesSettingsonce the player picks a language (thedidLocalizelistener ininit()).preference(key, value)changes one preference and callsStorage.update('Settings', preferences)right away. The settings screen changes preferences through it.preferences(object, true)merges and writes;preferences(object)withouttrueonly merges.
setup() also records storageStructure: JSON.stringify(monogatari.storage()) at that moment, which is the storage js/storage.js declared. resetGame() uses it to start a new game.
Saving: saveTo()
saveTo(prefix = 'SaveLabel', id = null, name = null) builds one slot and writes it:
- It returns
undefinedand writes nothing unless the globalplayingistrue. - It takes the date with Luxon (
DateTime.now().toISO(), with the time zone offset) and a timestamp in milliseconds. gameObject()collects{ history, state, storage }: the engine’s live objects, which the adapter serializes when it writes.- An empty
namebecomes the date and time as the player reads it (DATETIME_MED_WITH_SECONDS, like the save screen’s default name).save-slotshows a 2.8.1 slot whose name is its ISO date the same way. - The thumbnail
imageis the third word ofstate.background(show background forest with fadeIngivesforest), or ofstate.scenewhen there is no background. - The key is
`${setting(prefix)}_${id || timestamp}`.prefixis the name of a setting ('SaveLabel'or'AutoSaveLabel'), not the label itself:saveTo('Save')throws “Tried to access non existent setting”. - When
Screenshotsis on and the game screen is hidden, it uses the screenshotshowScreen('save')captured before it hid the game screen (_pendingScreenshot), without using it up: every save made in that visit to the save screen, autosaves included, gets it, andshowScreen()drops it when the player opens another screen. When the game screen shows (an autosave during play, a call from code), it captures it now. It passes the JPEGBlobtoonSaveScreenshot(slotKey, blob)and records the key it returns. A failure is a debug warning; the slot is written without a screenshot. - It writes the slot with
Storage.set(key, data)and returns what the space returns,{ key, value }.
The default onSaveScreenshot stores the blob in a second space: an IndexedDB database named <name>_Screenshots, store screenshots, under the key <slot key>__screenshot. This database exists whatever the main adapter is. onLoadScreenshot(key) turns the blob back into a data URL for the slot’s thumbnail, and onDeleteScreenshot(key) removes it when the slot is deleted.
Four things call saveTo():
| Caller | Call | Key |
|---|---|---|
The Save button (the save listener in save-screen) |
saveTo('SaveLabel', null, name), only when the name field isn’t empty |
Save_<timestamp> |
Overwriting a slot (the overwrite-slot listener in slot-container) |
saveTo('SaveLabel', overwrite_slot, name) |
The same Save_<id> |
| The autosave timer | saveTo('AutoSaveLabel', id) |
AutoSave_1 to AutoSave_<Slots> |
Game code, and cy.save(n) in the specs |
saveTo('SaveLabel', n) |
Save_<n> |
Once Storage.set() has written the slot, saveTo() calls runSaveHooks(): every action’s and every component’s static onSave({ key, value }), all at once, with the slot’s storage key and what was saved. A hook that throws is logged with the action’s id or the component’s tag and doesn’t undo the save. Before 2.9.0 nothing called onSave(), although the base classes said it ran on every save.
Autosave
init() starts the autosave timer when AutoSave is a number other than 0: a setInterval of AutoSave × 60000 milliseconds, kept in the global _auto_save_interval. Each tick calls autoSave(), which does nothing unless the global playing is true (the main menu uses up no slot). It asks nextAutoSaveSlot() for the slot, saves to AutoSave_<slot>, and sets the global current_auto_save_slot to the slot the next autosave will use. Slots limits only these: manual saves have no limit.
nextAutoSaveSlot() reads AutoSave_1 to AutoSave_<Slots> from the storage and returns the first one that’s missing, or else the one whose date is the oldest. Reading the storage each time keeps the order across page loads and after the player deletes a slot. Before 2.9.0 a counter in memory did this: it started at 1 on every page load and moved on at every tick, saved or not.
When AutoSave is 0, init() hides [data-screen="load"] [data-ui="autoSaveSlots"], and load-screen doesn’t render the autosave container at all.
The slot screens
slot-container has two props, label (Save or AutoSave, from the settings) and type (save or load):
willMount()goes through every key of the space (Storage.each()), keeps the ones that start with<label>_, don’t contain__screenshotand hold an object, and sorts them by the number after the label. Manual slots are numbered by timestamp, so they appear oldest first.didMount()follows the space:onCreateadds a key (through aSet, so overwriting a slot doesn’t add a second one),onUpdatepasses the new value to the slot,onDeleteremoves it. Artemis callsonCreatefor everyset(), an overwrite included.- In a
loadcontainer, a click on a slot (outside its delete button) runsloadFromSlot(slot)and thenrun(label()[state('step')]). In asavecontainer, a click asks to overwrite (theslot-overwritealert, with an editable name).
save-slot reads its slot in willMount(). It turns a v1 slot’s Name, Date and Engine.Scene into the current fields, and asks onLoadScreenshot() for the screenshot. Its thumbnail is the screenshot when there is one; otherwise the scene asset named by image; otherwise the background or scene statement of the saved state, used as a CSS background (that’s how show scene #335577 gives a colored thumbnail). The delete button stores the key in the global delete_slot and asks to confirm; the delete-slot listener deletes the screenshot, then the slot.
Loading: loadFromSlot()
loadFromSlot(slot) takes the full key ('Save_1', not 1) and returns a promise that resolves once the game screen shows. It does not run the saved statement: its callers do.
In order:
- Read and check.
Storage.get(slot), then the label the save was made at (Engine.Labelfor a v1 save,game.state.labelfor the others) must be a label of the script. When the key is missing, the value isn’t an object, or the label is gone, it showsengine:storage:slot_not_foundorengine:storage:slot_label_not_found, puts the cursor back and rejects, before anything changes.slot-containercatches that rejection. Only then does it setplayingand firewillLoadGame. - Reset.
resetGame()turns auto-play off (and skip, whenSkipis above0), replaces the storage withstorageStructure, setsstepto0andlabelto theLabelsetting, clears the deprecatedblockglobal, empties every history array, and calls every action’s staticreset()and every component’sonReset(). The state keys of actions are not touched here: each action’sreset()puts its own key back to empty (ShowImage.reset()removes the images and setsimages: []). - Convert or migrate. A save with an
Engineproperty comes from v1.4.1 or earlier: itsEngine.Step,Label,Scene,Song,Sound,Particles, theShowlist and the*Historyarrays become the current state and history, withimg/paths turned intoassets/. Any other save goes throughmigrate(data.game), and itsstate,historyandstorageare written back withstate(),history()andstorage().state()andstorage()merge deeply (arrays are replaced, objects merged);history()replaces each history array. - Clamp the step. When the saved step is past the end of the label (the script got shorter since the save was made), the step becomes the label’s last statement.
- Redraw.
engine.onLoad()sets the global_restoring_state, groups the actions byloadingOrder, and runs the groups one after another; inside a group, theonLoad()hooks run at the same time. The components’onLoad()hooks run alongside the action groups.ScenehasloadingOrder = -2, so the scene is drawn before anything is placed on it;ShowCharacterLayerhas1, so the characters exist before their layers are added; the others have0. - Show.
showScreen('game'), the cursor goes back toauto, anddidLoadGamefires. - Run. The caller runs the statement at the saved step. In a browser, the events come in this order:
willLoadGame,didLoadGame, thenwillRunActionanddidRunActionfor the saved statement.
The saved step is the statement the game was waiting on when the slot was written, usually a line of dialog or a choice. Running it again shows that line, so the player sees what they saw when they saved.
What an action does in onLoad() follows one pattern: read the statements its state key recorded, build each with prepareAction(), and run willApply(), apply() and didApply({ updateHistory: false, updateState: false }). The two false flags stop the replay from recording the statement a second time.
| Action | State key it replays | loadingOrder |
|---|---|---|
Scene |
scene (and it rebuilds sceneState from sceneElements when the two histories differ in length) |
-2 |
ShowBackground |
background |
0 |
ShowCharacter |
characters |
0 |
ShowImage |
images |
0 |
Play |
music, sound, voice (one entry per track name; the entries saved with paused: true are created paused) |
0 |
Video |
videos |
0 |
Canvas |
canvas |
0 |
Particles |
particles |
0 |
HideTextBox |
textboxHidden (hides the text box when it is true) |
0 |
ShowCharacterLayer |
characterLayers |
1 |
Migrating saves
Two mechanisms change saved data, for two different owners.
Engine migrations (src/migrations/) fix saves written by older engine versions. migrate() passes the game object of every loaded save (v2 format) through each function in the migrations array, in order, and the load uses what comes out. They run on every load of every save, so each one must leave alone a save that is already in the new shape. The two that exist turn strings into objects and pass objects through.
Game upgrades (monogatari.upgrade(oldVersion, newVersion, { storage, replaceStorage })) change a game’s saved data when the game’s Version changes. upgrade() records the callbacks in _upgrade['<old>::<new>']. setupStorage() registers each recorded one with the space (registerUpgrade()), and upgrade() registers its own at once when the space is already set up and not open yet, so a call from js/script.js or js/main.js still counts. Called after the space opened, it shows engine:storage:upgrade_too_late.
The space runs a registered upgrade while it opens, when it finds data from the older version:
- LocalStorage runs it after the keys have been copied to the new prefix, with the space already usable: the upgrade reads every key with
getAll()(the saves andSettings), awaitsstorage(oldData), withreplaceStorage: trueremoves every key the result doesn’t have, and writes every key of the result withset(). A rejection rolls the copy back, and the space throws. - IndexedDB runs it inside
onupgradeneeded, where the space can’t be read:getAll()would wait for the open that is waiting for the upgrade.upgradeIndexedDB()uses the version change transaction instead: a cursor reads every record (theidkey path removed),storage(oldData)runs synchronously, anddelete()andput()write the result in the same transaction. A function that throws, returns a promise or a value IndexedDB can’t keep aborts the transaction: the database keeps its version and its data, the open fails, andopenStorage()showsengine:storage:upgrade_failedwith the error.
The data
A save slot, as saveTo() writes it (the object has no declared type; SaveSlotData in save-slot reads the same fields). This one comes from the starter game with LocalStorage, on the second line of a label:
{
"name": "Probe slot",
"date": "2026-11-28T12:43:47.822-06:00",
"image": "#335577",
"game": {
"history": { "label": [], "music": [], "scene": ["show scene #335577 with fadeIn"], "background": ["show background #335577 with fadeIn"], "sceneElements": [[]], "sceneState": [{ "characters": [], "images": [], "textBoxMode": "adv" }], "character": [], "jump": [], "…": [] },
"state": { "step": 1, "label": "Start", "scene": "show scene #335577 with fadeIn", "background": "show background #335577 with fadeIn", "images": [], "music": [], "textboxHidden": false, "…": "…" },
"storage": { "player": { "name": "" } }
},
"screenshot": "Save_1795891427822__screenshot"
}With IndexedDB the record also carries "id": "Save_1795891427822", its key path.
The game part, from src/lib/types/index.ts:
export interface SaveGameData {
state: Record<string, unknown>;
history: Record<string, unknown[]>;
storage: Record<string, unknown>;
}A v1.4.1 save, as loadFromSlot() reads it (from LegacySaveData, the nested part):
export interface LegacySaveData {
Engine?: {
Step: number;
Label: string;
Scene: string;
Song?: string;
Sound?: string;
Particles?: string;
MusicHistory: string[];
SoundHistory: string[];
ImageHistory: string[];
CharacterHistory: string[];
SceneHistory: string[];
SceneElementsHistory: string[][];
ParticlesHistory: string[];
};
Show?: string;
Storage?: Record<string, unknown>;
game?: SaveGameData;
}What every storage space offers the engine, from src/lib/types/Monogatari.ts (Artemis Space and FileSystemStorage both satisfy it):
export interface StorageInterface {
get(key: string): Promise<unknown>;
set(key: string, value: unknown): Promise<unknown>;
update(key: string, value: unknown): Promise<unknown>;
remove(key: string): Promise<void>;
getAll(): Promise<Record<string, unknown>>;
each(callback: (key: string, value: unknown) => unknown): Promise<unknown[]>;
clear(): Promise<void>;
key(index: number, full?: boolean): Promise<string>;
keys(full?: boolean): Promise<string[]>;
contains(key: string): Promise<void>;
open(): Promise<unknown>;
configuration(object?: Record<string, unknown> | null): Record<string, unknown> | undefined;
rename(name: string): Promise<void>;
upgrade(oldVersion: string, newVersion: string, callback: (...args: unknown[]) => Promise<void>): Promise<unknown>;
onCreate(callback: (key: string, value: unknown) => void): void;
onUpdate(callback: (key: string, value: unknown) => void): void;
onDelete(callback: (key: string, value: unknown) => void): void;
addTransformation(transformation: { id: string; get?: ((key: string, value: unknown) => unknown) | null; set?: ((key: string, value: unknown) => unknown) | null }): void;
removeTransformation(id: string): void;
}The settings this subsystem reads, from GameSettings in src/lib/types/GameSettings.ts:
Name: string; // part of every key: changing it after release orphans every save
Version: string; // part of every key; a change triggers the upgrades
Slots: number; // autosave slots only
SaveLabel: string; // 'Save'
AutoSaveLabel: string; // 'AutoSave'
AutoSave: number; // minutes; 0 turns autosave off
Storage: {
Adapter: string; // 'LocalStorage' | 'SessionStorage' | 'IndexedDB' | 'RemoteStorage' | 'FileSystem'
Store: string;
Endpoint: string;
}
Screenshots: boolean;The engine’s defaults are LocalStorage and Screenshots: false; the starter’s js/options.js sets IndexedDB and Screenshots: true.
The two hooks and the upgrade record, from src/lib/types/index.ts and src/monogatari.ts:
export interface SaveSlot {
key: string;
value: Record<string, unknown>;
}
static _upgrade: Record<string, { storage?: (oldData: unknown) => unknown; replaceStorage?: boolean }> = {};
static onSaveScreenshot: (slotKey: string, blob: Blob) => Promise<string>;
static onLoadScreenshot: (key: string) => Promise<string>;
static onDeleteScreenshot: (key: string) => Promise<void>;Rules and why
- A save holds the stores, never the screen.
loadFromSlot()knows onlystate,historyandstorage. Anything an action shows must be recorded in its state key, put back to empty inreset(), and drawn again inonLoad(). An action that skips one of the three either loses what it showed or shows it twice (Exercise 2 shows both). onLoad()replays without recording. The replay passes{ updateHistory: false, updateState: false }todidApply(); the state was already written back by the load.loadFromSlot()doesn’t run the saved statement. Every caller runslabel()[state('step')]afterwards, asslot-containerandcy.load()do (Exercise 1).- Storage is set up once and opened once.
Name,VersionandStoragemust be set before the firstpreferences()call (in the starter, in thesettings()call at the top ofjs/options.js): a later change has no effect.monogatari.upgrade()must be called before the space opens, which issetup()ininit()unless game code used the storage earlier. NameandVersionare part of every key. Renaming a released game hides every save made under the old name. AVersionchange moves LocalStorage keys automatically; it is the time for upgrades.- Engine migrations must be idempotent. They run on every load, on saves of every age.
- A slot key is
<label>_<number>.slot-containerparses the part after the label as a number to sort the slots, and treats any key that contains__screenshotas something else. A custom screenshot callback should keep that suffix. - Preferences are not part of a save. They belong to the player, not to a game in progress: loading a slot never changes the volume or the language.
How to make the common changes
Make a new action come back after a load
Record the statement in its state key from didApply(), empty the key in reset(), and replay it in onLoad(). This is the shape ShowImage uses:
static override async reset(): Promise<void> {
this.engine.element().find('[data-screen="game"] [data-stamp]').remove();
this.engine.state({ stamps: [] });
}
static override async onLoad(): Promise<void> {
for (const statement of this.engine.state('stamps') as string[]) {
const action = this.engine.prepareAction(statement, { cycle: 'Application' });
if (action !== null) {
await action.willApply();
await action.apply();
await action.didApply({ updateHistory: false, updateState: false });
}
}
}
override async didApply({ updateHistory = true, updateState = true } = {}): Promise<ActionApplyResult> {
if (updateHistory === true) {
this.engine.history('stamp').push(this._statement as string);
}
if (updateState === true) {
this.engine.state({ stamps: [...(this.engine.state('stamps') as string[]), this._statement as string] });
}
return { advance: true };
}Declare the key in StateMap (and the history in HistoryMap) in src/lib/types/index.ts, and set its initial value in the action’s setup(). If the action must draw after another one, give it a loadingOrder (lower runs first). Its rollback side, revert(), is in State, Storage and Rollback.
Change the shape of saved data
Add a migration file to src/migrations/, named <YYYYMMDD>-<what-it-does>.ts, whose default export takes the game object and returns it:
import type { SaveGameData } from '../lib/types';
const RenameSomething = (save: SaveGameData): SaveGameData => {
const { state } = save;
if (typeof state.oldName !== 'undefined') {
state.newName = state.oldName;
delete state.oldName;
}
return save;
};
export default RenameSomething;Then add it at the end of the MIGRATIONS array in src/migrations/index.ts. Write it so that a save already in the new shape goes through unchanged. Exercise 3 does this end to end.
Migrate a game’s saves between versions
This is for game developers, but maintainers get asked about it. In any of the game’s files, outside the function given to monogatari.init(), with the new Version in monogatari.settings({...}):
monogatari.upgrade('1.0.0', '1.1.0', {
storage: (data) => {
const renamed = {};
for (const [key, value] of Object.entries(data)) {
if (key.indexOf('Save_') === 0) {
renamed[key] = { ...value, name: `${value.name} (from 1.0.0)` };
} else {
renamed[key] = value;
}
}
return renamed;
},
});data holds every key of the space: the saves and Settings. This was run with the LocalStorage and the IndexedDB adapters (cypress/e2e/storage.spec.js): after the Version change, the saved slot’s name had the suffix. With IndexedDB, storage must return the data, not a promise.
Keep screenshots somewhere else
Replace the three callbacks, in js/main.js or anywhere before the first save. This keeps them in the game’s own storage space, as data URLs:
const blobToDataURL = (blob) => new Promise((resolve, reject) => {
const reader = new FileReader();
reader.onload = () => resolve(reader.result);
reader.onerror = () => reject(reader.error);
reader.readAsDataURL(blob);
});
monogatari.onSaveScreenshot = async (slotKey, blob) => {
const key = `${slotKey}__screenshot`;
await monogatari.Storage.set(key, await blobToDataURL(blob));
return key;
};
monogatari.onLoadScreenshot = async (key) => {
try {
return await monogatari.Storage.get(key);
} catch {
return '';
}
};
monogatari.onDeleteScreenshot = async (key) => {
try {
await monogatari.Storage.remove(key);
} catch {
// Already gone
}
};With LocalStorage, this writes …_Save_<id>__screenshot next to the slot, creates no IndexedDB database, shows the thumbnail, lists one slot (the __screenshot key is skipped), and deleting the slot removes both keys. Data URLs are large: LocalStorage gives a site a few megabytes in total.
Load a slot from code
monogatari.loadFromSlot('Save_1').then(() => {
monogatari.run(monogatari.label()[monogatari.state('step')]);
});Pitfalls and history
- The
FileSystemadapter had no host before 2.9.0. “Add screenshots and file system storage” (78cfbcda) addedFileSystemStorage, but no host answered it: the Electron preload passed only its five window channels, and the Electrobun view never connected. Each request waited forever, so a game set toFileSystemstopped before the main menu in both hosts, andupgrade()stored its callbacks without running them. 2.9.0 added the hosts’ side (dist/engine/desktop/storage.js), the 5-second timeout with its IndexedDB fallback, and the upgrades. The fallback is what a game sees when itsengine/core/is new but itsengine/electron/files are old: The Starter Game and Desktop Hosts covers both. onSave()was never called before 2.9.0, thoughAction.onSave()andComponent.onSave()were documented as running on every save. 2.9.0 calls them fromsaveTo()after the slot is written (cypress/e2e/engine/api.spec.js).- A dead error. Screenshots were first stored in the main space, and LocalStorage or SessionStorage with
Screenshotsshowedengine:screenshots:storage_incompatible. “Move screenshots to their own blob storage” (4b5fff30, June 2026) moved them to their own IndexedDB database and removed the check. The error stayed registered indebug/index.jsuntil 2.9.0 removed it, and_hasCustomSaveScreenshotis still set by theonSaveScreenshotsetter and never read. loadingOrdergroups were sorted as text until 2.9.0:engine.onLoad()sorted the distinct orders with.sort()and no comparator, so2and10ran10first. It sorts them as numbers now (.sort((a, b) => a - b)inonLoad()insrc/monogatari.ts), checked bycypress/e2e/actions/action.spec.js.- The adapter can’t change after setup. Changing the
Storage,NameorVersionsetting aftersetupStorage()changes the setting, not the space. A spec that needs other values opens the game withcy.openWithOptions(), which changesjs/options.jsbefore the page loads (storage.spec.js,autosave.spec.js, the LocalStorage test ofcomponents/save-screen-screenshots.spec.js). Before 2.9.0,save-screen-screenshots.spec.jsswitchedStorageaftercy.open()and passed only because the starter already used IndexedDB. - A failing spec at v2.8.1.
components/load-screen.spec.js, “Gives priority to the last known background”, expects the slot’s thumbnail to be the background image. Since “Change service worker cache strategy & fix CSP for screenshots” (f6bf8beb) turnedScreenshotson in the starter, the thumbnail is the screenshot, and the expected URL also names an asset host (datadyne.perfectdark.space) thatcy.loadTestAssets()no longer uses (it loads fromdatadyne.hyuchia.com). It fails on a clean checkout. So does “Shows the correct background on when both scene and background are used” inactions/show_scene.spec.js, on the same host name, after the load itself has passed its checks. - History. The step clamp is from “Go back to the last statement of a label if the step is out of scope” (
3e3c11cb, 2020). The persistent-storage request is from2e66b879(2020), the RemoteStorage headers from074681be(2020), the filter for corrupted slots from “Filter invalid save files” (dd4625c6, 2020), theSetthat keeps an overwrite from adding a slot from47900193(2020).loadingOrdercame with “Allow setting a loading order for actions in case they have dependencies” (14b32488, 2021), and thesrc/migrations/folder with “Update how character history is handled to improve rollback” (441c699e, 2021). The starter switched to IndexedDB in8e2e75ba(December 2025).
Exercises
Each check is a Cypress spec in cypress/e2e/exercises/ of a scratch copy of the repository (How Each Part Works), run with:
bunx cypress run --browser chromium --spec 'cypress/e2e/exercises/<name>.spec.js'The specs use the repository’s commands from cypress/support/commands.js (cy.open(), cy.start(), cy.proceed(), cy.save(), cy.clearStorage()). An exercise that changes src/ needs the browser bundle rebuilt first (bun build.ts --browser), because the specs load dist/index.html. When you are done, delete the spec and undo the engine changes: git checkout -- src dist/engine/core.
Exercise 1: load a slot from code
What to do. Write a spec that saves on the line Before, moves on to After, then loads the slot with the engine’s API (not the load screen) and expects Before back in the text box, with the step and the scene as they were.
Hint. Read what slot-container does when a slot is clicked in a load screen. Call loadFromSlot('Save_1') alone first, and look at the text box.
Check. The spec passes. With loadFromSlot() alone, the step and the scene come back but the text box stays empty, and the last assertion fails.
Solution
cypress/e2e/exercises/load-from-code.spec.js:
context('Load a slot from code', () => {
beforeEach(() => {
cy.open();
cy.clearStorage();
});
it('Shows the saved line again and puts the state back', function() {
this.monogatari.setting('TypeAnimation', false);
this.monogatari.script({
'Start': [
'show scene #224466',
'Before',
'After',
'end',
],
});
cy.start();
cy.get('text-box').contains('Before');
cy.save(1);
cy.proceed();
cy.get('text-box').contains('After');
cy.wrap(this.monogatari).invoke('state', 'step').should('equal', 2);
cy.then(() => {
const engine = this.monogatari;
return engine.loadFromSlot('Save_1').then(() => {
return engine.run(engine.label()[engine.state('step')]);
});
});
cy.wrap(this.monogatari).invoke('state', 'step').should('equal', 1);
cy.wrap(this.monogatari).invoke('state', 'scene').should('equal', 'show scene #224466');
cy.get('[data-screen="game"]').should('be.visible');
cy.get('text-box [data-ui="say"]').invoke('text').invoke('trim').should('equal', 'Before');
});
});loadFromSlot() resets the game (which empties the text box), writes the stores back and redraws the scene through Scene.onLoad(), but nothing in it runs a statement. The saved step points at the line the player was reading, so running it again shows that line.
Exercise 2: make a custom action come back after a load
What to do. Write a stamp <word> action that adds <p data-stamp="<word>"> to the game screen. Play stamp gold, Before, stamp silver, After. Save on Before, go on to After, and load the slot from the load screen: exactly one stamp, gold, must show.
Hint. Look at ShowImage: where does it record what it showed, what does its reset() do, and what does its onLoad() replay? An action registered from a spec misses the engine’s setup(), but reset() and onLoad() are called on every registered action.
Check. The spec passes. Without onLoad(), no stamp shows after the load. Without reset(), three show (gold and silver from the game you left, and gold again from the replay).
Solution
cypress/e2e/exercises/stamp-on-load.spec.js:
// A small action that shows a word on the game screen and records its
// statement in the state, so a save can bring it back.
const defineStamp = (Action) => {
class Stamp extends Action {
static id = 'Stamp';
static matchString([keyword]) {
return keyword === 'stamp';
}
// A load runs resetGame () first: remove what this action shows and
// empty its state key, so the game being left doesn't leak into the
// loaded one.
static async reset() {
this.engine.element().find ('[data-stamp]').remove();
this.engine.state({ stamps: [] });
}
// Then onLoad () replays the statements the save recorded, without
// recording them a second time.
static async onLoad() {
for (const statement of this.engine.state ('stamps') || []) {
const action = this.engine.prepareAction(statement, { cycle: 'Application' });
await action.willApply();
await action.apply();
await action.didApply({ updateState: false });
}
}
constructor([keyword, word]) {
super();
this.word = word;
}
async apply() {
this.engine.element().find ('[data-screen="game"]').append (`<p data-stamp="${this.word}">${this.word}</p>`);
}
async didApply({ updateState = true } = {}) {
if (updateState === true) {
this.engine.state({ stamps: [...(this.engine.state ('stamps') || []), this._statement] });
}
return { advance: true };
}
}
return Stamp;
};
context ('A custom action after a load', function() {
beforeEach(() => {
cy.open();
cy.clearStorage();
});
it ('Shows what the save recorded, once', function() {
this.monogatari.setting ('TypeAnimation', false);
this.monogatari.script({
'Start': [
'stamp gold',
'Before',
'stamp silver',
'After',
'end'
]
});
cy.window().then((win) => {
this.monogatari.registerAction(defineStamp(win.Monogatari.Action));
});
cy.start();
cy.get ('text-box').contains ('Before');
cy.save(1);
cy.proceed();
cy.get ('text-box').contains ('After');
cy.get ('[data-stamp]').should ('have.length', 2);
cy.get ('[data-component="quick-menu"] [data-action="open-screen"][data-open="load"]').click();
cy.get ('[data-component="load-screen"] [data-component="save-slot"]').first().click();
cy.get ('text-box').contains ('Before');
cy.wrap(this.monogatari).invoke ('state', 'stamps').should ('deep.equal', ['stamp gold']);
cy.get ('[data-stamp]').should ('have.length', 1);
cy.get ('[data-stamp="gold"]').should ('be.visible');
});
});The class extends the page’s own Monogatari.Action (from cy.window()), so the engine treats it like a built-in. registerAction() puts it at the front of the list, ahead of Dialog, which would otherwise take stamp gold as a line of dialog. The saved state holds stamps: ['stamp gold'], and the load writes it back before onLoad() runs.
Exercise 3: write a save-data migration
What to do. Suppose an older build stored the text box’s visibility as state.textBoxHidden instead of state.textboxHidden. Add an engine migration that moves the value to the current key, so that such a save loads with the text box hidden and without the old key.
Hint. The migrations receive the game part of the save: { state, history, storage }. HideTextBox.onLoad() hides the text box when state.textboxHidden is true. To write an “old” save in the spec, save, change the object saveTo() returns, and Storage.set() it back.
Check. After bun build.ts --browser, the spec passes. Without the migration, textboxHidden stays false after the load and the first assertion fails.
Solution
src/migrations/20261128-rename-textbox-hidden-state.ts:
import type { SaveGameData } from '../lib/types';
/**
* Saves written before the rename stored whether the text box was hidden as
* `textBoxHidden`. Move the value to `textboxHidden`, the key HideTextBox
* reads in its onLoad ().
*/
const RenameTextBoxHiddenState = (save: SaveGameData): SaveGameData => {
const { state } = save;
if (typeof state.textBoxHidden === 'boolean') {
if (typeof state.textboxHidden !== 'boolean') {
state.textboxHidden = state.textBoxHidden;
}
delete state.textBoxHidden;
}
return save;
};
export default RenameTextBoxHiddenState;In src/migrations/index.ts, import it and add it last:
import RenameTextBoxHiddenState from './20261128-rename-textbox-hidden-state';
const migrations: Migration[] = [
AddPauseStateToMediaState as unknown as Migration,
AddPreviousStatementToShowHistory as unknown as Migration,
RenameTextBoxHiddenState as unknown as Migration,
];cypress/e2e/exercises/save-migration.spec.js:
context('A save-data migration', () => {
beforeEach(() => {
cy.open();
cy.clearStorage();
});
it('Reads a save that used the old state key', function() {
this.monogatari.setting('TypeAnimation', false);
this.monogatari.script({
'Start': [
'Before',
'end',
],
});
cy.start();
cy.get('text-box').contains('Before');
cy.then(async () => {
const engine = this.monogatari;
const { value } = await engine.saveTo('SaveLabel', 1, 'Old format');
// Write the slot the way the older build stored it
delete value.game.state.textboxHidden;
value.game.state.textBoxHidden = true;
await engine.Storage.set('Save_1', value);
await engine.loadFromSlot('Save_1');
});
cy.wrap(this.monogatari).invoke('state', 'textboxHidden').should('equal', true);
cy.wrap(this.monogatari).invoke('state').its('textBoxHidden').should('be.undefined');
cy.get('text-box').should('not.be.visible');
});
});bunx tsc --noEmit passes with the new file. The migration leaves a save that already uses textboxHidden alone, so it can run on every load. Without it, the reset sets textboxHidden: false, the load merges a state that doesn’t have the key, and the stray textBoxHidden is kept.
Related pages
- Saving and Loading in the guides: the same feature from the player’s and the game developer’s side.
- Configuration:
Storage,AutoSave,Slots,SaveLabel,Screenshots,NameandVersion. - Save Screen, Load Screen and Save Slot: the components, their markup and how to restyle them.
- Engine API and Events:
saveTo(),loadFromSlot(),upgrade(),willLoadGameanddidLoadGame. - State, Storage and Rollback: the stores a save copies,
resetGame()and whatreset()must do. - Statements and Actions:
prepareAction()and the life cycleonLoad()replays. - Components and Screens:
showScreen(), the screens and the alert used to confirm an overwrite or a deletion. - The Starter Game and Desktop Hosts: the Electron and Electrobun hosts that answer the
FileSystemadapter. - Testing: running the Cypress specs.