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’s js/options.js calls monogatari.preferences({...}) right after monogatari.settings({...}), so in a game made from the starter, storage is set up inside options.js, before storage.js, script.js and main.js run.
  • 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:

  1. picks the adapter from Storage.Adapter;
  2. 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;
  3. builds the space: new Space(adapter, { name, version, store, endpoint, props }), unless the adapter was FileSystem and a desktop bridge exists. An IndexedDB space whose Version reads as less than 1 (0.0.0, empty) is opened at version 1, the lowest IndexedDB accepts;
  4. 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():

  1. shows engine:storage:filesystem_no_bridge when Adapter is FileSystem and there was no bridge;
  2. with IndexedDB, shows engine:storage:invalid_version for a Version below 1, and opens the space. When the open fails and the database already exists at a higher version (Version went down), it opens the space at that version (adapter.numericVersion) and shows engine:storage:version_lowered. When the database doesn’t have the Store (it changed after release) and has one store, it goes on with that store and shows engine:storage:store_not_found;
  3. with LocalStorage, copies the unprefixed keys a 2.8.1 game with a non-Latin Name wrote (see below), and when keys of a higher version exist, configures the space with that version and shows engine:storage:version_lowered;
  4. shows engine:storage:upgrade_failed when a game’s upgrade threw, and engine:storage:open_failed for 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 versionchange listener on the IDBDatabase closes the connection and shows the StorageUpdated string, 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 blocked until it closes. Artemis’s adapter makes its open request itself, so watchBlockedOpen() wraps indexedDB.open for the space’s database name while space.open() runs, shows the StorageBlocked string 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() reads Storage.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_run and writes the defaults. A multi-language game with the language selection screen waits instead, and writes Settings once the player picks a language (the didLocalize listener in init()).
  • preference(key, value) changes one preference and calls Storage.update('Settings', preferences) right away. The settings screen changes preferences through it.
  • preferences(object, true) merges and writes; preferences(object) without true only 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:

  1. It returns undefined and writes nothing unless the global playing is true.
  2. It takes the date with Luxon (DateTime.now().toISO(), with the time zone offset) and a timestamp in milliseconds.
  3. gameObject() collects { history, state, storage }: the engine’s live objects, which the adapter serializes when it writes.
  4. An empty name becomes the date and time as the player reads it (DATETIME_MED_WITH_SECONDS, like the save screen’s default name). save-slot shows a 2.8.1 slot whose name is its ISO date the same way.
  5. The thumbnail image is the third word of state.background (show background forest with fadeIn gives forest), or of state.scene when there is no background.
  6. The key is `${setting(prefix)}_${id || timestamp}`. prefix is the name of a setting ('SaveLabel' or 'AutoSaveLabel'), not the label itself: saveTo('Save') throws “Tried to access non existent setting”.
  7. When Screenshots is on and the game screen is hidden, it uses the screenshot showScreen('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, and showScreen() 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 JPEG Blob to onSaveScreenshot(slotKey, blob) and records the key it returns. A failure is a debug warning; the slot is written without a screenshot.
  8. 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.

sequenceDiagram participant Player participant UI as showScreen() participant Screen as save-screen participant Save as saveTo() participant Shot as onSaveScreenshot() participant Space as Storage (Space) participant List as slot-container Player->>UI: Save button in the quick menu UI->>UI: captureGameScreenshot() while the game screen shows UI->>Screen: open: true Player->>Screen: types a name, presses Save Screen->>Save: saveTo('SaveLabel', null, name) Save->>Save: playing? gameObject(), image, key Save_timestamp Save->>Shot: onSaveScreenshot(key, blob) Shot-->>Save: 'Save_timestamp__screenshot' Save->>Space: set(key, { name, date, image, game, screenshot }) Space-->>List: onCreate(key, value) List->>List: add the key, render a save-slot for it

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 __screenshot and 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: onCreate adds a key (through a Set, so overwriting a slot doesn’t add a second one), onUpdate passes the new value to the slot, onDelete removes it. Artemis calls onCreate for every set(), an overwrite included.
  • In a load container, a click on a slot (outside its delete button) runs loadFromSlot(slot) and then run(label()[state('step')]). In a save container, a click asks to overwrite (the slot-overwrite alert, 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.

flowchart TD click(["Click on a slot in the load screen"]) --> get["loadFromSlot('Save_1'): cursor 'wait', Storage.get('Save_1')"] get -- "missing key, or its label isn't in the script" --> refused(["A dialog, cursor 'auto', the promise rejects:<br/>the game stays as it was"]) get --> start["playing = true, event willLoadGame"] start --> reset["resetGame(): auto-play and skip off, storage replaced with storageStructure,<br/>step 0, every history emptied, every action's reset(), every component's onReset()"] reset --> hide["hideScreens()"] hide --> format{"data.Engine?"} format -- "yes: a v1 save" --> legacy["Convert Engine.* and Show into state and history"] format -- "no" --> migrate["migrate(data.game), then state(), history(), storage()"] legacy --> clamp migrate --> clamp["Step past the end of the label? Use its last statement"] clamp --> onload["engine.onLoad(): _restoring_state = true,<br/>actions by loadingOrder, components' onLoad()"] onload --> show["showScreen('game'), cursor 'auto', event didLoadGame"] show --> runit(["The caller runs label()[state('step')]"])

In order:

  1. Read and check. Storage.get(slot), then the label the save was made at (Engine.Label for a v1 save, game.state.label for 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 shows engine:storage:slot_not_found or engine:storage:slot_label_not_found, puts the cursor back and rejects, before anything changes. slot-container catches that rejection. Only then does it set playing and fire willLoadGame.
  2. Reset. resetGame() turns auto-play off (and skip, when Skip is above 0), replaces the storage with storageStructure, sets step to 0 and label to the Label setting, clears the deprecated block global, empties every history array, and calls every action’s static reset() and every component’s onReset(). The state keys of actions are not touched here: each action’s reset() puts its own key back to empty (ShowImage.reset() removes the images and sets images: []).
  3. Convert or migrate. A save with an Engine property comes from v1.4.1 or earlier: its Engine.Step, Label, Scene, Song, Sound, Particles, the Show list and the *History arrays become the current state and history, with img/ paths turned into assets/. Any other save goes through migrate(data.game), and its state, history and storage are written back with state(), history() and storage(). state() and storage() merge deeply (arrays are replaced, objects merged); history() replaces each history array.
  4. 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.
  5. Redraw. engine.onLoad() sets the global _restoring_state, groups the actions by loadingOrder, and runs the groups one after another; inside a group, the onLoad() hooks run at the same time. The components’ onLoad() hooks run alongside the action groups. Scene has loadingOrder = -2, so the scene is drawn before anything is placed on it; ShowCharacterLayer has 1, so the characters exist before their layers are added; the others have 0.
  6. Show. showScreen('game'), the cursor goes back to auto, and didLoadGame fires.
  7. Run. The caller runs the statement at the saved step. In a browser, the events come in this order: willLoadGame, didLoadGame, then willRunAction and didRunAction for 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 and Settings), awaits storage(oldData), with replaceStorage: true removes every key the result doesn’t have, and writes every key of the result with set(). 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 (the id key path removed), storage(oldData) runs synchronously, and delete() and put() 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, and openStorage() shows engine:storage:upgrade_failed with 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 only state, history and storage. Anything an action shows must be recorded in its state key, put back to empty in reset(), and drawn again in onLoad(). 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 } to didApply(); the state was already written back by the load.
  • loadFromSlot() doesn’t run the saved statement. Every caller runs label()[state('step')] afterwards, as slot-container and cy.load() do (Exercise 1).
  • Storage is set up once and opened once. Name, Version and Storage must be set before the first preferences() call (in the starter, in the settings() call at the top of js/options.js): a later change has no effect. monogatari.upgrade() must be called before the space opens, which is setup() in init() unless game code used the storage earlier.
  • Name and Version are part of every key. Renaming a released game hides every save made under the old name. A Version change 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-container parses the part after the label as a number to sort the slots, and treats any key that contains __screenshot as 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 FileSystem adapter had no host before 2.9.0. “Add screenshots and file system storage” (78cfbcda) added FileSystemStorage, 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 to FileSystem stopped before the main menu in both hosts, and upgrade() 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 its engine/core/ is new but its engine/electron/ files are old: The Starter Game and Desktop Hosts covers both.
  • onSave() was never called before 2.9.0, though Action.onSave() and Component.onSave() were documented as running on every save. 2.9.0 calls them from saveTo() 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 Screenshots showed engine: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 in debug/index.js until 2.9.0 removed it, and _hasCustomSaveScreenshot is still set by the onSaveScreenshot setter and never read.
  • loadingOrder groups were sorted as text until 2.9.0: engine.onLoad() sorted the distinct orders with .sort() and no comparator, so 2 and 10 ran 10 first. It sorts them as numbers now (.sort((a, b) => a - b) in onLoad() in src/monogatari.ts), checked by cypress/e2e/actions/action.spec.js.
  • The adapter can’t change after setup. Changing the Storage, Name or Version setting after setupStorage() changes the setting, not the space. A spec that needs other values opens the game with cy.openWithOptions(), which changes js/options.js before the page loads (storage.spec.js, autosave.spec.js, the LocalStorage test of components/save-screen-screenshots.spec.js). Before 2.9.0, save-screen-screenshots.spec.js switched Storage after cy.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) turned Screenshots on in the starter, the thumbnail is the screenshot, and the expected URL also names an asset host (datadyne.perfectdark.space) that cy.loadTestAssets() no longer uses (it loads from datadyne.hyuchia.com). It fails on a clean checkout. So does “Shows the correct background on when both scene and background are used” in actions/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 from 2e66b879 (2020), the RemoteStorage headers from 074681be (2020), the filter for corrupted slots from “Filter invalid save files” (dd4625c6, 2020), the Set that keeps an overwrite from adding a slot from 47900193 (2020). loadingOrder came with “Allow setting a loading order for actions in case they have dependencies” (14b32488, 2021), and the src/migrations/ folder with “Update how character history is handled to improve rollback” (441c699e, 2021). The starter switched to IndexedDB in 8e2e75ba (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.