# Liminalia Studio

Studio is the authoring app for writers. It runs on the dev server of `lim studio` (or `lim dev`) and isn't included in what `lim build` exports.

```bash
lim studio [project] [--port 5180]
# Studio: http://localhost:5180/__liminalia/studio
# Player: http://localhost:5180/
```

The client (browser side) is in `packages/studio/src/client/`, and the dev server side is in `packages/studio/src/server/`.
`packages/editor/src/protocol.ts` is the source of truth for the shapes (types) they exchange.

## Screens

The interface is in Japanese and English. Switch it with "English" / "日本語" in the "…" menu at the right end of the top bar (in the desktop app, also with "View → Language" in the menu;
the app menus, the start screen, the export window and dialogs switch too). If you haven't chosen, it follows the language of the OS or browser.
Syntax check messages also appear in English when the interface is in English (`diagnostics-en.ts` in `@liminalia/lang`, a table that builds the English from the shape of each Japanese message; the default output of `lim check` stays in Japanese, and `lim check --lang en` gives English.
A test confirms that every `code` and message is in the table. Plugin diagnostics use the `messageEn` and `hintEn` they provide, and fall back to the original text if there are none).
Messages the dev server returns when it refuses a request (the `error` in the response) also appear in English when the interface is in English. The client adds the header `x-liminalia-lang: en` (`STUDIO_LANGUAGE_HEADER`) to its requests,
and the dev server translates the message with the table in `server/errors-en.ts` (which builds the English from the shape of the Japanese message; lines not in the table use the English of the syntax check, and if there is none, the original text) before returning it.
A test confirms that every Japanese message of the dev server matches the table. Messages thrown by plugins are passed through as they are.
Command descriptions (the names and tags in the parts panel, completion, hover and the parameter panel) also show the English of the command definitions (`summaryEn`, `docEn`) when the interface is in English,
and the parts panel can also be searched with English words for what you want to do (`keywordsEn`). Plugin commands without English stay in Japanese.
The export window of the desktop app also shows its progress lines in the interface language (`@liminalia/project/build-lines-en`; the output of external tools, and the detailed messages shown when a tool can't be found, stay as they are).
Confirmations for deleting and overwriting don't use the browser's built-in `confirm()`; Studio asks with its own dialog (`askConfirm` in `confirm-dialog.ts`, which also shows "Yes" and "Cancel" in the interface language). Esc or clicking outside cancels.

### How the interface is organized (choose the object first)

Files, scenes, lines, pages, parts, characters, assets, variables, game settings, endings and comments are opened and selected first, and the actions are attached to that object where you can see them (OOUI).
The screen names in the top bar are all nouns, every panel has a heading and a close button, and the cards for files, scenes, lines, pages and the flowchart show the same menu as a right-click from their "…". The script heading is the open file itself; clicking it shows that file's menu (including Import text and Change history).
The following stay as tasks, because the procedure itself is what matters: test play, export, ⌘K and search and replace across files, running checks and measurements, importing text, applying a theme, assigning voices in bulk, and the getting started tour.

From left to right, the top bar has the project button (the cover image and the project name; the cover is the export icon (build.icon), or the first background of "New game" if there is none; clicking it opens "Project"), back and forward (⌘[ and ⌘], or the mouse's back and forward buttons), the switch between the main screens ("Script," "Flowchart" and "Check"; Check has a badge with the number of problems),
the other screens ("Characters," "Assets," "Variables," "Game settings," "Game screens" and "Plugins") and the "More screens" menu,
search (⌘K; in the desktop app, ⌘P too; see "Search and commands" below), "Export," "Test play," the color scheme button (it switches auto → light → dark in that order; the desktop app tells the app the choice (`setTheme`), and the export window uses the same color scheme), and the "…" menu (Refresh, Getting started tour, How to use (website), How-to guides (website), language, showing and hiding panels, and backgrounds in scene headings).
"How to use (website)" opens the Studio guide on the site (`/guide/`, or `/en/guide/` in the English display), and "How-to guides (website)" opens the how-to guides (`/howto/`), in another tab (the Studio app opens it in the default browser; it's also in the Help menu).
The site's URL is kept in one place, `SITE_URL` in `protocol.ts`, and links are made with `siteUrl` and `referenceUrl`.
The top bar fits within the width of the window (`fitTopbar` in `app.ts`, which measures again whenever the width changes). If there isn't enough room, it first shortens the project name to 7 characters,
then moves the tabs of the other screens, starting from the end (Plugins), into the "More screens" menu, and if that still isn't enough, it shows only the cover for the project.
Moved tabs are hidden, so Tab doesn't move focus to them either (at a width of 1024px, all the other screens are in the menu).
The "More screens" menu lists the screens that didn't fit, and always "Timeline," "Comments," "Voices" and "Trash" (Timeline can also be opened with "Open" in the right panel of the Script screen).
The badge with the number of open comments appears on this button. When the current screen is one in the menu, the button looks selected. When the text size is 100%, the text size button isn't shown.
The keys for switching screens follow the order of the top bar: ⌘1 Script, ⌘2 Flowchart, ⌘3 Check, ⌘4 Characters, ⌘5 Assets, ⌘6 Variables, ⌘7 Game settings,
⌘8 Plugins, ⌘9 Project (Timeline, Comments and Voices, and Game screens, which was added later, have no number). The tab tooltips show the keys.
Except on the Mac, keys are shown with Ctrl (keys written with ⌘ are Ctrl on Windows and Linux; tooltips and tour text are changed to Ctrl+… too; `plainKeys` in `strings.ts`).
When Studio is opened in a browser, it doesn't take keys the browser uses: ⌘P and Ctrl+P stay as print (open files with ⌘K and Ctrl+K), and instead of
⌘1–9 and Ctrl+1–9 (which switch browser tabs), screens switch with ⌃1–9 on the Mac and Ctrl+Shift+1–9 elsewhere (⌘⇧3–5 on the Mac take screenshots, so they aren't used).
⌘+, ⌘− and ⌘0 are taken as Studio's text size (instead of the browser's zoom), and ⌘S as save. ⌘⌥P starts a test play from the cursor line, ⌘⌥R adds ruby to the selected characters (see "Ruby" below), ⌘⌥K bookmarks the cursor line, F2 and ⇧F2 go to the next and previous bookmark (see "Bookmarks" below), F12 goes to the jump target or the macro definition and ⇧F12 lists the lines using the macro on the cursor line (in some browsers the developer tools get them first), ⌘F finds in the open file in the script (see "Find and replace in the block view" below; the editor's search in the code view, and the search field of other screens; in the desktop app, also "Edit → Find" and "Edit → Find in All Files" (⌘⇧F) in the menu), and ⌘Z and ⇧⌘Z on the Timeline, Voices, Assets, Characters, Flowchart, Game settings, Game screens, Project and Variables screens undo and redo the changes made on that screen (see "Play from Here," "Go to Jump Target" and "Undo on screens" below). "Refresh" in the "…" menu (in the desktop app, "Project → Refresh" in the menu, ⌘⇧R)
reloads a project that was changed outside Studio (see "Refresh" below). "Test play" plays the game from the beginning (in the desktop app, in the app's test play window; in a browser, in another tab).
"Play from Here" starts a test play from the selected line (see "Play from Here" below).
Back and forward return to where you were, as in a browser. They remember screen switches, switches between script files, and moves to a line 10 or more lines away in the same file (not moves made by the preview's cursor sync),
and moves within a screen (asset kinds and folders, the selected character and the view ("Settings" and so on) on the Characters screen, position adjustment, variable kinds, the project panels, plugin pages). When you go back to a place in the script, the preview moves to that line too
(not while it is paused). Plugin screens can go back the same way with `navState`, `restoreNav` and `ctx.remember()` ([plugins.md](plugins.md)).
In the desktop app, "Export" opens the export window (the client tries to go to `STUDIO_PLAY` or `STUDIO_EXPORT`, and the app catches it).
In a browser, it shows how to export instead (`export-dialog.ts`): open the project in the desktop Studio and click "Export,"
or run `lim build . browser` in the project folder ("Copy" copies the command). Notices appear over the bottom center of the screen. Notices with a button such as "Undo" (12 seconds) aren't removed when the next notice arrives; the next one stacks on top (up to 3; each disappears when its time runs out or when you click it).
Error notices (`errorText` in `errors.ts`) show only what happened and what to do. Reasons the dev server returns in words (4xx) are shown as they are;
unexpected failures inside the server (5xx), lost connections and program errors are reworded. The raw details (exception messages, HTTP status codes) are left only in the developer tools console
(what project plugin screens and commands throw is shown as it is, for the people who write the plugins).

Studio's look uses Radix Colors (mauve for grays, violet for actions and the current position), with the bundled fonts Zen Kaku Gothic New, Zen Old Mincho and JetBrains Mono
(`client/fonts.css`; the desktop app includes only the woff2 files for the weights it uses). Character colors use `color` in cast.json (the color of the name box in the game) as it is,
and characters without a color are gray. Faces are cropped from the base variant of the sprite, and the crop position is saved in Studio's data (`.liminalia/shared.json`).
Things only Studio needs (face positions, the positions of scenes moved on the flowchart and so on) aren't saved in the game data (`.lim`, `cast.json`, `liminalia.json`).

Studio's data is split into two files (`server/studio-state.ts`). What is shared with the project (scene tags and statuses `sceneMarks`, character notes `castNotes`,
face crops `faces`, head marks `heads`, and positions of scenes moved on the flowchart `mapPositions`; `STUDIO_SHARED_KEYS`) is kept in `.liminalia/shared.json` and goes into Git
(the template's `.gitignore` excludes everything in `.liminalia/` except this file). It reaches co-authors and the mobile studio too, and changes brought in with Git show up on screen right away.
What belongs to you alone (where you last were, bookmarks, favorites, breakpoints, the character goal and daily counts, the TODO marker words, the name for comments) is kept in
`.liminalia/studio.json` and stays out of Git. Shared data that an earlier version saved in `.liminalia/studio.json` is moved to `.liminalia/shared.json` when the project is opened
(if `.liminalia/shared.json` already has a value for the same scene or character, that one is used). Neither file goes into the exported game.

The first time Studio opens, it guides you by highlighting the main areas in turn (blocks and code, the parts panel, the script, the preview, test play, dropping assets)
(`client/tour.ts`; close it with Esc or "Close," and it remembers that you've seen it). You can see it again with "Getting started tour" in the "…" menu.

When Studio opens, it returns to the file and line you had open last time (`lastOpen` in `.liminalia/studio.json`, remembered per project; if the file is gone, it opens the `entry` file).
When there is nowhere to return to (the first time a project is opened), the cursor goes to the first line of text in `entry` (a line whose picture shows in the preview, not the comments at the top).

## Search and editing

**Search and commands** (⌘K; "⌘K" in the top bar, or the search button in the bar of the phone app) is a panel where you type a name to open something (`palette.ts`, `panes/overlays.ts`).
It searches files, scenes (for the open file, its current labels before saving), bookmarks, screens, characters, commands, assets and variables in a single list, and shows the kind on the right.
When you choose a result, files and scenes open at that line, screens open that screen, characters open that character on the Characters screen, assets open that file on the Assets screen, and variables open that variable on the Variables screen (each is added to the back history).
The commands are the ones in the top bar, the "…" menu and the script heading menu (test play, play from the cursor line, export, search and replace across files, check, the all-routes test, block view and code view, collapsing commands, comments, importing text, change history, showing panels, text size, color scheme, language, Refresh, the getting started tour, plugin commands and so on), with their keys on the right if they have any.
It ignores the difference between hiragana and katakana (the two Japanese kana scripts), between full-width and half-width characters, and between upper and lower case. A result matches if it contains the typed characters in order, and results that match by name come before those that match only by description or kind (up to 80 results).
Scenes (and the scene at the top of a file) can also be found by their flowchart title (`extra.flowchart.titles` in liminalia.json), their first line of text (from `GET /map`, the same as the flowchart; for the open file, the current document before saving),
and their tags and status (see "Edit tags and status" below; `#tag` and the status name). The title or the first line is shown faintly after the name. These three only match when the typed characters appear together
(after matches on the name and before matches on the description; the titles are read again each time ⌘K opens).
Variables are reloaded when the panel opens and added to the list once they have loaded.
When nothing matches what you typed (and at the end of the list), "Search all files for "…"" is shown; choosing it searches all files for those words (`QuickOpen.fallback`).
The actions also include "Find in this file" and "Replace in this file" (in the script heading's menu too), so the block view's find and replace opens on the mobile studio, which has no ⌘F.

**Ruby** (small reading aids printed above Japanese characters): select characters in the text (dialogue and narration) and press ⌘⌥R ("Add ruby" in ⌘K, or in the script heading menu) to turn them into `{r base|reading}` (`model/ruby.ts`).
If the glossary (`extra.glossary` in `liminalia.json`) has a `reading` for the word, the reading is filled in too; if not, the cursor is placed where you type the reading (between `|` and `}`).
In the code view, ruby goes on the selected characters; in the block view, on the characters you select while editing the text in place (if you aren't editing, a notice tells you to start editing the cursor line, select the characters and press ⌘⌥R).
Ruby isn't added to the speaker's name, inside markup (`{…}`), or to a selection that spans lines. "Add ruby from glossary readings" in the script heading menu (and in ⌘K) goes through the open file
scene by scene (from one label to the next) and adds ruby to the first occurrence of each word that has a reading (longer words first; it skips a word that already has ruby in that scene, and doesn't look inside `@define`; ⌘Z undoes it).

**File tabs**: when you open two or more script files, tabs for the open files appear above the script heading (`file-tabs.ts`; the name is the file name without the folder, and hovering shows the name with its folder).
A file you open is added to the right of the current tab, and when there are more than 10, the oldest ones other than the current file are removed. Click a tab to go to that file, and close it with × or the middle button (if it is the current file, the file of the tab on its right opens, or the one on its left if there is none).
Right-click a tab for "Close tab," "Close other tabs" and "Open to the side" ("Split view" below). The tab order is remembered per project in that device's localStorage (files that are gone are removed). They aren't shown in the phone app.

**Split view**: "Open to the side" in the right-click menu (and "…") of a file tab or a file in the scene list, or "Open a file to the side" in ⌘K, opens another file in the code view to the right of the script (`split-pane.ts`).
You can edit the file on the side in place too; automatic saving, bringing in outside changes and choosing between conflicting changes work as in the script (it has its own saving).
Breakpoints (click to the left of a line number), bookmarks (⌘⌥K) and comment marks (click one to show that line's thread in the right panel; add one with ⌘⌥M) can also be added and removed in the side file as in the script,
and while it is open, that editor moves the marks. While you are typing in the side file, the preview (the stage and "State at this line") and the comments in the right panel follow that file's cursor line
(the state at that point is taken from the lines around it), and when input returns to the script, they go back to the script's cursor line. ⌘⌥P also starts a test play from the cursor line of the side file.
Right-click in the line number column for "Play from Here," "Add comment," "Breakpoint" and "Bookmark" for that line.
The panel heading has the file name and save status, "Swap with the main editor" (swaps them, keeping each cursor line) and a close button (also in ⌘K).
The same file isn't opened in both (a file open in the script can't be put on the side, and if you open the side file in the script, it is saved and the split view closes).
Drag the border with the script to change the width (remembered in `liminalia.studio.width--split-w` in that device's localStorage; double-click to go back to half; neither panel gets narrower than 240px).
While the split view is open, the right panel uses its narrower width (340px), and each panel's width decides its margins and its summary cards. It isn't shown in the phone app.

Choose "Open containing folder" from the menu of a file in the scene list or of an open file's tab to open the folder that contains that script; in the Mac Finder and Windows Explorer, the script is selected. If you've changed where scenarios are saved, or the script is in a subfolder, it follows that location. On Linux, it opens the parent folder. It isn't shown in the version that runs only in the browser.

**Scene markers**: Click "Scene markers" in the scene list to list the `// @scene` comments in the project's scripts in a popover, with their files and lines. It closes with the close button, Esc or a click outside, and on a phone also with the back gesture. The order follows the scene list's name order or story order, and within a file, the line order. The field filters by date, event and file name, and clicking a marker goes to that line. "Add at current line" inserts a comment before the cursor line, and the list reflects changes being edited too. For example, write `// @scene August 27, Kanade visits` or `// @scene date=8/27 event=visit`. When a value contains a space, put it in quotation marks, as in `event="Kanade visits"`. The date can also be text such as "next day." A marker doesn't become a game command or a jump target.

Hover over or click the problems and the character count at the top of the script to see a breakdown. The problems are the errors, warnings and info in the open file; click one to go to that line. For the count in this scene, it shows the line range from the label to just before the next label (from the start of the file if there's no label) and how the characters are counted. Scene markers don't divide this range. When the screen is too narrow to show the character count, the same explanation opens from the script's "…" menu.

**Bookmarks**: marks put on lines (`editor/bookmarks.ts`). ⌘⌥K (in the block view, also "Bookmark" in a line's right-click menu, or "Toggle bookmark on the cursor line" in ⌘K) adds or removes one on the cursor line.
The code view shows a colored line at the left edge of the line, and the block view shows a mark to the left of the line (click it to remove). The mark is placed at the start of the line, so it stays on the same line even when lines are added above it.
A "Bookmarks" list appears at the top of the scene list (sorted by file name and line order; it shows the content of the line, the file and the line. Click one to go to that line, or right-click it to remove it), and bookmarks are listed in ⌘K too.
F2 and ⇧F2 go to the next and previous bookmark in the open file. Bookmarks are remembered in `bookmarks` in the project's `.liminalia/studio.json` (file → line, the content of that line (up to 80 characters, shown in the list) and a hash of the whole content), and aren't included in the game.
For a file open in the split view, that editor moves the marks while it is open too. When a file that isn't open is rewritten elsewhere (another editor, the split view, replace, a plugin, Git and so on,
detected when the file's hash differs from when the marks were last placed), the marks are put back, as with breakpoints, on the line with the same content (the one nearest the original line if there are several), or else on a similar line
(if none is found, they keep the original line number; `model/bookmarks.ts`). Remembered marks are also put back onto the current content when a file is opened. The dev server moves the marks of a renamed file (renaming, below),
and when a scene is moved to another file or a file is split, the marks of the moved lines move to the lines where they ended up. Marks of files that are gone aren't listed.
When saving to Studio's data file, only the entries for files changed on this screen are written over a freshly reloaded copy of it (so marks the dev server moved aren't lost).

**Copy scene text**: from the right-click menu (and "…") of a scene in the scene list or a scene heading in the block view, the script heading menu (the cursor's scene) or ⌘K,
copies only the text of that scene to the clipboard (for proofreading or handing to an AI; `model/scene-text.ts`). Commands, comments, labels, empty lines and the inside of macros are left out.
Dialogue becomes `Speaker「line」` or `Speaker "line"` (on a line whose name box name was changed with `{name …}`, that name), narration stays as it is, and choices become `Choice: text`, one per line.
Inside the text, ruby becomes `base《reading》` (the Japanese convention, the same as in the recording script), `{br}` becomes a line break and embedded values become `［expression］`, and click waits and inline commands are removed.
Scenes in files that aren't open are copied from the content on disk.

**Play from Here** starts a test play from a line or a scene (`play-launch.ts`; the save is built in `model/play-from.ts`). It is in the right-click menu (and "…") of lines, pages and scene headings in the block view,
the right-click menu (and "…") of scenes in the scene list (including the first scene of a file), the right-click menu of flowchart cards, and "Play from the Cursor Line" in the script heading menu and ⌘⌥P (the cursor line, in both the code view and the block view).
It opens in the same window as "Test play" (in the desktop app, the app's test play window; in a browser, another tab; in the phone app, over the screen). It works the same for scripts in subfolders (`part1/chapter2`).
The player's `?start=file#label&skip=N` only starts from the beginning of that scene in an empty state (variables at their initial values, no background, sprites or BGM) and fast-forwards to page N, so it isn't used.
Instead, from the current position data (`GET /sweep`), Studio builds a save with the background, sprites, BGM and variables just before that line runs, and starts from it (built the same way as "Play" on the timeline):

- For text and choice lines, the save of that line's state (the same as the preview). For a label line, the state right after passing that label (the state on arriving there by a jump)
- For other lines (commands and so on), the save of the file's page is the skeleton (the `@call` return points and the `@let` values), the position is that line's command, and the look of the game screen and the variables come from
  the nearest earlier line that has a state (or, if there is none, from the point of entering the file; `Sweep.base.stage`)
- Choice lines and lines inside `@script` and `@html` start from their `@choice` or `@script` line. Empty lines and comments start from the next command. It can't start from inside a macro (`@define`), so it starts from the beginning of that scene with variables at their initial values, and says so
- For a line the current route doesn't pass, it first looks for a route that does (`GET /sweep/reach`, searching the same way as the preview, for up to 15 seconds). If none is found, it starts from the state of the line before and says so

The save is put in localStorage (`PLAY_FROM_KEY`), and the player opens with `/?play=1&from=<id>&start=<scene>`. The player loads the save with the matching id using `loadSave` (only when served by the dev server; `packages/web/src/studio-play-from.ts`),
and if it can't, starts from the beginning of the `?start=` scene. To allow sound to play, it first shows "クリックで開始" (Click to start). The desktop app asks with `STUDIO_PLAY` with the same query, and the app passes it straight on to the test play window.
`temp.` variables, which aren't part of a save (`SaveData`), aren't carried over.
The part that looks up the current position and builds the save (`findPlayStart`) is also used by "Play from Here" in the VS Code extension (`@liminalia/studio/play-from`). The extension can't write to the browser's localStorage,
so it leaves the save with the dev server through `POST /play-from`, and the page `GET /play-from?id=&start=` puts it in localStorage and then moves to the same `/?play=1&from=<id>&start=<scene>` (`server/play-from.ts`; what it is given is only kept in memory and not written to files).

**Test play tools** (only when served by the dev server; `packages/web/src/play-dev.ts` in the player; not included in exported games):

- When you fix the script, a test play in progress shows "The script changed" and "Reload from here" (the dev server reports script changes with
  `liminalia:scenario-changed`; a test play keeps running the script it loaded, so fixing it alone changes nothing). Reloading keeps the current state
  (including the history, the record of choices and the play time), reloads the script and continues from the current page (`SystemController.reloadHere`; even if lines have shifted, it finds the same page the same way as loading).
  ⇧R reloads too. It doesn't show this on the title screen (the next play started reads the new script). When plugin code or project data changes, the whole player reloads as before
- ⇧E and "Open this page in the script" in the menu at the top right open the line of the current page (for choices, those choices) in Studio. In a browser, it's passed through a same-origin BroadcastChannel
  (`TEST_PLAY_CHANNEL`), and if no Studio receives it, the test play shows "The studio isn't open". In the desktop app, it's passed from the test play window's preload
  (`preload-test-play.ts`) through the app, and the app brings the Studio window to the front. "Project → Reload from Here" and
  "Open This Page in the Script" in the app's menu (only while a test play is open) do the same
- Runtime problems (a missing screen, an error in an expression and so on; they also go to the console) are shown small at the top right as "N warnings" and "N errors", and clicking lists them in a menu (click one to open that line in Studio).
  They're also sent to Studio's check, in the "Found in test play" category. Notices that a save position shifted because of script changes aren't sent
- ⇧R and ⇧E aren't in the player's default key assignments. Even if the project assigns these keys, the test play gets them first

**Go to Jump Target**: opens the jump target of `@jump`, `@call`, a choice, or a parameter of the jump target type (including `@dialog target=` and `{@…}` in the text) (`goto-target.ts`).
In the code view, hold ⌘ (Ctrl except on the Mac) and point at a jump target to underline it, and ⌘-click to go there (`editor/goto-link.ts`; ⌘-clicking a collapsed command card also goes to that line's jump target).
F12 goes to the jump target of the cursor line (in the code view, the one at the cursor position, or else the first one on the line). In the block view, click "→ jump target" on a choice, ⌘-click the line, or choose "Go to Jump Target" in the line's right-click menu.
If it is in another file (including `part1/chapter2` in a subfolder), that file opens, and where you were is added to the back history (go back with ⌘[). It finds and resolves the target the same way as "Go to Definition" in the VS Code extension
(`goto.ts` in `@liminalia/lang`; for the open file, it resolves with the current labels before saving). For a jump target decided by an expression or one that can't be found, it doesn't move and says so.

**Go to Macro Definition**: on a macro call (`@name` on a line, `@with name`, or `{@name}` in the text), F12 and ⌘-click (the name is underlined in the code view) also go to the macro's `@define` line
(a jump target on the line comes first; the open file is searched in its current document before saving, and other files with `defines` of each file from `/project`; `goto-target.ts`).
F12 on an `@define` line, ⇧F12 on the cursor line, and "Lines using this macro" in the block view's right-click menu list the lines that use the macro in a menu, in the same form as "Lines Leading Here"
(the line's text, the file and the line; click one to go there; `GET /macro/uses`, `server/macros.ts`; it includes lines inside `@if` and `@define`, and `{@…}` in text and choices; changes waiting to be saved are saved first).
⌘K also shows "Go to macro definition" and "Lines using this macro" while the cursor line is a macro. Completion and hover read the macros of the open file with `@liminalia/lang` (`defineSpec`)
and also offer the macros of files brought in with `@use` (with candidates for the `asset(folder)`, `cast` and `enum(…)` types and the summary from the comment right above `@define`; `macroSpecs` in `editor/complete.ts`).

**Lines Leading Here**: the right-click menu of a scene in the scene list, a scene heading in the block view or a flowchart card, and the script heading menu, list the lines that lead to that scene in a menu
(how it gets there, the file and the line; click one to go to that line). It is built by following the arrows of `GET /map`, the same data as the flowchart, in reverse (`model/incoming.ts`), so it includes `@jump`, `@call`, choices, commands with a jump target
(including what plugin commands report they might jump to, and the candidates for jump targets given as expressions) and scenes continuing from the previous one, and it never disagrees with the lines in the flowchart. Changes waiting to be saved are saved before it looks.

## The Script screen

**Script** has the scene list on the left, the script in the middle, the preview and state on the right, and thumbnails at the bottom.
To the right of the script heading are the number of characters in the cursor's scene ("N characters in this scene"), the number of problems and the save state. While text is selected in the code view, or lines are extended with Shift in the block view, it shows "N characters selected"
(a selection within one line counts its characters; a selection across lines counts the text of the selected lines). It counts the same way as `lim stats` and the character count on the Check screen (the shown characters of dialogue, narration and choices; ruby counts its base characters,
and commands, inserted values, spaces and the outer brackets of dialogue aren't counted; `model/scene-chars.ts`). It waits until you stop typing, and is hidden when the panel is narrow.
At first, the scene list shows only files (with the number of scenes to the right of each name; when the panel is narrow, the middle of the name is left out, keeping the last 8 characters and the extension;
when names sharing the same beginning are listed (`episode1_2.lim` and `episode10_1.lim`), it keeps what follows the shared beginning; `model/trunc.ts`).
When sorted by name, scripts in subfolders (`part1/chapter2/side`) are listed under folder headings (`part1/`, `chapter2/` with the number of files inside), indented one step per level (`folderItems` in `panes/toc.ts`;
folders come before files at the same level, in name order). Click a heading to collapse or expand it (collapsed folders are remembered; folders are expanded by default). Story order crosses folders, so it shows names with their folders and no headings. With the switch at the top, choose name order (numbers are compared as numbers, so chapter3_2 comes before chapter3_10) or story order (following jump targets in the order they are written from "New game" in the flowchart, in the order files are first reached; files that are never reached come last, under a heading, in name order) (the choice is remembered). The › to the left of a file name expands that file's scenes (labels),
each with a small image (that scene's background and the faces of the characters in it), its name and its first line of text; click one to go to that line (expanded files are remembered).
Long lists (the scene list, variables, check problems, the asset grid) build only what is visible plus a little more, and build the rest as you scroll and the end marker comes near (`lazy-list.ts`;
the scene list builds up to the current file first, and when returning to the previous scroll position or showing the selected variable or asset, it builds up to there first).
The "＋" to the right of a file name adds a scene (label) at the end of that file. Right-click a scene (or use its "…") for "Play from Here," "Lines Leading Here" and the scene actions ("Scene actions" below). Search across files (⌘⇧F) shows a field at the top of the list.
The search is done by the dev server (`POST /search`; `server/search.ts`, with the search rules in `search.ts`), which searches every script, including files in subfolders, reusing the parse results
(if the open file has edits that aren't saved yet, that content is sent along with the search; the client doesn't fetch the files one by one).
Pack scenarios (`packs/<id>/scenario`) are searched too and listed after the main ones as `packs/<id>/scenario/<scenario>.lim` (`packs` in `SearchOptions`; read with the speakers in the pack's `cast.json` too).
Studio has no way to open and write pack scenarios, so their lines don't open when clicked, and replacing in all files skips them as read-only.
The buttons below the field change the search options (they are remembered): "Text" searches only dialogue and narration (leaving out commands, comments, labels, choice lines, speaker names, and markup inside the text
(`{@…}`, `{= expression}`, `{click}` and so on, and decoration prefixes); the base characters and readings of ruby count as text), "あア" treats hiragana and katakana as the same,
"Aa" matches case (the default ignores case), and ".*" uses a regular expression (JavaScript syntax; if it can't be read, it says so).
Matching lines are listed by file with the number of matches, and every match is marked (up to 300 lines). If there are more than 5,000 matching lines or it takes more than 3 seconds, it stops there and says so.
The two menus below the options narrow the search: where to search (all files, the open file, or a folder; `scope` in `SearchOptions`; with the open file chosen, opening another file searches again)
and speaker (only that speaker's dialogue lines, including inside `@if` and `@define`; `speaker`). Both also apply to replace in all files, and aren't remembered.
While results are shown, the scene list gets wider (`min(30rem, 32vw)`, or the width you dragged it to if that is wider; it goes back when you close the field or clear the text).

**Replace in all files** opens with "Replace" to the right of the search field (`panes/replace-panel.ts`; the logic is in `model/replace-all.ts`). Matching lines are listed by file with a preview of the characters removed and added
(up to 500 lines; any more are replaced without being listed, and can still be excluded by file). Clear the checkboxes by file or by line, then click "Replace." It searches the same way as search across files (the dev server searches with the same options in the same field). With a regular expression, the replacement can use `$1` to `$99`, `$&` and `$$`.
Changes to the open file go in as editor changes, so ⌘Z undoes them (they are saved by automatic saving). Other files are read when replacing, and if they are still as they were when searched, they are saved through the write API (`PUT /file`) with the hash from the search as baseHash, so they are kept in the change history
(it doesn't check on every save, but checks once after replacing). Files changed elsewhere after the search are skipped. Read-only files are skipped (and have no checkbox), and so are lines of the open file whose content changed after the search.
All the replaced files are remembered as one action, and "Undo" in the notice and in the replace panel undoes them all at once (including files that aren't open; it checks the same way as "Undo on screens" below,
and if a replaced file was changed elsewhere afterward, it undoes nothing and says so; if the open file was already undone with ⌘Z in the script, that file counts as undone).
Skipped files are reported at the top of the list (until you search for something else).
The script switches between "Blocks" (the block view) and "Code" (the code view) with the switch above the script (⌘E) (both edit the same document and share undo, automatic saving, the preview and the syntax check).
The block view shows labels as scene headings (with that scene's background; the "…" menu can remove the background, leaving just the name and a line), the command lines that follow as a row of one-line cards
(colored by kind; sprites show the character's face and color; details such as fade, time and volume are in the parameter panel), dialogue with the face, name and text, narration as text with the face column left empty,
and choices as a card (click "→ jump target" on a choice to go there).
Comment lines that continue from the line above (such as the explanation at the top of a file) are grouped together; while collapsed, the group shows its first line and "N more lines" (click to expand; every expanded line can be edited, and a group expands when Find in the file lands inside it).
Lines with errors and warnings get a wavy underline on their content (the text, the command card, the scene name) and a mark ("!") on the left. The diagnostics are the same as the wavy underlines in the code view
(the check as you type and the whole check on save; `editor/lint.ts`). Click the mark to show a card with the message, the suggested fix and "Fix" (when there's a fix that can be applied) (`block-marks.ts`).
**Drafts**: "Mark as draft" in the right-click menu (and "…") of a file in the scene list writes `// lim: draft` at the top of the file ("Unmark as draft" removes it; for the open file it's an editor change).
Draft files show "Draft" next to the name, and aren't in exports, the all-routes test or coverage (they can still be test played; "Drafts" in [format.md](design/format.md)).

**Scene info**: "Scene info" in the right-click menu (and "…") of a scene in the scene list, a scene heading in the block view, a card in the flowchart, and in the script heading menu,
writes the point of view (character IDs and speaker names are suggested), the date in the story and the place to `scenes` in liminalia.json (`file` or `file#label`; `POST /scenes`, other fields are kept).
The staging rules (Check in the project settings) read it.

**Format**: "Format" in the script heading menu and in ⌘K tidies the open file the same way as `lim fmt` (spaces in command lines and expressions, and block indentation if `fmt.indent` is set).
It goes in as one editor change, so ⌘Z undoes it. Files with syntax errors aren't tidied, and the reason is shown.

The files in the scene list and the file tabs get a dot for errors and warnings (red if there are errors, yellow if there are only warnings; the check as you type for the open file, the check results for the others).
Each time the script changes, only the groups (pages, lines) where one of the following changed are rebuilt: the line number, the text, the parse result, or the look decided by the duration bars (the background of the scene heading, the face on dialogue).
Everything else reuses the elements drawn before, and only the places whose order changed are moved (`itemKey` in `blocks.ts`; groups are also rebuilt when you start editing them in place and when characters or other image sources change).
When you switch to the block view, only the groups in the 120 lines above and 360 lines below the place to show (the line you were looking at before switching, or the cursor line) are built right away.
The rest get placeholder boxes of approximate height (`.blk-pending`; the height is estimated from the kind of line by `estimateHeight` in `model/blocks.ts`, which also estimates the height of pages off screen),
which are replaced 12ms at a time, starting nearest to where you are looking (for an 8,000-line file, switching went from about 700ms to 60–80ms, and the rest is built within about a second).
When you move to, select or edit a line that isn't built yet, the area around it is built first. While building, the line you are looking at doesn't move (the browser's scroll anchoring takes care of this, and in browsers without it, the scroll is adjusted by the difference in height).
**Find and replace in the block view** (⌘F; `block-find.ts`): shows a small field at the top right of the blocks (with selected text, it looks for that). It searches the lines of the .lim file themselves (the same text as ⌘F in the code view),
and "Text", "あア", "Aa" and ".*" below the field switch the same options as the project search (text only, ignore hiragana and katakana, match case, regular expression).
The options are shared with the project search and remembered (`search-flags.ts`), so switching one in either place switches it in the other. Replacing with a regular expression can use `$&`, `$1` and so on, and a pattern that can't be read shows "Not a valid regular expression" where the count goes.
It counts lines that aren't built yet (placeholder boxes) too and shows "N of M", and builds the groups with matches before the ones around where you are looking (the 40 nearest the current match right away, the rest a little at a time).
Lines with matches get a background, the line of the current match gets an outline, and matching characters in the drawn text get a text highlight (CSS Custom Highlight; where the drawn text differs from the .lim text, such as command parameters, only the line is marked).
Enter (and the ↓ button) goes to the next match and Shift+Enter to the previous one, selecting that line (the preview follows). "Replace" opens the replace field: "Replace and find next" replaces the current match and moves on (to the next match after the replaced text, so it doesn't keep returning to the same place even when the replacement contains the search text), and "Replace all"
replaces every match in the file as one change (⌘Z undoes it in one step). Read-only files aren't replaced. Esc (even while a button in the panel has focus) or the close button closes it, and so does switching to the code view.
Click the face on a line of dialogue (only for characters with variants) to see the expressions of the sprite set shown at that line in a list of faces (`face-picker.ts`; the faces are cropped with "Face position" on the Characters screen).
Choose one to rewrite the variant of that character's `@chara` in the page of that dialogue (from after the previous text up to the dialogue), or, if there is none, to add `@chara character variant` before the dialogue (`model/expression.ts`; a character not on screen appears at the default position; ⌘Z undoes it).
The variant field in the parameter panel (parameters of the variant type, such as `@chara` and `@face`) also chooses from the same list of faces once the character is known (with "Not set" at the top if it isn't required). Completion in the code view also shows faces at the start of character and variant suggestions.
Character completion lists the characters that appear near the line (speakers of dialogue and commands that name a character) first, nearest first (`model/cast-ranking.ts`; it looks past branches and right after them as the same scene, and stops at labels, scene changes, and `@jump` and `@return` in the same flow).
For parameters that act on sprites on screen (the `shown` type: built-in and standard commands such as `@chara-hide`, `@chara-move` and `@chara-shake`, plugin commands written with `t.cast(…, { shown: true })`, and macros that first pass the parameter to such a parameter in their body),
the characters shown just before that line go further up with an "On stage" mark, and the other characters stay below them (`shownBefore` in `complete.ts`; it reads the stage played the same way as the cursor line's current position.
`@chara`, `@chara-hide`, `@chara-hide-all` and `@scene-change` written before the current position arrives are applied by the completion first. It doesn't filter, since branches and half-written lines can make it wrong. Lines without a route state use the usual order).
If a plugin has the hook (`suggestAssets`; `docs/plugins.md`), completion of asset values lists up to five assets that fit the scene being written at the top, with a "Fits the scene" mark (`suggest` in `complete.ts`; a source separate from the usual suggestions, which doesn't make you wait even when it's slow).
The list of faces is ordered by the variants the script uses most for that character and sprite set (the counts in `variants` of `GET /cast/usage`; ties and variants not yet used follow the order in `cast.json`).
Click the name on a line of dialogue, or choose "Change speaker" in the right-click menu of a text line, to choose again from the list of speakers (faces and names, with "Narration" last) (`model/speaker-change.ts`).
Changing the speaker of dialogue replaces only the name at the start of the line (`{name …}` and the text stay as they are). Changing it to narration removes the name and the outer brackets or quotation marks (and adds a leading full-width space, the Japanese paragraph indent, if more than half of the narration in that file has one).
Changing narration to dialogue removes the leading space and, if the text doesn't already start with a bracket or quotation mark, wraps it in 「」 (Japanese quotation brackets), or in `""` in a project whose source language is English (the first entry of `languages` in liminalia.json is `en`). Text that starts with a quotation mark gets a half-width space between it and the speaker name. "Emphasize dialogue" next to the name on a line of dialogue (it appears when you hover over the line), or "Emphasize this person's dialogue" in the line's right-click menu, fades every line except that person's dialogue (`speaker-focus.ts`; it only changes how it looks, doesn't change the document and isn't remembered). A text line and the command lines just before it are grouped as a page (only in how they look; wherever you move a command,
pages are redrawn with text lines as the breaks; how they are divided is in `model/blocks.ts`). Labels and flow commands are one row each,
and `@choice`, `@define` and `@script` are grouped into one row up to `@end`. Drag the handle on the left of a line (for a card, the handle that appears on its left when you hover over it), and a copy of that line follows your finger (mouse),
leaving a gap where it will go. The gap moves between lines (inside pages too) to match the height of your finger, and the lines around it slide out of the way (when the OS is set to reduce motion, they are placed without sliding).
Release to drop it into the gap, or press Esc to cancel. Dragging to the edge scrolls automatically. The handle at the top left of a frame moves the whole page
(the gap goes only between pages). Drag a part from the parts panel (opened with the icon above the script), and a gap with the part's name moves in the same way;
drop it to add it there (for a command, the form opens; double-click to add it after the selected line. The "Dialogue" part adds `Speaker「」`, or `Speaker ""` in a project whose source language is English, where the first entry of `languages` in liminalia.json is `en`). Click a selected line again to edit text in place
(Enter confirms, Esc cancels. Home and End move the cursor to the start and end of that line, and with ⌘, or PageUp and PageDown, to the start and end of what is being edited.
On the Mac, Home and End only scroll the list, so while editing they aren't passed to the list), or to open the form for a command. Delete removes it, as does the × that appears at the right end when you hover over a line (and on the selected line) (⌘Z undoes it). Markup inside the text (ruby, line breaks, click waits, inline commands) is rendered as formatting in the blocks (the text itself doesn't change).
Select a range of lines by dragging anywhere except a line's handle (for a card, the card itself), with Shift-click, or with Shift+up and down (⌘A selects all), and copy, cut, paste (after the selected line) and duplicate with ⌘C, ⌘X, ⌘V and ⌘D. ⌥↑ and ⌥↓ move the selected lines past the line above or below (the same in the code view).
Open the list of keyboard shortcuts with ? (when you aren't typing), ⌘/ (outside the code view), or "Keyboard shortcuts" in the "…" menu. The list is built only from the table in `shortcuts.ts`, and is shown with Ctrl+ on Windows and Linux (when you add a key, add it to the table too).
Keys in the code view follow VS Code (⌥↑↓ moves lines, ⇧⌥↑↓ copies lines, ⌘⌥↑↓ adds cursors, ⌘L selects the line, ⌘/ comments it out, ⇧⌘K deletes the line, ⌘D adds the next occurrence of the word to the selection). ⌥PageUp and ⌥PageDown jump to scene headings.
Copied lines can be pasted as text into other apps, and lines copied in other apps can be pasted too. Right-click a line for a menu with the same actions plus "Play from Here" (⌘⌥P), "Go to Jump Target" (F12; only on lines with a jump target), items that open what the line (for a page, every line in it) uses, such as "Open character "Akari"," "Open background "hill.webp"," "Open scene "#night"" and "Open variable "game.x""
(`model/line-refs.ts`: the speaker of dialogue and parameters of the character type, parameters of the asset type (that folder if `folder=` is given), jump targets (except one already covered by "Go to Jump Target," and expressions), and `game.`, `system.` and `temp.` variables; up to 8, each opening on the Characters, Assets, Script or Variables screen), "Add comment" (⌘⌥M), "Breakpoint," "Add to favorites" and "Delete"
(right-clicking the handle on the left of a page applies to the whole page; for a scene heading, "Lines Leading Here" and the scene actions are included too). Lines added to favorites are listed under "Favorites" at the top of the parts panel (kept per project in `favorites` in `.liminalia/studio.json`, and not included in the game; favorites from before, which were kept in localStorage and shared across projects, are copied once to the end of the project's favorites when a project is opened (identical sequences of lines aren't copied; `favorites.ts`)).
Like parts, they are added by dropping or double-clicking, and removed with a right-click.

**Keyboard and screen readers** (checked by `dev/verify-a11y.ts`):

- The block view's list is a single place for input that selects lines (a listbox). Lines are options; the up and down arrows move between them, and the selected line is announced with `aria-activedescendant`.
  The name read out is "speaker, text" for dialogue, the text for narration, the name and summary (the card's text) for command cards, "Scene #name" for scene headings and "Choice, …" for choices. Pages are groups of lines
- The "…" and × buttons on lines and the button that emphasizes a speaker aren't in the Tab order. Shift+F10 (and the menu key) opens the right-click menu of the selected line, and Esc returns to the list
- F6 and ⇧F6 move focus through scenes, script, preview, thumbnails and the top bar in that order (closed panels are skipped; on other screens, between the top bar and that screen)
- Only one row of the scene list (folders, files, scenes, New file) is in the Tab order (the current scene or the current file). ↑↓ move to the previous and next row, ← → collapse and expand files and folders
  (moving inside when already expanded; ← on a scene goes to its file), Home and End go to the first and last row, and Shift+F10 (and the menu key) opens the row's menu. The fold, "…" and + buttons on a row aren't in the Tab order
- "/" opens the list for choosing a part to add after the selected line (the same panel as ⌘K). "Insert part…" in ⌘K does the same (after the cursor line in the code view)
- Parts in the parts panel are buttons, and Enter or Space adds the part after the selected line. Enter in the search box adds the best match, and ↓ moves into the parts (arrows move between parts)
- In the flowchart, entering the canvas selects the card of the scene with the script cursor, and the arrows move to the nearest card in that direction (scrolling it to the middle if it isn't visible).
  Enter goes to that scene's script and Shift+F10 opens the card's menu. The selected card has a dashed outline and is announced with `aria-activedescendant`

**Spell check**: in projects whose source language isn't Japanese (the first of `languages` isn't `ja`), only the text of dialogue and narration is checked (`editor/spell.ts`; the code view marks that text with
`spellcheck="true"`, and command lines, speaker names and comments aren't checked; the block view checks while editing in place). Japanese projects aren't checked.
The desktop app turns spell checking on in project windows, sets the dictionary language to the project's source language (on a Mac, the OS works out the language), and adds suggestions and "Add to dictionary"
to the right-click menu of misspelled words (`studio-desktop/src/main/spellcheck.ts`). `lim studio` in a browser uses the browser's spell checking and right-click menu.

Lines in the block view also show the same comment and breakpoint marks as the code view (`block-marks.ts`; it keeps no state of its own and refers to the code view's marks; the marks sit to the left of a line, at the top left of a card, and to the left of a choice).
Click a comment mark to show its thread in the right panel, and click a breakpoint mark to remove it. Breakpoints stop at command lines, so right-clicking inside a choice puts the breakpoint on the `@choice` line (a comment goes on the choice line you clicked).

Parts are arranged in sections (Common, Text, Flow, Backgrounds and screen, Sprites, Sound, Motion, Progress and system, Custom commands). Each section opens and closes with its heading (remembered).
Inside a section, cards with an icon in the section's color and a short name are laid out in 2 columns
under subgroup headings (for Backgrounds and screen: Background, Fades and color, Shake and camera, Weather and particles and so on; `group` in `command-meta.ts`) (names wrap to at most 2 lines; the `@command-name` and long names appear on the description card shown on hover).
For built-in and standard commands, the description card (it stays when you move onto it), the right-click menu of a part and the parameter panel show "Learn more,"
which opens the command reference on the site (`/reference/<name>/`).
Rarely used commands such as waiting, stopping and resetting (`advanced` in `command-meta.ts`) are collapsed under "More commands" at the end of the section (whether it is open is remembered).
"Common" lists recently added parts (up to 6; `liminalia.studio.recentParts`) under "Recently used" and a fixed set of parts under "Everyday."
The Scenes and Parts panels close with the close button in their heading, and after closing, click the name (trace) left at the edge to open them again (in the phone app, the parts panel opens with the button in the script bar).

Custom commands are commands added by plugins. When two or more share the same first part of their name (such as `fx-`), they are grouped under that prefix
(where each command comes from is in `commandSources` in `/project`; if a plugin writes `category` in a command definition, the command is listed in that section).
The sections, the words for what you want to do and the moving previews of the built-in commands are all in the engine's `packages/lang/src/command-meta.ts`.

Searching with the field at the top removes the sections and lists the results under "Matching parts" in order of relevance: matches by name, then by words for what you want to do (such as shake, fade to black and rain;
`keywords` in `command-meta.ts` and the `keywords` of plugin commands), then by description, parameter description and syntax example.
It ignores the difference between katakana and hiragana and between upper and lower case.

Hover over a command part to show a description card beside it (description, syntax example, main settings). For commands with a sample line (`preview`) in `command-meta.ts`,
a small preview using the project's first background and its first character with variants runs that command over and over to show it (the game's `/?ui-preview=command&cmd=<command-name>`).
When there is no background or character, a short note says the sample can't be shown. Command forms also show the syntax example below the description.

Script files are handled with "New file" at the very bottom of the scene list and with the menu from a file name's "…" or a right-click (Add a scene, New file, Duplicate, Rename, Move to trash).
Names use letters, digits, `_`, `-`, and `/` to separate folders. Renaming a file also moves the jump targets in other files (`@jump`, `@call`, `@use`, choices, jump target parameters;
also jump target parameters in `{@…}` in text, and the strings in `visits("file#label")` and `read("file")` in expressions) and the change history, and if it is the "New game" file, rewrites `entry` in liminalia.json too (the game picks it up after a restart).
Other places that hold the file name are moved too: `afterLoad` in liminalia.json, the `target` of extras recollections and chapters, flowchart title keys, initial values of variables used as jump targets,
`files` in `chapters` (names without wildcards; you are told when a wildcard won't match the new name), the keys of `scenes`, `check.sound.quiet`, the keys of translations and `voice-lock.json` (`file:…`),
script tests (the places in `from` and `expect reach` in `tests/*.limtest`, and `visits` and `read` in expressions),
threads in `reviews/`, bookmarks, breakpoints and `lastOpen` in `.liminalia/studio.json`, `mapPositions` in `.liminalia/shared.json`, and the baseline images of `lim regress`.
Renaming a scene, a variable or a speaker name rewrites script tests too (`file#label` for scenes, the expressions of `set` and `expect` for variables, and `expect text` compared with the speaker name for speaker names).
If saving fails partway through a rename (of a file, asset, variable or character), what was already saved is put back before the failure is returned (`server/undo.ts`; the same as renaming a scene; anything that couldn't be put back is named).
The rewriting of scripts and settings is in `client/model/name-rename.ts`, and `lim rename` and renaming in the VS Code extension use the same code. Renaming a character also rewrites `{@chara …}` in text,
and for lines whose text was rewritten (`{= variable}`, `{@chara …}`, `{img …}`), translation keys and `voice-lock.json` keys are moved to the new key of the same line (variable names inside translations are changed too).
Rename a macro (`@define`) with "Rename macro" in ⌘K when the cursor line is a macro, or with "Rename macro…" in the menu of "Lines using this macro"
(`POST /macros/rename`; the same `renameMacro` in `server/manage.ts` as `lim rename macro` and F2 in VS Code. It rewrites `@define` and the calls, `{@…}` in text and the keys of `commandDefaults`).
When `@define` with the same name is in two or more files, "@define to rename" above the name field chooses which file's one to rename (it starts at the file of the cursor's `@define` line,
or the one a call from the open file reaches). Only that file and the files whose calls reach that file's `@define` are rewritten (files without their own `@define` where that file is the first `@use` that has it, the same as the player),
and the key in `commandDefaults` is copied to the new name, keeping the old one.
A file moved to the trash can be brought back with "Undo" in the notice or on the "Trash" screen (the "New game" file can't be deleted).

**Scene actions** are the same wherever you open them: the "…" or right-click of a scene row in the scene list, a scene heading in the block view or a flowchart card, or the script heading menu (for the cursor's scene) (`sceneItems` in `app.ts`; the logic is in `editor-actions.ts`):
"Edit tags and status," "Rename scene," "Duplicate scene," "Move to another file," "Split the file from here" and "Delete scene." In read-only files, only tags and status can be used.

- Edit tags and status: gives the scene a status (Draft, Needs review, Reviewed), a color (red, yellow, green, blue, purple, pink, gray) and tags (separated by commas; tags already in use are suggested)
  (`scene-marks-dialog.ts`; the scene at the top of a file can have them too). They are kept in Studio's shared data (`sceneMarks` in `.liminalia/shared.json`, keyed by the same scene id as the flowchart,
  `file#label`, or `file` for the scene at the top of a file) and go into neither the game nor the .lim files. Renaming the scene or the file and moving the scene to another file change the key too.
  The scene list shows a dot before the scene name (the color if set, or else the status color: gray for Draft, yellow for Needs review, green for Reviewed; hover to see the status, color and tags),
  and the menu at the top of the list (shown only when some scene has tags or a status) filters by all, scenes with tags or status, a status, a color or a tag (while filtering, matching scenes are listed even in files that aren't expanded).
  The flowchart shows the same dot before the card name and the status and tags over the bottom left of the picture, and filters the same way with a menu in the top bar. ⌘K also finds them by status name and tag (`#tag`) (`model/scene-marks.ts`)

- Duplicate: puts a copy at the end of the file with the name `name_2` (the first free number). It is an editor change, so ⌘Z undoes it. It doesn't change the flow:
  if the original scene ran straight on into the next scene, `@jump #next-scene` is added at the end of the copy, and if the last scene of the file stopped at the end of the file, `@stop` is added at its end
- Delete: deletes the scene's lines (it is an editor change, so ⌘Z and "Undo" in the notice undo it). If lines that lead to this scene remain, the notice includes how many (they appear in the check as jump target errors)
- Move to another file: asks for the destination file (existing files are suggested; a name that doesn't exist creates a new file, and "New file" appears below the field; folders such as `part2/rest` can be created too),
  and moves the scene to the end of that file (`POST /scenes/move`; the text is assembled in `model/scene-move.ts`, and the files are handled in `server/scene-move.ts`)
- Split the file from here: moves everything from that scene to the end of the file into a new file (it asks for the name; the default is `file_2`). Otherwise it is the same as Move to another file

What is rewritten when a scene is moved (the same mechanism as renaming a scene; `toFile` in `LabelTarget`):

- Jump targets anywhere in the project that point to the moved scene (`@jump`, `@call`, choices, expression candidates and `to=`, jump target type parameters, `{@…}` in the text, `data-jump` in `@html`) are pointed to the destination.
  `#scene` in the original file becomes `destination#scene`. A `#scene` put in a variable is resolved in the file doing the jump, so after a move it always becomes `file#scene`
- Among the `#label`s inside the moved scene, those that point to scenes staying in the original file become `original-file#label` (those that point to scenes moved along with it stay as `#label`)
- The flow doesn't change: `@jump destination#scene` is added at the end of a scene that ran straight on into the moved scene; if the end of the moved scene ran on into the next scene, `@jump original-file#next-scene` is added; and
  if the last scene of the destination file stopped at the end of the file, `@stop` is added at its end (the notice shows how many lines were added; whether a scene runs on is judged the same way as "Continues" in the flowchart)
- The `@use` lines of the original file, and the original file's macros that the moved scene calls (`@use original-file`), are added at the top of the destination
- `liminalia.json` (`entry`, `afterLoad`, extras recollections and chapters, flowchart titles, initial values of variables), `mapPositions` in `.liminalia/shared.json`, and the names of the `lim regress` baseline images
- The keys of translations and `voice-lock.json` (keys are made from the file and the original text, so the keys of moved lines are copied to keys for the destination file, and the original keys are removed if nothing uses them anymore). Threads in `reviews/` attached to moved lines move to the destination lines, and so do the marks in `bookmarks` in `.liminalia/studio.json` attached to moved lines
- References that couldn't be rewritten (inside `@script` and so on) are reported in the same list dialog as for renaming. The open file is updated to the rewritten content while keeping its undo history

Studio refuses when the scenes aren't next to each other, when the scene is at the top of the file, or when the destination has a scene with the same name (rename it first). If the destination or original file was changed elsewhere, it refuses without writing anything.
If saving fails partway through, what was already saved is put back, as with renaming (files it created are deleted). Saves (file and command numbers) and read marks shift by the moved lines, as with any other edit.

Rename a scene (label) with "Rename scene" in the scene actions (`POST /labels/rename`; the text is rewritten in `model/label-rename.ts`, and the files are handled in `server/labels.ts`).
Invalid names and duplicates within the same file are refused, with the reason shown below the field. It can't be used in read-only files. What it rewrites:

- Scripts (through the write API, so they are kept in the change history): label lines, `@jump`, `@call`, choice jump targets (both `#label` in the same file and `file#label`), strings inside jump targets given as expressions and `to=` candidates, `@set` and `@let` that put strings in variables used as jump targets,
  jump target type parameters (including `{@…}` in the text), `data-jump` in `@html`, and the strings in `visits("#label")` and `read("file#label")` in expressions. A `#label` put in a variable (and the initial values in the settings) is resolved in the file doing the jump, so it is rewritten only when the project has just one label with that name; if there are others, it isn't rewritten, and you are told.
  Macro (`@define`) parameters and defaults have no target type, so only `file#label` is rewritten, and `#label` is left as it is, and you are told
- `liminalia.json`: `entry`, `afterLoad`, the `target` of `extra.replay` and `extra.chapters`, the keys of `extra.flowchart.titles`, initial values of variables used as jump targets, the keys of `scenes`, and `check.sound.quiet`. If `entry` or `afterLoad` is rewritten, the dev server's current position data and the flowchart use the new place right away, and the game picks it up after a restart (you are told so)
- Script tests (`tests/*.limtest`): `file#label` in `from` and `expect reach`, and `visits("file#label")` in the expressions of `set` and `expect`. `visits("#label")` without the file has no file to resolve it in, so it isn't rewritten, and you are told
- `mapPositions` and `sceneMarks` in `.liminalia/shared.json` (keyed by `file#label`), and the baseline images in `.liminalia/regress/baseline` (named `file_label.png`)

`liminalia.json` is saved only when its content changes. If saving fails partway through, what was already saved is put back before the failure is returned (scripts go through the write API, so the writes that put things back are also kept in the change history; anything that couldn't be put back is named).
- The line content of threads in `reviews/` attached to rewritten lines
- The keys of translations (`lang/*.json`) and `voice-lock.json` are made from the file and the original text, so they have no labels. Only lines where a `{@…}` jump target in the text was rewritten have a changed original text, so the keys of those lines are replaced (jump targets inside the translated text are rewritten too)

Things left alone because they hold no labels: saves (file and command numbers), read marks (keys made from the file and from the speaker and text of each page), the change history, `lastOpen` and breakpoints (they follow the line content). The flowchart records left on players' devices (`scene:<id>`, where the id is `file#label`) can't be rewritten from Studio. References that can't be rewritten (inside `@script`, jump targets decided by expressions such as a string put in a variable being used as a jump target in another file,
jump targets a plugin command takes from project data, files that were changed elsewhere and couldn't be saved) are reported in a list dialog; click one to go to that line. The open file is updated to the rewritten content while keeping its undo history.

"Import text" above the script makes dialogue and narration lines from text or a table (CSV or TSV; a table copied from a spreadsheet is fine) and inserts them.
`Name「…」`, `Name "…"`, `【Name】…` and `Name: …` become dialogue (wrapped in 「」 if there are no brackets or quotation marks, or in `""` in a project whose source language is English), and everything else becomes narration (you can choose whether to add a full-width space, the Japanese paragraph indent, at the start).
For a table, it uses the column headed "名前" or "話者" (or name, speaker) and the column headed "本文" or "セリフ" (or text). `{`, `}` and `\` in the text, and `@`, `#` and `//` at the start of a line, are escaped, and lines already written in .lim syntax
pass through as they are. Ruby written with 《》 (`｜base《reading》` and `kanji《kana reading》`) becomes `{r base|reading}` (brackets around titles such as 「絵画《星月夜》」 are left alone). You can choose whether to add names that aren't speakers yet as speakers, and whether to insert after the cursor line or make a new file (⌘Z undoes it).
Choose Ink, Yarn Spinner, Ren'Py or Twine (Twee 3) in the format (or drop a `.ink`, `.yarn`, `.rpy` or `.twee` file, or let it detect the format automatically),
and it converts to .lim with labels, choices, conditional branches and variables, using the same conversion as `lim import-ink` / `import-yarn` / `import-renpy` / `import-twine`.
It converts into a single file, writes variable initial values as `@set` at the top, and turns parts that can't be converted into comments, showing how many and why alongside
([ink-yarn-import.md](ink-yarn-import.md)). Characters shown with Ren'Py's `show` are listed alongside so you can add them as characters (`lim import-renpy` adds them to cast.json automatically).

The Scenes, Parts, Preview and Thumbnails panels open and close with the close button in their heading and the trace at the edge (Scenes, Preview and Thumbnails also from the "…" menu). "Enlarge" is in the preview heading. The timeline collapses with the chevron in its heading (all of this is remembered;
the timeline and the parts panel are closed at first). The widths of the scene list and the right panel can be changed by dragging the border (remembered; double-click for the original width;
the width of the right panel while enlarged is remembered separately).

From the top, the right panel has the preview (16:9), the row of controls below it (Pause, Resume, Mute, Cursor sync, device, screenshot, New window, Full screen), the line and route display, the parameter panel, the current state of the preview (background, BGM, sprites and looping sound effects, one per row, with the line that set each; click one to go to that line),
then, below a divider, the variables (each value and the line that last set it) and the timeline. The list of variables is closed at first; click "Variables" to open or close it. While paused, the same button changes to the resume icon. Click the preview to move the story forward.

Put the cursor on a command line, and the parameter panel for that line opens on the right; moving to another command line switches its contents. Moving to a text line or similar closes it. Commands inside text are edited by clicking their tags, as before. On a phone, moving the cursor alone doesn't switch the screen.
In the code view, hovering the pointer over a command's argument shows that argument's type, default and description. This also works for shorthand true/false values such as `solo`, values such as `at=left`, and unnamed arguments.
While you're typing, popovers with descriptions or diagnostics shown for another line close. The description for the line being edited stays.

**Trying values in the preview**: while the preview shows text or choices (including while it is stopped at a breakpoint or paused), click the value on a variable's row in the right panel to change it on the spot (Enter or clicking outside confirms, Esc cancels;
numbers, `true`, `false`, `null`, `"…"`, `[…]` and `{…}` are read as they are, and anything else as a string; if the current value is a string, it stays a string even if it looks like a number). This changes only the values of the runner running in the preview (`game.`, `temp.`, `system.`), and nothing at all is saved to files or initial values.
A changed row gets a "Changed" mark (click it to go back to the original value), and the script cursor moves to the preview's line and is drawn with "State at this line (preview)." Resume or click the preview to move forward, and branches follow that value.
If the script puts a different value in the same variable, the mark goes away. If you move the cursor and the preview is rebuilt, changed values go back to the values at that point, and a short note above the variables says so.
Values can't be clicked while the preview shows a command line (where the runner doesn't move forward). `system.` rows show what the preview's runner holds (`content_filter` and `packs`, which the engine sets itself, only when the script uses them or you changed their values) (`temp.` only shows the preview runner's values when the state was reached by moving the preview forward).

**Thumbnails** lists the text and choice pages of the open file side by side, each as a small preview of the background and sprites at that page (built from the duration bars).
Below each are a dot in the speaker's color (gray for narration, violet for choices) and the line number, and label names at scene breaks. The page of the cursor line (that line's page, or the next page) is marked;
click a page to go to that line.

## Flowchart

**Flowchart** is an overview of the branches, made from the script. Scenes (the top of each file, and each stretch from one label to the next) are cards (that scene's background and the images of its characters,
"#label" and the first line of text), and how scenes connect (continues, `@jump`, `@call`, choices, commands with a jump target; conditional if inside `@if`) are lines.
They are stacked from top to bottom in story order, file by file (built by `GET /map`, laid out by `model/map-layout.ts`). For projects where the stacked height exceeds 4,000px and
wrapping into columns in story order makes everything look at least 1.5 times larger when fitted (projects with many files), the files are wrapped into columns placed side by side
(`wrapColumns`; it tries a column height limit at each file boundary and picks the one that fits largest in a panel with a 1.6:1 width-to-height ratio). Lines to the very next file in the same column go down,
lines that skip ahead or go back within the same column go around the right of the column, and lines to other columns cross on curves. Turning off "Wrap" in the top bar goes back to a single column (it appears only for projects that can wrap; remembered in the browser).
The positions of scenes you moved are remembered in the coordinates of the single-column layout, and when wrapped, they are shifted along with their file's block (positions you moved before still work).
Lines from choices are labeled with the choice text,
and `@call` is a dotted line. Lines that go back to an earlier scene, such as investigating or choosing again, become loops around the right of the card. Each time it opens, the scene where the script cursor is
is highlighted and centered, and the scenes and lines of the route you chose are emphasized. If the all-routes test (Check) has been run, scenes that weren't reached are faded. Click a scene
to go to that scene's script. Drag the background to move the whole chart, and drag a card to move just that scene (moved positions are remembered in `.liminalia/shared.json`;
"Reset position" in the right-click menu puts it back where it is placed automatically). "Play from Here" in a card's right-click menu starts a test play from the beginning of that scene, and "Lines Leading Here" lists the lines that lead to it.
A card's right-click menu (and "…") also has the scene actions (rename, duplicate, move to another file, split the file from here, delete), and after a rewrite, the flowchart is redrawn without moving the view.
You can build on the flowchart (the text is rewritten in `model/map-edit.ts`; the open file receives editor changes, and ⌘Z and ⇧⌘Z on the Flowchart screen undo and redo; see "Undo on screens" below):

- Draw a line: hover over a card, and a handle appears in the middle of its bottom edge. Drag the handle and release it on another card to write a line that goes to that scene. A scene that ends with choices gets one more choice
  (its text is the target scene's name; edit it later), a scene that ends with `@jump` gets its jump target changed, a scene that ends with `@stop` has the `@stop` changed to `@jump`, and a scene that runs on into the next gets an `@jump` added at its end
  (before any trailing comments). Lines can't be drawn from scenes that end with `@return` or a command that ends the play (you are told so). The jump target is `#scene` in the same file, and `file#scene` otherwise
- Delete a line: hover over a line to thicken it, and right-click for "Open the line" and "Delete line." It deletes the `@jump` or `@call` line or the choice line (if it is the only choice, from `@choice` to `@end`),
  and for a line that continues to the next scene, it adds `@stop` at the end of the scene. Lines decided by commands can't be deleted
- Add a scene: right-click the background and choose "Add a scene to start.lim" or similar (the file is the nearest one above the clicked height in the clicked column). It asks for a name, adds `# name` at the end of that file, and places the card where you clicked
  (the position is remembered like a moved scene). If the last scene stopped at the end of the file, `@stop` is added so that it doesn't run on into the new scene. Zoom in and out with ⌘ / Ctrl + wheel or ＋ −, and search by label name or the start of the text with "Find a scene."
"Fit all" zooms so that everything (when filtered, the matching scenes) fits. It doesn't go below 10%, though; when things don't fit, it shows the start of the story (top left)
and shows where you are on the overview at the bottom right (＋ − and the wheel zoom out to 4%; below 35%, ＋ − step by 1.4 times).
Below 20%, cards become filled rectangles without images or text (and their image sources aren't fetched), lines keep their thickness, and file names stay at a readable size,
drawn over the top edge of that file's cards.
When not all cards are visible, an overview appears at the bottom right (dots for scenes, the current scene, scenes matching the search, scenes matching the filter, and the visible area); click or drag in it to center that spot.
Filter with the selections in the top bar: file (choosing a folder selects all the files under it), character (people who speak in that scene; `GET /map/cast`), tags and status (see "Edit tags and status" above; shown only when some scene has them), "Unreached" (scenes the all-routes test didn't reach; disabled if it hasn't been run) and "Endings" (scenes where the play ends).
The layout doesn't change; scenes and lines that don't match fade, the count is shown as "N / M scenes," and it zooms so that the matching scenes fit (not remembered).
The card images are built from the duration bars (`GET /sweep/stage`), fetched only for files whose cards come into view. For a scene that shows choices, the card shows the background and characters
at the point where the choices appear rather than at the start of the scene. A card image is the background at one point and the characters on screen at that time (characters who appear later in the scene aren't layered on).
Scenes where the play ends (the end of a file, `@stop`, a command that ends the play; `ends` on the command) get an "End" mark (or, if the command's `ending` parameter is given, its kind and
the name in `title`, such as `bad "Silence"`), and no line is drawn to the next scene.
"Endings" in the top bar opens a panel listing the scenes where the play ends (`endings-panel.ts`; built from the same `GET /map` data, with no separate calculation). It shows the kind and name of the ending (or "End" if there is none), the file and scene, and whether it is reached (the result of the all-routes test, with the number reached for each kind, if it has been run; if not, it says so).
Click one to center that scene and mark it. The Check screen also shows the number of endings and "See the list."
For plugin commands whose jump target is decided by data, arrows are drawn using what the command's `targets` reports it might jump to ([plugins.md](plugins.md#命令commands)).

Switches within a screen (character settings and position, variable kinds, the project's basics, extras, translation and export, comment filters) are all placed to the right of the screen's heading row.
Asset kinds and plugin pages are many and keep growing, so they are listed in the left panel.

## Characters and assets

**Characters** is the standard screen for characters (`cast` in cast.json and the names in dialogue). Switch between "Settings," "Lines" and "Position" to the right of the heading.
"Change history" to their right compares the change history of cast.json (the content before each rewrite; 20 entries in `.liminalia/backups/cast-<date-time>.json`) with the current content line by line, in the same panel as the script's change history
(`GET /cast/backups`). "Restore this content" saves the characters and speakers at that point through the same API as normal saving (`POST /__liminalia/api/cast` of the position adjustment screen),
so the content before restoring is also kept in the change history, and in projects made by importing, it is also written back to the import source.
"Settings" shows the list of characters on the left (`cast` in cast.json, with the face, name, number of lines of dialogue and number of script lines; sort by most appearances, fewest appearances, name A–Z or name Z–A, and the choice is remembered), and on the right a large panel for the selected character
(on a background in the character's color: the sprite, character ID, display name, name color, the look of the dialogue text, default sprite set, notes and the list of expressions).
"Add a character" below the list takes the display name (the name shown in the game as the speaker) and the character ID (the name used by `@chara` in scripts and for the sprite folder).
If the ID is left empty, it is made from the display name (kana and letters become romaji, the same as project IDs, so "アカリ" becomes `akari`; a name that can't be romanized, such as kanji, is used as is; `_2` is added if it is taken; `model/cast-id.ts`).
If the display name and the ID differ, `speaker` is written for that character in cast.json.
"Notes" holds background, voice actor and so on. It is saved in `castNotes` in `.liminalia/shared.json`, not in cast.json or the game data (it saves when you leave the field, and moves along when the character ID is renamed).
"Base variant" above the list of expressions chooses the variant used when none is given (`defaultVariant` of the sprite set) (when there are two or more variants).
Each variant in the list of expressions shows the number of script lines that specify it (parameters of the variant type, such as `@chara`; a line that omits the sprite set counts for the default sprite set if that set has the variant; `variants` in `GET /cast/usage`).
Variants other than the base variant that are never specified are shown as "Unused" with a faded image, and their count appears next to the heading (the base variant appears without being specified, so it isn't called unused even at 0).
"Face position" decides which part of the sprite is cropped for the faces shown in the scene list, the script, the flowchart and so on (drag to move it, and change the size with the wheel or the slider;
it is saved in `faces` in `.liminalia/shared.json`, not in cast.json). Changing the character ID or the display name also rewrites the references in the script (parameters of the character type, the names at the start of dialogue lines)
(the script's change history is kept). When you change the ID of a character whose display name is the same as the ID, Studio asks whether to change the display name too ("Change both" or "ID only").
For the character ID, the face crop (`faces`), the notes (`castNotes`) and the system voice assignment (`character` in `ui.systemVoice`) move along too;
for the display name (speaker), the speaker names in translations (`speakers` in `lang/<language>.json`) and `voice-lock.json` (its keys are made from the speaker and the original text, so the numbers are moved to the new keys of the same lines) move along too. Drop an image onto the list of variants to add a variant, positioned and sized by comparing its non-transparent area with that of the base variant (normal, default, or the first one)
(the image is placed in the same folder of `fgimage/` as that character's images). "From assets" makes variants from images already in `fgimage/`, positioned and sized the same way
(the images aren't copied; images in that character's folder come first, then images not used anywhere, and images used by other variants show that character; `variant-pick.ts`).
In the desktop app, "Add variant" opens the file dialog in that character's image folder (or where you last chose sprites in this project).
Changes on this screen (adding, variants, colors, names and so on) are undone with ⌘Z and redone with ⇧⌘Z (added images too; see "Undo on screens" below). Select a variant to replace the image, rename it,
set the overlay images for lip sync and blinking, delete it, or use "Adjust position." The name color applies to the name box in the game (including names in NVL).
The dialogue text color, the text font, italic dialogue, the name box image and the message window image apply only to that character's dialogue (`text`, `nameImage` and `windowImage` in cast.json).
"Sprite motion" chooses how that character's sprite is drawn (`model` of the character in cast.json): None, Sway (`sway`), Live2D or Spine. For Live2D and Spine, "Model file" chooses
a `.model3.json` (Live2D) or a `.skel` or `.json` (Spine) in `fgimage/`. If that plugin isn't installed, or there is no model file in `fgimage/`, the choice is put back without writing cast.json,
and Studio suggests installing the plugin or adding the file to the assets ([live2d-spine.md](live2d-spine.md)).
Selecting a variant of a Live2D or Spine character shows a "Sprite motion" panel for choosing that variant's expression and motion (Live2D), or animation, skin and loop (Spine) (`model` of the variant in cast.json).
The choices are the names read from the model file (`Expressions` and the `Motions` groups of `.model3.json`, plus "group:number" for groups with two or more motions; `animations` and `skins` of a Spine skeleton `.json`).
"Same name as the variant" writes nothing for that field, and "None" writes `""`. When only `type` is left, the variant's `model` is removed. For a `.skel`, whose names can't be read, you type the names.
"Layered sprite" in the variant actions opens a dialog for editing the layered sprite of the selected sprite set (`layers` of the sprite set in cast.json and `parts` of the variants; the shapes and rules are in
cast.ts of `@liminalia/lang`) (`parts-editor.ts`; the operations are in `model/parts.ts`). On the left are the layers (listed with the front one at the top;
add with "＋," reorder by dragging rows, or move with "Bring forward" and "Send backward"), the images of the selected layer (put in `fgimage/<character-folder>/<sprite-set>/<layer>/` with "Add images" or by dropping;
listed as small images cropped to their non-transparent area), the default image, rename and delete; in the middle, a preview of the selected variant with its layers stacked; on the right, the list of variants and the image per layer for the selected variant
("Default (…)" uses the layer's default without writing it in `parts`, and "None" hides that layer). Clicking an image thumbnail also sets that layer's image for the selected variant.
"＋" on the variants makes a new variant that copies the `parts`, position and size of the selected variant (or starts from empty `parts` if a single-image variant is selected). Every operation saves to cast.json right away.
Removing an image from a layer keeps the image file. Dropping a PSD onto the list of variants (PSD import) also produces these layers and variants.
Layered sprite variants are drawn with their layers stacked in the sprite, the list of variants and the face position too.
"Position" embeds the sprite position adjustment screen (the dev server's `/__liminalia/cast` with `?embed=1`; in the phone app, the Service Worker serves it) as it is. It edits and saves the positions and sizes of sprites in cast.json.
When the tab opens, it selects the sprite shown at the script's cursor line (the frontmost one). Unsaved changes on the position screen are saved before the window closes, on ⌘S,
before "Refresh" and when you go back to "Settings." Both kinds of writes go through the same API as the position adjustment screen, so the content before the change is kept in `.liminalia/backups/`,
and in projects made by importing, it is written back to the import source. "Project → Adjust Sprite Positions" in the desktop app's menu also opens this tab.
"Lines" lists the dialogue of the character selected in the list on the left, in file name order and line order (`speaker-lines.ts`; the names in dialogue are looked up the same way as for the dialogue count in the list). Filter with the text in the field at the top (words separated by spaces must all be present; it ignores the difference between katakana and hiragana and between upper and lower case),
and click a line to go to that line in the script.

**Assets** is the standard screen that lists the contents of the asset folders (backgrounds, sprites, images, BGM, sound effects, voices, videos, and any asset folders the project added).
Choose a kind on the left and browse its folders in the middle (typing in the search field searches everything of that kind). Click an asset to show on the right a preview and the size of the image, sound or video, and
where it is used (script lines, characters, project settings); click a line to go to that script, or a character to go to the Characters tab.
Renaming an asset ("/" moves it into a folder) also rewrites the script lines and character sprites that refer to it, the asset references in `ui`, `extra` and `items` of liminalia.json,
and the head marks (`heads` in `.liminalia/shared.json`, for sprites) (whether a setting is a reference is decided by whether `uiAssetReferences` and similar functions list it as an asset of that kind, so colors and text with the same characters aren't changed; references that couldn't be rewritten are reported).
"Move to trash" moves the asset to `.liminalia/trash/`, and it can be undone right there. Drop files or click "Add files" to add them to the open folder
(in the desktop app, the file dialog opens in the open folder, or where you last chose that kind of asset in this project; remembered in `asset-pick.json` in the app's userData).
Renaming, moving to trash and adding are undone with ⌘Z (the rewritten references and an overwritten file come back too; see "Undo on screens" below). "Use as a character sprite" on a sprite image
chooses a character and sprite set and makes the image a variant (the same as "From assets" on the Characters screen).
The assets folder can also be outside the project with `paths.assets` in `liminalia.json` (`"../shared-assets"`, another disk, or the absolute path of a shared folder), and the assets folder itself or folders inside it can be symbolic links to outside places (the dev server adds the assets folder and the targets of the links inside it to the places it may serve, so assets that a plugin's CSS `url()` or `import` points to can be read too. No other places are added; `packages/web/dev-allow.ts`).
Use it to share large assets in an outside place instead of Git. The list, previews, adding, renaming, the check and exports use the outside folder as it is,
and moving to the trash (the project's `.liminalia/trash/`) and restoring copy and then delete the original when it's on another disk (`moveAcross`). The phone app can't read an outside folder, so it says so.
"Add sample assets" in the "…" menu copies the assets of the `lim new` template (CC0 1.0: backgrounds, sprites, BGM and sound effects) (files with the same name aren't copied; a note about the assets, "素材について.txt," is placed too, or the English sample's SAMPLE-ASSETS.txt in a project whose source language is English;
`server/samples.ts`; the phone app doesn't have the template's files, so it isn't shown). "Make placeholder assets" makes, on the screen, a plain background (the size of the game screen) and
a person-shaped sprite (90% of the screen height) as PNG files and adds them (`placeholder-assets.ts`; `placeholder-bg.png` and `placeholder-person.png`, numbered if they already exist).
Kinds with no assets show the same two buttons below the empty-state text.
"Export the asset request list" writes the assets, sprite variants and unrecorded voices that the script and characters use but that don't exist, with the line where each is first used (from the "New game"
file, in line order), that line's text and the number of uses, to `exports/asset-requests.csv` (with a BOM so it opens in Excel) (`server/asset-requests.ts`).
The desktop app opens the folder, and a browser shows a download (`GET /assets/requests.csv`).
For missing images, the dev server returns to the player a tag with the asset's name written on it (SVG; the size of the screen for backgrounds, person-shaped for sprites), so the preview and test play don't stop
(`server/missing-placeholder.ts`; it isn't returned for Studio's own thumbnails). Exporting (`lim build`) still stops with an error for missing assets, as before.
"Unused only" and "Heavy only" above the list filter from all the folders of that kind (the counts of the kinds on the left become the matching counts; pressing both shows assets that match both).
Unused assets are judged by `/assets/usage` (commands in the script and inside the text, the numbered files of `@voice-auto`, characters, project settings). An asset not found that way is treated as possibly in use and not counted as unused if its file name (with or without the extension) appears as a word in the text of any script, `liminalia.json`, `cast.json`, `themes/*/theme.json` or the `.json` files in `paths.data`; its usage shows "Text match" (macro parameters, strings in variables, strings in conditions, themes, `build.winIcon` and so on). Only assets whose names are assembled inside plugin code can't be detected, so instead of a firm verdict it says "The name doesn't appear in scenarios, characters, settings, themes, or data."
What counts as heavy is set by the constants in `model/assets.ts`: images over 5MB, or with a side more than 3 times that of the game screen (the dev server reads the size from the start of the file; for files it can't read, and in the phone app, only the bytes are considered), BGM over 30MB, and sound effects over 5MB. Voices and videos aren't checked.
While filtered, you can select several with the tile checkboxes and "Select all," check the count and total size, and then move them to the trash (they go in under one id, so a single "Undo" brings them all back, however many there are).
**Check** shows "N heavy assets" as information when there are heavy assets; click it to go to the Assets screen filtered to heavy ones (it doesn't count toward the number of problems or the result of `lim check`).

Select a BGM track to show its waveform, playback and playback position, and markers for the start and end of the loop in the right panel (`waveform.ts`; the logic is in `model/bgm-loop.ts`; the audio is decoded with Web Audio, drawn on a canvas, and played with an `AudioBufferSourceNode` loop, the same as in the game).
Click the waveform to move the playback position. Besides dragging, the markers can be set with the arrow keys (10ms; 100ms with Shift) and the seconds fields. "Listen to the loop seam" plays from 3 seconds before the end, goes back to the start of the loop, plays 3 seconds and stops.
The markers start at the position written on the first line in the script, or else the LOOPSTART and LOOPLENGTH embedded in the OGG (`readLoopTags` in `@liminalia/lang`, the same as the player uses), or else the beginning and the end.
The `@bgm` lines that use the track are listed (leaving out lines with `loop=false` and lines that choose the track with an expression), and you are told if the values differ from line to line. "Save to scenario" shows the lines to be rewritten with the lines around them, then rewrites `loop-start` and `loop-end` through the write API
(removing the parameter if it is the same position as when omitted). The audio file isn't changed. Press ⌘Z on the Assets screen to undo this save (⇧⌘Z redoes it; see "Undo on screens" below).

**Add assets just by dropping them**: wherever you drop files in Studio (a cover appears over the whole screen while dragging), a screen to confirm the kind
(`import-dialog.ts`) opens and lists each file with the kind it is guessed to be. The guess is `guessKind` in `model/asset-kind.ts`.

| File | Guess |
| --- | --- |
| Image | A sprite if it has transparent areas and is taller than wide, a background if it has the same aspect ratio as the project's screen, otherwise an image |
| Sound | Whatever its name contains, such as `bgm`, `music`, `voice`, `se` or `sfx`. Otherwise BGM if 30 seconds or longer, a voice if the name is numbered (`yui_001.ogg`), otherwise a sound effect |
| Video, subtitles (`.vtt`) | Video |
| Font | Other |

The kind can be changed row by row (only folders that can hold that file are offered), and "Don't add" can be chosen too. Files that can't be assets are listed with the reason and aren't added
(for PSD and PSB files, you are told to drop them onto the list of variants on the Characters tab). "Add" saves each file directly under the folder of its kind (if the name exists, it asks before overwriting).
Files taken as sprites are registered together into the default sprite set of the chosen character (if a character's name matches the start of the file name, it is preselected; if not, enter an ID with "New character"),
with the same positioning, sizing and variant naming as dropping on the Characters tab (both use `prepareVariants` in `asset-import.ts`). A newly made character is also added as a speaker, and for its first variants, the first variant becomes `defaultVariant`.
When you drop onto a panel that takes drops itself, such as the Assets tab, the list of variants on the Characters tab, or the import text field, that panel takes them. When you drop onto the script panel,
asset files are taken by this screen, and text files are left to the editor as before.

## Timeline, comments, voice and trash

**Timeline** is the standard screen for editing the effects of the script cursor's page (one line of text) as bars on a time axis (`timeline-view.ts`;
the data and rewriting are in `model/timeline.ts`). Open it from the "More screens" menu in the top bar, or with "Open" in the timeline heading in the right panel.
When the script cursor isn't on a text line (for example, on a comment at the top of the file), it shows the first page after the cursor (or the last page if there is none), and moves the cursor there too.
At the top are buttons to move to the previous and next page, the file and line, "Open in script" (opens this page in the script), zoom in, zoom out, fit, and "Play"; below them, the preview and the details of the selected bar; and at the bottom, the bars. The bars are the effect commands placed before that page
(`@bg`, `@chara`, `@camera`, `@quake`, `@mask`, `@wait`, plugin commands and so on), the way the text appears, click waits and commands inside the text,
calculated the same way as the timeline in the right panel (lengths from `time` and `fade`; whether to wait from the `wait` written, or else from `waits` in the command's spec).
Every action on the screen rewrites that line of the .lim (it goes in as an editor change, so ⌘Z undoes and ⇧⌘Z redoes it both on the Timeline screen and back in the script; it is saved by automatic saving; see "Undo on screens" below).
- Drag the right end of a bar to change its length (`time=` or `fade=`) in steps of 50ms. If it becomes the same as the default, the parameter is removed
- Drag a bar to change when it starts. If the effect command just before it is `@wait`, that wait's length changes (and the line is deleted if it reaches 0); if not, an `@wait` line is added before it
  only when moving it later. `@wait` also delays every command after it (as it means in .lim). A bar can move earlier only by as much as the `@wait` just before it
- Click a bar to select it, and the preview shows the screen right after that command runs. In the details, you can change the length (`1.5s`, `800ms`) and "Wait until done"
  (only for commands with a `wait` parameter; not written if it is the same as the default). For the selected bar, ←→ change the start and Shift+←→ change the length in steps of 50ms, and
  Enter or a double-click goes to that line in the script
- Commands inside the text (such as `{@quake}`) are display only (edit them in the script). Nothing can be changed in read-only files
- "Play" saves, then runs the commands in the real player from the screen just before the page's first effect command (the state of the line before it) and shows the page
  (a red line moves across the bars). The preview uses a different player from the script's preview, with the same mute setting

**Comments** is the standard screen for review comments attached to lines of the script (they can be replied to and resolved) (`reviews-view.ts`).
- Adding: the speech-bubble button above the script or ⌘⌥M shows a field for writing about the cursor line under "Comments" in the right panel (⌘Enter saves, Esc cancels; in the block view, "Add comment" in a line's right-click menu works too).
  Lines with comments get a speech-bubble mark to the left of the line number (in the block view, to the left of the line) (violet if open, gray if all are resolved); click it to show that line's thread in the right panel.
  The right panel shows the thread of the cursor line, where you can reply, resolve (and reopen) and delete comments. Your own comments (those whose name matches your current name) can be edited with the pencil button,
  and show "(edited)" next to the time (`ReviewComment.edited`).
  If two or more lines are selected in the code view, the comment applies to that range ("Comment on lines 12–15"; `ReviewThread.end` holds the last line). A speech bubble is placed on the first line of the range
  and a thin line mark on the following lines, and with the cursor on any line of the range, the right panel shows that thread
- The screen: for each file, lists the line (the current line number and the line's content), the comments and a reply field. Filter with "Open," "Resolved" and "All," and click a line to go to that line in the script.
  The badge on the "More screens" button in the top bar is the number of open comments (the Comments screen opens from this menu). "Name" at the top right sets the name attached to your comments (`reviewer` in `.liminalia/studio.json`;
  if empty, the OS user name)
- Where they are saved: `reviews/<id>.json` in the project (one per thread; they can be shared with git, and different people adding different threads don't conflict).
  Export (`lim build`) reads only the script, data and asset folders, so they aren't included in the game. When `reviews/` changes outside Studio
  (such as when you bring in changes with git), the dev server sends `reviews-changed` and the client reloads them
- How lines are tracked: a thread holds the line number, the content of that line (without leading and trailing spaces) and its hash (`textHash` in `@liminalia/lang`).
  On opening and on saving, it looks for a line with the same content (the one nearest the original line if there are several), or else a line with similar content (an overlap of character pairs of 0.6 or more)
  (`model/reviews.ts`). If it was found by similarity, it is reattached to that line on each save (so next time it can be found by content). While you type, the mark moves with the line.
  Threads whose line can't be found show "Line not found" on the screen. The last line of a range is found by the same rule, and if it isn't found after the first line, the range extends as many lines after it as it had when added
- Importing feedback from a test build: "Import feedback…" in the heading row lets you choose `.liminalia-feedback.json` files left in a test build (docs/distribution.md, "Test builds"; any number of them).
  Each piece of feedback becomes a thread on its script line. The line is found again in the current script by its page key (`pageKeys`), so it lands on the same page even if lines were added after the feedback (otherwise the line it was left on).
  The name, time and text are kept as they are, the screenshot is placed in `reviews/shots/<id>.jpg` and attached to the comment (click to enlarge), and the test build it came from is shown next to the name.
  The same feedback isn't imported twice, and feedback for another project, for a missing script, or in a file of another form is skipped with the reason (`importFeedback` in `server/reviews.ts`).
  Feedback received at the URL (`build.feedback.url`) has the same JSON form, so it can be imported as a file too

**Voices** is the standard screen for assigning a voice to each line of dialogue (`voice-view.ts`, `voice-drop.ts`; the logic is in `model/voice-assign.ts`). Open it from the "More screens" menu in the top bar.
- The list: filter dialogue by speaker and file, and split it into "All," "Not set," "File missing" and "Set" (200 lines at a time). Each row shows the speaker, the line, the current voice file and the status. The file follows
  the same rules as `lim voice-script` (`@voice` before the line, or the locked numbers and the `@voice-auto` pattern; it shares `voiceScriptRows` in `@liminalia/lang`). Even for an `@voice-auto` speaker, a line whose number isn't locked yet is not set.
  A second `@voice` played at the same time on the same line of dialogue (`who=`, `channel=`) is a row of its own too; its speaker is that voice's speaker, and next to the position the speaker of the dialogue is shown, such as "with Yui" (rows are told apart by `voiceRowKey`)
- "Listen" on a row plays the voice, and clicking the row goes to that line in the script
- "Choose" picks from the voice assets (Enter in the search field takes the first one; "Add from file" works too). While filtered to Not set, assigning one opens the choice for the next unset line, so you can fill them in order
- Drop one file on a row to place and assign it. For a line decided by its number, the file is placed under that number's file name (no `@voice` is written)
- Dropping several at once opens a confirmation screen. Files are matched to lines by the file names in the recording script (without folders; case is ignored), and files that don't match (not in the recording script, the same name appearing two or more times, not audio) are listed.
  For those, choose a line, or use "Assign to unset lines in name order" (unset lines have no file name in the recording script, so they can't match by name). If a file with the same name exists, you choose whether to overwrite it. Nothing is saved until you confirm
- Writing: as an `@voice` line before the dialogue (above any `//` note directly above the dialogue), through `PUT /file`, so it is kept in the change history (the open file receives an editor change; `script-writer.ts`). Press ⌘Z on the Voices screen to undo an assignment and ⇧⌘Z to redo it (files that aren't open too; see "Undo on screens" below). If there is an `@voice` line, its value is replaced.
  Choosing the same file for a line decided by `@voice-auto` and its number writes nothing (choosing a different file writes `@voice` and replaces just that line's voice). If the file changed after it was loaded, nothing is saved, and it reloads and tells you so (also when it changes while a dialog or file picker is open: the line's text is compared with the text when loaded, and it isn't saved)

**Trash** is the standard screen for script files, assets and themes that were moved to the trash (`.liminalia/trash/`, up to 100 entries) (`trash-view.ts`). Open it from the "More screens" menu in the top bar.
Everything moved at once is one row; rows are listed newest first with the kind, the names (up to 20; if there are more, "N more"), the date and time it was moved, and "Restore." "Restore" puts it back where it was (clearing any notice with "Undo" still showing),
and if something with the same name is already there, it isn't restored and you are told so. What was moved is saved in `<id>/.items.json` at that time; for older entries without it, the topmost files and folders inside are shown.

**Undo on screens**: on the Timeline, Voices, Assets (BGM loops, renaming, trash, adding), Characters, Flowchart, Game settings (including command defaults), Project (Basics, Export, Extras, Translation) and Variables screens, ⌘Z undoes the changes made on that screen one at a time, newest first, and ⇧⌘Z (also Ctrl+Y except on the Mac) redoes them
(`edit-undo.ts`; if one action rewrote two files, they are undone together). While you are typing in an input field, it undoes in that field. Changes made in the script aren't undone from these screens (so that changes you can't see aren't lost;
if there is nothing to undo, you are told so). To stay consistent with the script's undo history (CodeMirror), rewrites to the open file go in as editor changes, and when undoing from the screen,
if that change is at the top of the history, CodeMirror's undo and redo are used (going back to the script and pressing ⌘Z or ⇧⌘Z follows the same history). If the content has changed since, because you typed in the script or already undid it there, it isn't undone and you are told so.
In the desktop app, Edit → Undo and Redo in the menu do the same (when the app isn't in front, they act on the window that was last in front; while typing in a field they undo the typing, and on the Script screen they undo the script; `editHistory` in `main/menu.ts` and `__liminaliaStudio.undo` on the screen).
For files that aren't open (saved directly through the write API), if the content on disk is still what was saved, the content from before the save is saved through the write API (and kept in the change history). If it changed elsewhere, nothing is saved. After undoing, Studio saves and reloads the screen.
The settings screens deal with liminalia.json and the translation files (`lang/<language>.json`). The functions that write them (`setUi`, `setSettings`, `setExtra`, `writeTranslation` and so on in `Api`) read and remember the content before and after writing,
and to undo, if the current content is still what was written, they save the content from before through `PUT /part-file` (`part` is `@config` or `@lang/<language>`) (the earlier content is kept in the change history as `@config` and `@lang/<language>`;
if an item that needs a restart to take effect changed, the notice says so with "Restart"). Applying a theme, "Reset everything to default," and saving and deleting initial values of variables remember several writes as one action (`Api.undoGroup`),
and "Undo" in the notice undoes them too. "Change history" in the heading of the Game settings, Project and Variables screens shows the change history of liminalia.json (`.liminalia/history/@config/`)
in the same panel as the characters' change history, compared with the current content, and restores the chosen version (restoring can also be undone with ⌘Z on that screen).
Actions that move files (applying a theme, adding, renaming and trashing assets, renaming characters) make a record on the dev server for each action (`undo` in the reply; `server/file-undo.ts`),
and the screen remembers it as one change (`@files/<id>`). To undo, Studio checks that things are still as the action left them (`GET /undo/state`) and undoes with `POST /undo/apply`,
bringing back not only the settings and references but also the asset files, to the same places with the same content (for a theme, the copied assets are removed and the previous theme's assets moved to the trash come back).
Removed and overwritten files are kept in `.liminalia/undo/` (they are no longer used when the dev server changes, and are deleted the next time the project opens). If something changed after the action,
or the dev server was restarted, nothing is undone and you are told so. On the Characters screen, rewrites of cast.json are remembered by the content before and after (`@cast`), like the positions on the Game settings screen,
and become one action together with the added images. The dev server's write routes and how ⌘Z undoes each are listed in `server/undo-routes.ts` (`test/file-undo.test.ts` fails for a route
that isn't listed and for a route that isn't checked by undoing).

## Variables, game settings and game screens

**Variables** is the standard screen that puts the variables used in the script (`game.`, `system.`, `temp.`) and their initial values (`variables` in liminalia.json) in one table.
They are listed by kind, in name order (numbers are compared as numbers, so `chapter_2` comes before `chapter_10`).
Editing an initial value saves it right away (emptying it removes it; strings as `"…"`, and numbers, `true` and `false` as they are), and the preview and the current position data run again from the initial values.
Click a row to open the lines that assign and read the variable, and click one of those to go to that script. Renaming a variable also rewrites the references in the script, where it is assigned, the name of its initial value, the conditions (`if`) in `ui` and `extra` of liminalia.json, and the conditions of breakpoints.
Variables that are read but have no assigning line or initial value, and variables that are assigned but read nowhere, are marked. "Add a variable" lets you set just an initial value in advance.

**Game settings** is the standard screen for editing `ui` in liminalia.json ("Game settings" in docs/player.md). On the left are the items (Text, Message window, Name box,
Click-wait icon, Choices, Chat, NVL, System screens, Title screen, Ending name, Chapter card and end, Cursor, Saves and backlog, Config defaults, Quick menu, Key bindings),
and on the right a preview drawn by the real player (switch between Text, Choices, Title, Menu, Save, Settings, Log, Ending, Chapter card and NVL; touching an item switches to the preview it affects.
Ending waits with the name of a sample ending (`@title-screen ending=good`) shown, using `?ui-preview=ending`, and applies the values of `ui.ending` as they are.
Chapter card shows `@chapter-card` in the Game screens preview (`?ui-preview=screen&screen=chapter`) and applies the values of `ui.chapter`.
NVL stacks two `@nvl on` paragraphs with `?ui-preview=nvl` and applies the values of `ui.nvl`. Touching a field in a row of named looks (`ui.nvlStyles`) switches the preview to `@nvl on style=<name>`).
Like Game screens, the preview never reads or writes the player's saves, read pages or settings (it opens with a sample store; the save and load previews get sample saves).
Edits are saved right away and take effect in the preview and any open player without a restart. An emptied item is removed (it goes back to the default).
Nested values are edited in a field for each item too, without writing JSON (`game-fields.ts`): image slicing as four numbers for top, right, bottom and left (written as one number if only the top is given or all four are the same),
text shadow as the horizontal and vertical offset, blur and color, text outline as width and color, letter spacing as a number of em (values that can't be split, such as layered shadows or letter spacing in px, are edited as CSS with "Enter as CSS"),
the title button layout as position, direction, spacing and width, the titles and help pages that change after the game is finished and so on as lists with rows added by "Add" (rows without a condition or heading aren't written),
captions per sound effect, sprite tones and tones by background (`ui.backgroundTones`) as name-value pairs, and system voices as rows of the moment (title screen, confirmation, each action) and voice, condition, assigned character, and volume
(split into `title`, `confirm` and `actions` when saved). "Startup splash" (`ui.splash`) is edited with fields for the logos shown in order (rows of image, background color and time; rows without an image aren't written),
the notice heading and items (rows of heading and text; rows without text aren't written), background color, text color, display time, whether it advances automatically, whether a click moves to the next, and the fade-out time at the end.
Items with no field (written by hand) are kept, not deleted. To add a key, click "＋" and then press the key.
"Edit layout" above the preview lays frames over the Text and Choices previews for what can be moved (the message window, name box, face window, choices, quick menu, sprites and HUD items) (`layout-overlay.ts`, `model/layout.ts`; the preview is `?ui-preview=page&layout=1`, shows up to three characters at left, center and right, shows one line per name of the script's `@hud-button` and `@hud-text` with `show-if=` removed, and reports the layout with `liminalia:layout-report` from the player's `layout-probe.ts`).
Select a frame and drag it to move it, or drag the handles on its corners and edges to resize it (the message window, face window and HUD buttons; choices keep their center and change only the width).
The handles can be pressed within 20px, or 44px on touch devices (tablets and the mobile version; CSS `pointer: coarse`).
With the keyboard, arrow keys move 1px, Shift+arrow keys move 10px, and ⌥+arrow keys change the size. Dragging and keys can't take things off the screen (the edge being dragged stops at the edge of the screen, and something already sticking out only moves back inward; sprites aren't stopped).
Selecting a frame shows X, Y, Width and Height fields in the row below the top bar, and highlights and scrolls to the same items on the left.
Changing a number in either field moves the preview and the frame, and dragging updates the numbers in the fields.
Something put off the screen with the numbers gets a red frame, with "Off screen" next to the number fields. The row below the top bar (Edit layout, the number fields, Change history) is always shown, and the size of the preview doesn't change when you start editing the layout or select something.
The result is written to `ui.message` (all four of `x` `y` `width` `height`), `x` `y` of `ui.name` and `ui.menuBar`, `x` `y` of `ui.face` (when moved) and its `width` `height`, and `y` `width` of `ui.choice` (values are in the px of the text and window coordinates, the same for portrait projects and projects of a different size).
A sprite moves that position (`frame.positions` in cast.json) by the same amount in every variant of its sprite set (so it doesn't jump when the expression changes; moving a variant without a frame makes a frame that matches how it looks now).
"Position" for a selected sprite changes which position the preview shows it at.
A HUD item rewrites every script line with that name that places it at the same spot (the `x` `y` numbers): `x` `y`, plus `width` `height` when changed or already written.
Other parameters are kept, and lines that give the position as an expression or place it somewhere else are left alone.
A drag is saved when you let go and keys when you stop pressing them, and all of it can be undone with ⌘Z in Game settings (cast.json and scripts too).
If `ui` changed elsewhere after it was loaded, it is merged item by item before saving, as with the script (see "Principles" below).
If a project plugin replaces a screen (title, startup splash, Settings, save and load, Log, quick menu, menu, confirmation, ending name,
extras, flowchart, the auto and skip indicator, codex, notifications, choices, name box, dialog boxes, controls screen, items, click-wait icon; known from the plugin's declaration),
the group heading shows "(plugin name)'s screen" (whether these settings are used is up to the plugin). When you add a way to replace a screen, also add it to `REPLACEABLE` in `packages/web/src/ui-probe.ts`
(`packages/studio/test/replaced-screens.test.ts` checks it against the list of standard screens).
In the Text and Choices previews, each item's value is tried with two different values, and items whose actual look doesn't change are marked "No effect"
(when something else decides the look, such as the project's CSS, a plugin, or a character's name color; the values are put back before drawing).
"Command defaults" at the very bottom is `commandDefaults` in liminalia.json ("Project command defaults" in [format.md](design/format.md)). Choose a command and parameter and click "Add,"
and entering a value saves it right away (the faint text in the field is the standard default; emptied and deleted entries are removed). When saved, completion, the parameter panel and the syntax check reload with the new defaults,
and the preview runs with the new defaults from the next "New game" or load. "Reset everything to default" at the very bottom removes both `ui` and the command defaults.
"Change theme" in the theme section at the very top opens a modal where you switch between "Preset themes" and "Original themes" to choose one. Nothing in the project settings or assets changes until you click "Apply." On the Original themes tab, you can save the current look as a theme and move project themes to the trash ("Themes" in [player.md](player.md)).
Portrait-only themes (`orientation: "portrait"`, such as chat) aren't listed for landscape games, and for portrait games they are grouped at the top under the heading "Portrait only." Cards for themes that show text in speech balloons are drawn with balloons.
The "Chat" group holds the `ui.chat` items ("The chat screen" in [player.md](player.md)).

**Game screens** is the standard screen for opening the built-in screens (title, message window, choices, save and load, log, ending name, extras, codex, investigation and so on;
the screens in the table in [screens.md](screens.md)) filled with sample content. On the left is the list of screens, on the right a preview opened in the real player.
Without playing the game up to that screen, you can check how filled save slots look (thumbnail, date, the start of the text, memo, lock), the log (voices, a page where two people speak at once, a choice that was picked),
the ending name and kind, and items in the extras, codex and inventory. The sample content uses neutral names (a guide, a traveler, a lighthouse and so on) and never the project's characters or scripts.
The bar at the top switches the content (Filled, Empty, Long text; long text means long lines and long names), Portrait (Landscape for portrait projects; portrait uses the layout in `system/portrait.css`),
English (the built-in screens' wording and the sample content in English; English is added inside the preview only, even if the project's `languages` don't include it),
and the theme (the current theme, or one of the bundled and project themes, listed as light themes and dark themes). Content a screen doesn't provide can't be selected.
The chosen screen and switches stay the same the next time you open it (`liminalia.studio.screens` in the browser's `localStorage`).
Screens that can't be opened (click to start, the hint shown when a phone is held upright, playtest feedback) go at the end of the list with the reason.
A screen replaced by a plugin opens as the replaced screen, and the list shows "<plugin>'s screen" (whether the plugin has the replacement hooks in the table in screens.md, such as `screens.*`, `title`, `system`
and `extensions.renderers.*`; the standard commands' `std` counts as standard).
When `ui` in liminalia.json is saved (from the Game settings screen, another app or an AI), the preview applies the look without reloading and opens the same screen again.
Saving a plugin's CSS also swaps it in place. While a project theme (`themes/<id>/theme.json`) is applied in the preview, an outside change to it reloads the preview.
The preview never reads or writes the player's saves, read pages or settings (IndexedDB, `localStorage`): before it starts, the store is swapped for a sample store that disappears when the page closes
(`useMemorySaveStore` in `packages/web/src/system/storage.ts`). The theme, language, orientation and sample extras are layered only onto the loaded project information; the project's files are never rewritten.

While "Pick parts" in the top bar is on (the default), clicking a part in the preview (a slot number, a title screen button, the message window, a choice button and so on)
outlines that part and shows, in the panel on the right, the theme values (`ui` in liminalia.json) that set its look. The parts and values come from the parts table in [screens.md](screens.md)
(`parts` in `packages/web/src/system/screen-catalog.ts`), and the fields are the same as in Game settings (colors in color fields, text sizes and corner radii in number fields, shadows in split fields; `client/screen-parts.ts`).
The part under the mouse is outlined with a dotted line. You can also pick a part from the menu above the fields. Clicking a part under a screen opened over the preview (such as the message window) shows it as a part of that screen.
While you drag a field (picking a color, typing a number), the preview takes the unsaved value (`liminalia:screen-draft`); once you settle, it is saved to `ui` in liminalia.json
(if it changed elsewhere after it was read, items are merged as in Game settings). Saved changes can be undone one at a time with ⌘Z on this screen.
Under each field are the other parts on the same screen and the other screens the same value affects (values in `ui.system` affect the other system screens too). Hovering over or entering a field outlines the other parts the same value affects with a dotted line.
Under the theme values are the project CSS fields (text color, background color, text size, padding, corner radius, border color, border width). Choosing a value writes one line,
"part selector { property: value; }", to the project CSS (a line with the same selector and property is rewritten, and clearing the field removes it. Nothing is put in an element's style, so you can open the CSS file and read it later),
and the unsaved line is sent to the preview too. The lines go to the first file in `ui.css`; if there is none, `ui/screens.css` is created and added to `ui.css` ("Project CSS" in [player.md](player.md)).
Like theme values, written lines can be undone one at a time with ⌘Z on this screen (a created file and `ui.css` are restored too). They also cover changes theme values can't make (a color for just that part, for example).
For a part with no theme values (the menu's dimmed backdrop, captions and so on), a single line shows the part's selector and the file the lines go to, and only the project CSS fields are shown.
Turning "Pick parts" off lets you click inside the preview (switch tabs, scroll lists and so on). In the mobile version the panel sits under the preview, and you tap a part to pick it.
Switching the panel to "CSS" with the switch above it lets you write the project CSS file directly (the same file the part fields use: the first file in `ui.css`, or `ui/screens.css`, which is created and added to `ui.css`;
`client/screen-css.ts`, a CodeMirror CSS editor). Lines written by the part fields can be read and edited here too. What you type shows in the preview right away, before it is saved
(`cssFile` in `liminalia:screen-draft`, used in place of that file's content), and is saved after a short pause (`PUT /ui/css`; if the file changed elsewhere after it was read, it isn't saved and the current content is loaded).
⌘Z inside the editor undoes typing; ⌘Z outside it undoes saved changes one at a time (a created file and `ui.css` are restored too).
Completion offers part class names (the open screen's first, with the part's name; other screens' too), `--lm-*` variables (the variables shared by system screens, the screen's own variables,
and the variables theme values go into, with the value's name), the state attributes the engine writes (`data-lm-hover` and so on; "States" in [design/screen-templates.md](design/screen-templates.md)),
and CSS properties and values (`@codemirror/lang-css`). Clicking a part in the preview moves to the rule for its selector and highlights its lines; if there is no rule, it shows where to add one at the end (click it to add the rule).
Putting the cursor inside a rule outlines the parts its selector matches in the preview (states such as `:hover` and `data-lm-*` are dropped when looking).
CSS that can't be read (an unclosed brace or comment) and `url()` pointing outside the project get a wavy underline with the same diagnostics as `ui-css-syntax` and `ui-css-outside` in lim check.
The switch is remembered for next time (`liminalia.studio.screens.panel` in `localStorage`). In the mobile version, the editor sits under the preview like the part fields.

For screens that can be built from a template (confirmation, menu, controls help, ending name, choices, save and load, backlog, title and settings; `GET /screens/rules`, decided by `STANDARD_SCREENS` in `@liminalia/web`, so new ones show up as they are added),
the switch above the panel also offers "Template" (`client/screen-template.ts`; templates and attributes are explained in [design/screen-templates.md](design/screen-templates.md)).
Before copying, it shows "Make this screen my own" and what to copy (the whole screen or one part). Like `lim screens copy`, it copies the built-in template to
`ui/screens/<screen>/<screen>.html`, registers it in `ui.templates` in `liminalia.json`, and keeps the copied original in `.liminalia/screens/`.
The copied file opens in this editor, and the desktop app also shows the template's folder in the file manager (the "Open folder" button does the same later).
If a plugin's `screens.*` (including one in a theme) or `system` replaces the same screen first, it says beforehand that a copy won't be used.
What you type in the template editor reopens the same screen with that template in the preview right away, before it is saved (`template` in `liminalia:screen-draft`), and is saved after a short pause (`PUT /screens/file`).
Attribute values (`data-role`, `data-field`, `data-text`, `data-part`, `data-item`, `data-setting`) are completed from the screen's rules (working roles, screen values, built-in text keys, part names and the setting names of the settings screen).
Problems from the template check in `lim check` (`template-*`) get wavy underlines for errors and warnings. When a part's built-in template has changed since the copied version (`template-outdated`),
a line saying the built-in template changed appears above the editor; clicking it shows the differences from the built-in template, the same as `lim screens diff`.
"Add JS to this screen" puts a screen JS skeleton next to the template (the same as `lim screens js`) and opens it, and you can switch between the template and the JS
(the mobile version's preview doesn't load screen JS yet). "Reset to built-in" removes the screen from `ui.templates` like `lim screens reset` and keeps the template and the screen JS
with `.reset-<date and time>` added to their names. Copying, writing, adding JS and resetting can each be undone one at a time with ⌘Z on this screen (created files and folders and `ui.templates` are restored too).
⌘Z inside the editor undoes typing.

The preview player opens at `/?ui-preview=screen&screen=<screen id>` (dev server only; it isn't included in exported games).
The parameters and the sample content are kept in one place, `packages/web/src/screen-preview/samples.ts`, and screenshot tools and the like can open screens the same way:

| Parameter | Meaning |
|---|---|
| `screen` | The screen id (`id` in `GET /screens`; the screens in the table in screens.md) |
| `state` | `empty` (Empty) or `long` (Long text). Omit it for Filled |
| `orientation` | `portrait` or `landscape`. Omit it to keep the project's orientation |
| `lang` | The language to play in (`en` for English) |
| `theme` | The id of the theme to apply (the name written in `ui.system.preset`) |
| `bg` | The sample background (a path from `bgimage`; omit it for a sample picture) |
| `sample-lang` | The language of the sample content (`ja` or `en`; omit it to use the play language, the same as the built-in screens' wording) |
| `still` | `1` shows the final state without waiting for opening animations |

When the screen is open, `data-lm-screen-preview` on html becomes `ready` (`failed` if it can't be opened), `window.__liminaliaScreenPreview` holds the state (`status`, `replaced`, `problems`),
and `{ type: "liminalia:screen-preview", screen, state, status, replaced, problems }` (`ScreenPreviewReport` in `protocol.ts`) is sent to the parent page. Each time the screen opens again, it starts over from `loading`.
When you add a screen to the list of built-in screens (`packages/web/src/system/screen-catalog.ts`), write how to open it or why it can't be opened in `SCREEN_SAMPLES` in `samples.ts`
(`packages/web/test/screen-preview.test.ts` checks them against each other; write how to check each screen's content in `CONTENT` in `packages/studio/test/screen-preview-e2e.test.ts`).

## Project and plugins

**Project** is the standard screen for settings that concern the whole project (other than the game settings), switched with the switch to the right of the heading.
- Basics, Export: the top level of liminalia.json (`project-settings.ts`). Field names are tied to their inputs with `<label>`. Among the basics, fields you don't change in normal work
  (Call after loading, Allow @script, Protect saves from tampering, Folders, Import) are collapsed under "Advanced settings" at the end
  (when the export screen opens one of those fields, it is expanded even if collapsed)
- Extras: builds the lists in `extra` of liminalia.json (CG, recollections, music, achievements). Images and tracks are chosen from the asset lists, and a recollection's start position from the script files and labels
- Translation: add and remove playable languages (`languages`; the first is the language of the original), and write translations of the text, choices, speaker names and the game data text (the translatable fields of `data/*.json`, shown with the data file and the place in it) for each language (`lang/<language>.json`).
  Opening it syncs with the current script (new lines are added with empty translations, and translations no longer used are carried over or kept; the same as `lim i18n`; just opening doesn't save to the file, and it is saved in this form when you edit a translation), and lists what isn't translated yet
  100 at a time. Lines whose original was rewritten show the previous translation, which you can click to put into the translation field. Click a location to go to that script. The number translated is shown for each language
  (for languages that list system screen text, the script translations and the system screen text are counted separately, and the list is narrowed by "Script" and "System screen text" the same way).
  Lines with a fixed line ID whose original changed after they were translated (`translatedFrom`) show the original at the time of translation; type the translation again, or remove the mark with "Keep this translation"
  (if there are any, "Source changed" narrows the list to them). For languages other than Japanese and English, the system screen text (`ui`, with the English original) is listed in the same list.
  Renaming a script also rewrites the translation keys
Extras and languages take effect in any open player without a restart.

**Plugins** lists "All plugins" in the left panel along with the screens added by project plugins (`./studio`, grouped by plugin; [plugins.md](plugins.md#制作画面studio)),
and opens the chosen one on the right (the last one opened is remembered).
- All plugins: the `plugins` list. It shows the name, version, entry points (custom commands, rendering, import, Studio) and the custom commands added, and lets you reorder and remove plugins (the folder stays).
  For plugins inside the project folder, you can edit the name and description (package.json) and open the folder in the OS file browser (installed packages aren't rewritten)
- Create new: choose a name (lowercase letters, digits, -) and the entry points (commands always, rendering and Studio optional), and it makes a small working sample in `plugins/<name>`
  (`@<name>-hello`; with rendering, it shows text on the screen; with Studio, it adds one screen) and adds it to the end of `plugins`
- Add an existing plugin: a plugin folder (a path relative to the project folder, `./plugins/…`, or the absolute path of a folder outside the project) or
  the name of a package installed with `npm install` in the project folder. It only appends to plugins in liminalia.json and doesn't copy files. A plugin that can't be found isn't added.
  In the desktop app, "Choose folder…" lets you pick a folder in the OS folder picker and add it directly
- Official plugins: lists the plugins bundled with the app (currently AI consultation) with their name, description, entry points and version. "Install" copies one into `plugins/<id>` in the project and
  adds `./plugins/<id>` at the end of `plugins` (npm isn't used). If it is installed, it shows "Installed"; if the bundled version is newer, "Update to (version)";
  and if only the folder exists and it isn't in `plugins`, the installed version and "The folder is there, but it is not added to the project." For plugins whose bundled folder is missing (such as an app extracted for development; `CatalogPluginInfo.unavailable`),
  it shows only "Not included in this app," not as an error (the places it looked are in the console). "Reinstall" and update keep the previous content in `.liminalia/backups/plugins/<id>-<date-time>` (up to 3)
  and copy it again. If `plugins/<id>` holds a different package, it doesn't install. Where the list is kept and its shape: [plugins.md](plugins.md#公式のプラグイン)
After changing the order of plugins, restart for it to take effect ("Restart" restarts the dev server in the desktop app).

## Code view and preview

- The **duration bars** (effect bars) to the right of the line numbers in the code view draw, for the whole file, 3px vertical lines showing from which line to which line the background, BGM, looping sound effects and sprites last
  (`GET /sweep/stage`). The minimap at the right edge covers the whole file too. Click a bar to go to the line where it starts. Each column of bars is drawn inside boxes of equal width,
  so bars in the same column join up at the same horizontal position and width on every line, regardless of whether other columns have bars, the start and end marks, or wrapped lines
- Point at a bar, the minimap or a card (background and sprite commands) to see the range in a peek window, along with the background image for a background, or for a sprite, the
  variant at that line and the sprite set's image (looked up from the characters). Backgrounds are 16:9 at 480px wide, and sprites are 420px high (aspect ratio 3:4);
  if they don't fit on screen, they shrink to the screen height or width, keeping the ratio. Until the image loads, an area of the same size is shown first (so the window doesn't jump).
  The window is placed at the bottom right of the pointer, moves left or up if it would stick out, and if it fits neither way, moves toward the side with more room, staying within 8px of the screen edges.
  BGM and sound effects show only the name and the range. Images that are loading or can't be loaded, and variants the character doesn't have, are labeled as such
- Completion (command names, parameters, values) and the inputs of card forms are built from the command specs. For **asset** parameters, assets used in this file are suggested first,
  followed by those in the asset folder (images are shown shrunk; sounds by name only). "Add from file" lets you choose a file on your computer,
  adds it to the asset folder of that parameter (or the `folder=` folder if given), and uses it as the value right away. "Show in folder" in the parameter form on the right selects the asset in the Finder or Explorer (on Linux, it opens the folder). If you write an asset that isn't in the asset folder,
  the syntax check while typing tells you without waiting for a save. For choice lines, it completes the jump target and the parameters after it (`if=` and the look; the spec is `CHOICE_OPTION`).
  Parameter names aren't suggested while you are typing inside `"…"` and `(…)`
- In the code view, pressing Enter after a line of dialogue suggests the previous speaker and the other person who spoke before them. Choosing one (with Tab and so on) inserts `speaker「」` (`speaker ""` when the original language is English), so you can type inside the brackets. It also suggests them when you split a line of dialogue in the middle, and choosing one closes the previous line and puts the rest of the text into the next line of dialogue. If you don't choose a suggestion, nothing changes except the line break. The existing speaker completion at the start of a line lists the speakers within 30 lines before and after in the same scene, nearest first (it looks past branches and right after them as the same scene, and stops at labels, scene changes, and `@jump` and `@return` in the same flow; the suggestions after Enter work the same way), and then the others in order of how many lines of dialogue they have across all scripts. For the file being edited, its unsaved content is used. With touch on a phone, the speaker bar above the keyboard is used as before.
- Choice lines with a condition (`if=`) get a condition card in the right margin ("if expression" with a dashed border). Clicking it doesn't open a form
- The **timeline** draws this page's effects from the command lengths and "whether to wait until done" (`waits` in the command's spec; a `wait` written takes priority).
  When the cursor is on a command line, a mark is placed at the point when that command has finished running (for a command that waits, when it ends; for one that doesn't, when it starts),
  and the commands and text after it are faded
- The language selector in the row of controls below the preview (only when `languages` in `liminalia.json` has two or more) shows the preview in a translated language (remembered per browser and per project).
  Choosing one reloads the player with `?studio=1&lang=<language>` and asks again for the screen it was showing. The player passes it to `SystemEnv.language` of the system screens,
  and the standard system screens use it ahead of the config language and the device language (the translations of text, choices and speaker names, and assets per language; translations are written in `lang/<language>.json` under "Translation" in the project).
  Nothing is saved to the script or the game data
- The device selector in the row of controls below the preview lets you try PC (landscape, portrait) and phone (landscape, portrait) screens. PC is drawn as a screen whose long side is 1280 (the game's aspect ratio if the orientation matches the game, 16:9 / 9:16 if not). Phone is drawn at roughly the screen size of an iPhone, leaving margins for the notch and home bar,
  and shows the touch device UI (the menu button at the top right, hiding the quick menu at the bottom, the notice shown when a landscape game is held upright) (the player's `?device=phone`)
- The **preview** shows that page for text and choice lines ("Line N" in the row below), and for command lines (effect commands, `@set`, labels and so on)
  the screen right after that line runs, before the text ("Right after line N"). The state panel also shows the variables right after it. The route is shown below the preview.
  For empty lines and comment lines, it shows the nearest earlier line that has a state
- The row below the preview holds the preview's control buttons. The keys work even when the preview has the focus (when the writer has clicked the preview)
  - **Pause** (⌘⇧P; press again to resume): freezes the preview on the current screen. Sound (BGM, sound effects, video) and moving effects (animations,
    text display, auto, waits) stop, and clicking the preview doesn't move it forward. "Paused" appears at the top right of the preview. While paused, moving the cursor
    doesn't rebuild the preview, and refetching the current position data (`GET /sweep`) stops too (the state and the timeline are drawn from the state already fetched).
    Resuming shows the cursor line at that moment again and does the refetching that was held back. Also useful in heavy projects to stop the preview from moving on every keystroke.
    The paused state isn't remembered (reopening starts it moving)
  - **Mute** (⌘⇧M): silences the preview without stopping it. It is remembered, so it stays silent even when the preview is rebuilt or reopened
  - **Enlarge** ("Enlarge" in the preview heading, or ⌘⇧B; once pressed, it changes to "Normal size"): widens the right panel to make the preview larger (the timeline and the state at this line go below it; the script gets narrower). Remembered
  - **New window** (the icon in the row of controls): shows the preview in a separate window. It expands to fit the window, and the cursor line, pause, mute and cursor sync keep working. In the panel, "Show window" brings the preview window to the front, and "Bring back" brings the preview back to the panel. Closing the window also brings it back to the panel. While in a separate window, the full screen button is hidden (make the window itself full screen)
  - **Full screen** (⌘⇧Enter): shows only the preview (with its row of controls) full screen, centered at the largest size that fits with the game's aspect ratio. Esc returns
  - **Screenshot** (the camera icon in the row of controls; there is no key): captures the screen the preview is showing at the game's size (`screen` in `liminalia.json`,
    not the shrunk size of the preview), without Studio's decorations (the line display, the "Paused" label and so on), and saves it in `exports/shots/<file>-<line>.png`
    (/ in nested file names becomes _; if the name exists, -2, -3… is added, never overwriting). What it captures is the screen last requested from the preview (for text and choice lines, that page
    fully displayed; for command lines, the screen right after), and if you moved the preview forward by clicking, the page it reached (named after that line too). The button can't be pressed while capturing.
    When saved, the location appears in the status bar, with "Open folder" in the desktop app (opens Finder or Explorer with that file selected)
    or "Download" in a browser. How it captures is described in "Screenshots and performance measurement" below. Nothing is saved to the game data
  - **Cursor sync** (⌘⇧J; press again to turn off): when the preview moves forward by itself (the writer clicked the preview, auto, skip, or a choice), the script cursor moves
    to the line of the page the preview started showing (for choices, that choice). If it moved on to another file with `@jump` or similar, that file opens.
    The cursor line it moves to doesn't rebuild the preview (so the preview you moved forward doesn't start over). Input isn't moved to the script, so you can keep clicking the preview to move forward.
    It doesn't move while you are typing in the script (when the script has the focus), while paused, on the Check screen, or while the change history panel or the panel for choosing between conflicting changes is open.
    When skip moves through several pages, it moves only to the last line. Moving the cursor from the script makes the preview show that line again as usual, and cursor sync continues from there.
    At a line it moved to, the state panel, route and timeline are drawn from the state actually reached in the preview (not the state at that point along the route).
    The line display below the preview becomes "Line N (preview state)," and the state panel gets the "State at this line (preview)" label.
    The route, as "Route (preview)," is the route up to the page the preview was asked to show plus the choices made in the preview, with marks on the choices made in the preview.
    Where a variable comes from ("← start 133") is the line that set it in the preview if there is one, or, if the value is the same as at the page the preview was asked to show, where it came from at that page.
    When the system screens don't report the line that set a value (`SystemEnv.onAssign` isn't passed to the runner), a changed variable shows just "← preview."
    Moving the cursor from the script returns to the state at that point as usual. Whether it is on is remembered
  - Checks on screen (including cursor sync) are in `packages/studio/dev/verify.ts` (dialogue per speaker, endings, saving themes, plugin checks and the English interface are in `packages/studio/dev/verify-lists.ts`, which starts `lim studio` on port 5313 to check; Play from Here, confirm before leaving, Go to Jump Target, Lines Leading Here and undo on screens are in `packages/studio/dev/verify-nav.ts`, port 5315; scene actions, Move to another file, building on the flowchart, all-routes test progress, the breakpoint list, the preview language and overflowing pages are in `packages/studio/dev/verify-structure.ts`, port 5316; find and replace in the block view, the scope and speaker of search across files, scene tags and status, text and tags in ⌘K, Go to Macro Definition, the lines using a macro and renaming a macro, TODO comments and the character count in the heading are in `packages/studio/dev/verify-find.ts`, port 5319, which also measures speed on a large project with `--project <copy> --file <large file> --word <word>`; search from the desktop app's menu is in `packages/studio-desktop/scripts/find-check.ts`; replace in all files, "Delete all" and "Fix all," undo on the settings screens (including the "takes effect after a restart" bar) and the change history of liminalia.json are in `packages/studio/dev/verify-undo.ts`, translation on the Project screen (translations whose original changed, system screen text) is in `packages/studio/dev/verify-i18n.ts`, and reloading a test play, "Open this page in the script" and runtime problems are in `packages/studio/dev/verify-test-play.ts`; both start a dev server on a free port), and full screen and keys in the desktop app (Electron) are checked with
    `npx tsx packages/studio-desktop/scripts/stage-check.ts [--shots folder]`
- **Breakpoints**: click to the left of a line number to add a red mark (click again to remove it). When the preview is moving forward (clicks, auto, skip, choices)
  and reaches that line's command, the preview stops before running it (in the block view, add and remove them with "Breakpoint" in a line's right-click menu). The script cursor moves to that line, and the state panel shows the state reached up to there.
  In the block view, the line where it stopped is centered, with a red border and "Stopped here" (it disappears on resuming).
  Press "Pause" again (⌘⇧P) to continue from that command. While stopped, "Step" appears in the row of controls below the preview; click it to run that command and
  stop again before the next command (`stage-step`). Adding lines above it keeps it on the same line. Rebuilding to show a requested line in the preview
  doesn't stop at breakpoints (the messages to the preview are `stage-breakpoints` and `stage-break`, and the runner uses `RuntimeOptions.beforeStep`)
  - How they are remembered: in `breakpoints` in the project's `.liminalia/studio.json`, by line number, the line content (without leading and trailing spaces) and its hash (`model/breakpoints.ts`; older localStorage entries with only line numbers
    are remembered again using the line content when loaded). On opening and on startup, as with comment threads, they look for a line with the same content (the one nearest the original line if there are several), or else a similar line, and reattach there,
    so lines don't shift even if the script is edited elsewhere. Those whose line can't be found stay in the list with "(line not found)"
  - The list: when there are breakpoints, "Breakpoints N" appears in the row of controls below the preview. Click it to see a list of file and line, line content, a condition field and a remove button;
    click a row to go to that line, or "Remove all" to remove them all
  - Conditional: write an expression in a condition field of the list (such as `game.n == 1`; the same syntax as `@if`) and press Enter, and it stops only when the expression is true (empty stops every time). The preview's runner evaluates the expression before that command,
    and stops if the expression can't be read or evaluated (so you notice typos)
- **Change history** (the button above the script) shows the previous content kept on each save (recent saves in detail, older ones thinned more coarsely; see "Principles" below). Choose an entry in the list to see its differences from the current content (including edits not yet saved)
  line by line, and "Restore this content" replaces the current content with it and saves. The content before restoring is also kept in the change history,
  so a restore can be undone too (⌘Z undoes it as well). It can't restore read-only files

## Check

**Check**, when there are no problems (errors, warnings, information) and no lines unreached by the all-routes test, doesn't line up cards showing 0; it shows just a "No problems" line,
"Check again," and running the all-routes test (or its result if it has been run). If something was found, three cards appear at the top ("All-routes test" (`POST /coverage`) with the share of lines reached and "Run again," "Problems" with the count and the breakdown of errors and warnings,
and the first range under "Unreached"; zero counts in the breakdown are gray), and below them round buttons with counts for the categories (Syntax, Commands and parameters, Characters, Jump targets, Assets, Plugins) and the list of problems.
The syntax check runs automatically on every save (it uses the whole-project check the write API runs once after saving, so the client doesn't check again; opening and "Check again" use `POST /check`). Click a category to show only its problems (choose as many as you like; click again to remove).
Click any problem to go to that line in the script (problems in cast.json go to that character or sprite set on the Characters screen; suggested fixes are also shown in the interface language). The badge on "Check" in the top bar is the same number as the "Problems" card
(errors and warnings, adding those found by the all-routes test, the overflow check and test play, and counting the same file, line and code once; `client/model/problems.ts`). It's red when there are errors and yellow when there are only warnings.
Writing suggestions (sprite flicker, gaps in sound, values equal to the defaults and so on; `SUGGESTION_CODES` in lang) aren't counted in the badge or "Problems"; the card lists them separately as "Suggestions."
The check is the same as `lim check`, the VS Code extension and the MCP `check_text` (`projectDiagnostics` in `@liminalia/sdk` builds the input in one place; it also checks translation files, the script format version and jump targets from command data).
After a recheck and after outside changes (scripts, cast.json, liminalia.json, translation files, project data), the problem count in the script header, the marks in the scene list and tabs, the squiggles on lines, and the line state and route are all rebuilt from the new result.
The category counts are split into errors (red), warnings (yellow) and information (uncolored), showing only the ones there are (0 if none; hover for the breakdown; the total is in the button's `data-count`).
Problems whose suggested fix can be applied as is (the diagnostic's `fix`: candidates with similar spellings for commands, parameters, labels, characters, variants and so on, assets with similar names, punctuation) are fixed with "Fix" on the right of the line.
In the editor, "Replace with "…"" and "Delete this line" in the problem's tooltip apply the same fix. For unneeded `@cg-unlock`, punctuation, parameters equal to the project default (`same-as-default`),
fades that can be one `@scene-change` (`scene-change-candidate`, which merges several lines into one) and unused `lim-ignore`, the count and "Delete all" or "Fix all" for each kind appear above the list (applied after you confirm).
For warnings and info, "Don't show on this line" in the menu of the problem's tooltip and of a row in the list (right-click and "…") writes `// lim-ignore code` on the line before (or adds the code to a `lim-ignore` right above; ⌘Z undoes it),
and "Don't show this kind" writes `off` for that code in `check.severity` in liminalia.json (turn it back on with "Undo" on the notification or under Check in the project settings; "Silencing diagnostics" in [format.md](design/format.md)).
If a diagnostic's `fix` is a Studio fix (`ProjectFix` in `client/fix-actions.ts`), Studio carries it out instead of rewriting the line. `{ kind: "add-speaker", name }` is
"Add X as a character" (like "Add" on the Characters screen, it makes a character without sprites in cast.json and adds it to `speakers`),
and `{ kind: "create-scene", label, file? }` is "Add the scene #X" (like "Add scene" in the scene list, it adds `# X` at the end of `file`, or the diagnostic's file if it's left out).
The button says what it does, and the same action runs from the check list, the tooltip in the code view and the problem card in the block view.
When a diagnostic has both a Studio fix and a rewrite of the line (such as replacing with a name of similar spelling), every screen offers the Studio fix first (the order recommended in `fixes`),
and the rewrite of the line can be chosen too (two buttons in the code view's tooltip and on the problem card, and the row's menu in the check list).
Fixes are applied the same way as replace in all files: the open file receives editor changes (⌘Z undoes them), and other files go through the write API (kept in the change history). Lines that changed after the check are skipped.
"Delete all," "Fix all" and "Fix" remember all the files they changed as one action, and "Undo" in the notice undoes them all at once (the same as replace in all files).
Runtime problems found in test play (see "Test play tools" above) are gathered in the "Found in test play" category and counted in the number of problems and the badge (they're cleared when a new test play opens).
The all-routes test runs each file up to 8 times, widening to ways of choosing not tried yet (it stops early when every way of choosing has been tried; the same as `lim coverage`; "Covering every branch" in [ci.md](ci.md)).
The all-routes test also warns about destinations that plugin commands reported to the flowchart but that never appeared as a choice when run without a screen (since neither route search nor the all-routes test can get past them; [plugins.md](plugins.md)).
While running, the all-routes test card (the "No problems" line when there are no problems) shows "Run N of M (file)," a progress bar and "Stop" (`POST /coverage/stream`, which sends progress after each run;
`onProgress` and `signal` of `coverage` in `@liminalia/runtime`). If it fails, the reason appears in a notice and on the card.
The result is saved in `.liminalia/coverage.json` with the hashes of the files at the time of the run (not when stopped), and shown again after reopening (`GET /coverage`; the flowchart's Unreached and the endings panel use it too).
If the script changed after the saved result (a different content hash, or a file that is gone), the card says "N files changed after the run" (hover to see the names of the changed files).
The result also records the engine version and a hash of what changes the run besides the scripts (`liminalia.json`, `cast.json`, the project data and the plugin commands).
If the version differs from the current one (including results saved before the version was recorded), or those changed after the run, `GET /coverage` adds `outdated` and the screen doesn't show it as the current result
(the percentage is dimmed, with "This result is from an earlier version of Liminalia" or "Project settings, characters, or data changed after the run" and a prompt to run it again;
it isn't rerun automatically because the all-routes test is heavy on large projects). It is checked again when characters, settings or data change outside.
Below the list of problems (the "No problems" line when there are none) and the number of endings is "Find overflowing pages." Click it to turn every text page of every script (dialogue and narration, including inside `@if`) into
the same pieces the runner puts in the message window (characters, ruby, line breaks, decorations such as bold and text size; `model/overflow.ts`), and have them measured by an invisible player opened off screen
(the same device as the preview, with the game settings, theme and project CSS as they are) (`stage-measure`; the player uses `DomHost.measurePages` to put the text, without the typing animation, into an invisible copy of the current
message window). Pages where the text area needs scrolling, where the message window grows beyond its empty size, or where the message window has a fixed height and the text goes past its inner bottom edge
are listed in the check as the warning "Overflows the message window (N lines; it fits M)" (click one to go to that line), and counted in the number of problems and the Check badge.
The open file is measured with its content before saving. The original and each translated language (`lang/<language>.json`; only lines with translations use them, and scene translations `contexts` and speaker name translations are used just as the runner does)
are measured with each language's player (fonts and text sizes per language), and warnings for translations name the language, as in "The en translation overflows the message window."
When there are translated languages, a selector for the languages to measure (All languages, the original, or each language; the default is all; remembered in that device's localStorage) appears to the left of the button.
Expression values (`{= …}`) are measured as the characters of a literal string or of a variable with a string initial value (`variables` in liminalia.json); conditional expressions as the longer of both sides if both are known, or else as 4 full-width characters.
Inline images are measured as one square character the height of the image (or the text size if not written). Inline commands and click waits don't become characters (even when divided by click waits, the text continues in the same message window, so a line is measured as one page).
The result isn't remembered; click again to measure again.

Below that is **TODO comments**. It lists the comment lines that start with a marker word (TODO, FIXME and XXX by default), such as `// TODO: …`, from every file
(the word, the comment text, and the file and line; click one to go there; letters ignore case, and words followed by more letters or digits, such as TODOS, are left out). It searches with a regular expression through `POST /search`, the same as search across files,
so the open file is searched in its content before saving (`model/todos.ts`, `panes/todos.ts`). It searches again when the Check screen opens and after each check.
"Marker words" changes the words (separated by commas; leave it empty to go back to the defaults). The words are kept in Studio data (`todoWords` in `.liminalia/studio.json`) and aren't included in the game.

Below that is **Measure performance**. It is the same measurement as `lim profile` (`POST /profile`; "Development tools" in [player.md](player.md)).
Choose the start position ("New game" (`entry` in `liminalia.json`) or a script file) and the number of pages (30 by default, up to 200), then click "Start measuring,"
and it opens the game without showing it and measures while paging through it. While measuring, it shows "Page N of M," the current position, a progress bar and "Cancel" (nothing is saved if canceled).
When done, a single card shows a one-line verdict ("Runs smoothly" if the lowest frame rate is 50 or more and long frames are 1% or less; otherwise, what to look at),
the frame rate (average and lowest), long frames (count and the longest), memory (peak, start and end, and the peak number of DOM elements), the number of assets loaded (images, sounds),
the assets that took longest to load (5), and the collapsed "Per-page numbers," noting that it was saved to `exports/profile/profile.md` and `profile.json` (the same as `lim profile`; in the Japanese display, `計測.md` and `計測.json`).
Measuring continues even if you move to another screen. One at a time (asking while measuring returns 409).

Below the list of problems are cards for the character counts (dialogue, narration, choices), dialogue with voices and the number of spelling variant groups, tables of the breakdown by file, scene and speaker, and the list of spelling variant groups
(`GET /stats`; the same tally as `lim stats`, recounted when the Check screen opens and when the syntax check is fetched again). Click a table row or a spelling variant location to go to that line,
and "Exclude" on a spelling variant group adds it to `stats.variants.ignore` in `liminalia.json` ([text-stats.md](text-stats.md)).
The "Progress" card next to the character count cards shows today's progress, the share of the character goal, daily progress (14 days) and the estimated play time ("Progress" in [text-stats.md](text-stats.md)).

## Reloading and saving

When project data (.json in `paths.data`) or plugin code changes and only the player reads it, the dev server doesn't reload the whole Studio;
it tells only the player (the preview) to reload (`liminalia:player-reload`), and the preview shows the same line again after reconnecting. When code loaded from Studio's entry point
(such as a plugin's `./studio`) changes, Studio reloads too, as Vite does by default.

**Refresh** reloads a project that was changed outside Studio (another editor, an AI, git and so on). It saves the changes waiting to be saved first, then with `POST /reload`
has the dev server reload the scripts, characters and assets, and fetches the table of contents, the open file (keeping its undo history), the current position data, the duration bars, the preview and the syntax check again.
Changes to scripts, `cast.json` and the asset folders are watched all the time and reloaded automatically, so use Refresh for changes the watcher doesn't detect (such as after a mass rewrite) or
when you want to be sure everything is up to date. If the project settings (`liminalia.json`) or the code of command plugins (.ts and .js in the `./commands` folder) changed,
plugins already loaded by Node can't be swapped, so `POST /reload` returns `{ ok: false, restart }`. The desktop app's client (opened with `?desktop=1`)
tries to go to `STUDIO_RESTART` (`?file=&line=`), and the app catches it, restarts the dev server and reopens the same line of the same file
(the test play window closes). In a browser (`lim studio`), it tells you to restart.

**Outside changes and screens**: the Characters, Assets, Flowchart, Variables, Game settings, Game screens, Project (including Translation), Plugins, Voices and Comments screens
redraw with the new content when a file changes outside while they are open (another app, AI, another window; if you are typing in a field, after you leave it).
Saving from a screen that still shows the old content doesn't overwrite the outside change: Characters and Voices write with the version they read and, if it changed, don't save but reload and tell you.
Game settings (including command defaults), the parts panel in Game screens, Project and Plugins send the hash they read and, if it changed, merge item by item before saving.
Variables, Assets and Comments write only what you changed. Which screen shows which files and how it handles them is the list in `client/view-sources.ts`; add new screens there
(`test/view-sources.test.ts` fails for screens that aren't listed, and for screens whose outside changes and saves with old content aren't checked).
The dev server also starts watching folders that didn't exist when it opened (`reviews/`, `lang/`, the data and asset folders) once they are created.

**When the same project is open in two windows**: each window sends its id to the dev server in a header (`x-liminalia-window`), and when a script is saved, created,
renamed or moved to the trash, the dev server tells every window with `file-changed` and the like, adding the id of the window that saved it (`by`). The window that saved skips its own notice,
and the other windows load it the same way as a change made in another app (merging if you're in the middle of typing). Project data (`data-changed`) works the same way.

**When saving fails**: if Studio's server can't be reached, a bar appears at the top with how to fix it (restart `lim studio`; in the desktop app, reopen the project) and
"Save again" (it also retries automatically). When saving is refused (4xx, 5xx), the reason is shown once in a notice. Each time saving fails, the content waiting to be saved is
backed up in localStorage (`unsaved-backup.ts`; per project id and file), and the backup is removed once saving succeeds. When you reopen the same project and open that file,
if the disk is still as it was then, the content is restored from the backup with "Undo," and if it changed elsewhere, the notice shows a "Restore from backup" button
(once restored, the backup is removed and the restored content waits to be saved as usual). When "Continue Without Saving" or "Close Without Saving" (the browser's "Leave") is chosen
in the confirmation before leaving, the changes were deliberately thrown away, so the backup is removed too (when `pagehide` comes after `beforeunload` stopped). Reopening in another process
can let the new page read first, so a backup kept after the confirmation was shown gets a mark (`left`); on reopening it isn't restored automatically,
and "Restore from backup" in the notice can restore it once (the mark is removed if you cancel the confirmation and keep writing).

**Plugins that can't be loaded**: `lim studio` and Studio open without plugins that can't be loaded (the package isn't found, the folder or `package.json` is missing,
loading `./commands` throws), and show a bar at the top ("Opened without plugins that can't be loaded: X (reason)" and "View in Check").
The "Plugins" category of the check shows a `plugin-load` diagnostic ("Can't load plugin X (reason)"), and findings about undefined commands that may belong to that plugin
are folded into one ("Adding a plugin" in [plugins.md](plugins.md)). The reason isn't Node's raw message but one of: the package isn't found, the folder is missing,
`package.json` is missing, the entry file is missing, a module it loads isn't found (npm install), or a syntax mistake (`pluginErrorReason` in `@liminalia/project`),
and it takes the same form when `lim check` and others load plugins without leaving them out, and when the dev server side's entry (`./studio-server`) can't be loaded.

**Confirm before leaving**: only when the open script has changes that are unsaved, being saved, failed to save or in conflict (`FileSync.unsaved`), closing, reloading
and switching projects (the phone app's "Open another project" button) are stopped first (`beforeunload`; the browser's confirmation appears, and saving starts right away when it stops). If everything is saved, nothing stops.
Other files aren't checked, because Studio doesn't switch files unless it can save before switching. For "Open another project" in the phone app, the confirmation may not appear in an app added to the home screen,
so it saves the changes waiting to be saved first, and if it can't save, it doesn't move and shows the reason. In the desktop app, closing a window goes through the existing save before closing (if it can't save,
it asks about "Close Without Saving") and then closes; leaving the page by reloading or similar makes the app show a confirmation dialog ("Cancel," "Continue Without Saving") through `will-prevent-unload`,
so Electron doesn't silently stop (`packages/studio-desktop/src/main/unload-guard.ts`; once you decide to close, it doesn't ask twice).
Test play, export, switching the language and asking the app to restart (`STUDIO_PLAY` and so on; the page doesn't leave) aren't stopped.
How to check it: `npx tsx packages/studio-desktop/scripts/nav-check.ts [--shots folder]` (it also checks the test play window of "Play from Here").

## Test play and the desktop app

### Test play save data

Test play saves, read text, unlocked content and the values in Settings stay in the storage of the same origin as Studio (in the desktop app, an origin whose number is fixed per project).
"Delete test play save data…" in the "…" menu and in ⌘K deletes them after confirming (`client/play-data.ts`; it deletes from IndexedDB and localStorage only the keys that start with `liminalia:<project ID>:`,
and keeps Studio's own settings; an open test play is told that they were deleted). In the desktop app, "Project → Delete Test Play Save Data…" in the menu deletes them too
(it closes the test play window first, then empties IndexedDB with `session.clearStorageData`).

### Exporting (desktop app)

"Project → Export…" in the menu and "Export" in the top bar open one export window per project (`packages/studio-desktop/src/main/export.ts`; the window is `src/pages/export.*`).

- "Project settings" shows the version, the icon (red when it's missing or can't be found), signing for the Mac and Windows versions (only when that platform is selected;
  decided the same way as `lim build`, from environment variables, then `liminalia.json`; red when the credentials aren't enough), encryption, and where save data is stored and how it's protected. Click one to open that field in the project settings
- When it's done, even if it succeeded, it shows "N warnings" and what they are (warnings from the check and the "警告: " (warning) lines of the export)
- "Open in browser" on the row of an exported browser version serves that folder from a temporary server on 127.0.0.1 (stopped when the export window closes) and opens it in the default browser.
  "Run a playthrough" plays from "New game" to the end automatically in a hidden window (the same steps and defaults as `lim playtest`; if it gets stuck, it takes a screenshot to `<export folder>/playtest/run-1.png`)
- Below what was exported, the next steps toward publishing are shown (`shared/export-guide.ts`): "How to publish on the web" (/howto/export-web/ on the website) if there is a browser version,
  and "How to distribute" (/tutorial/publish/) if there is a Mac, Windows or Linux version. Clicking one opens that page in the default browser (the /en page when the app is in English)
- The export window isn't a child of the project window. If you close the project during an export, the window stays and keeps exporting, and reopening the project brings you back to it.
  Closing the export window or quitting the app during an export asks "Stop and Close" or "Stop and Quit." A second export to the same destination doesn't start.
  App updates aren't swapped in during an export, and once swapping starts, no new export starts until it finishes
- How to check it: `npx tsx packages/studio-desktop/scripts/nav-check.ts [--shots folder]`

Other things in the desktop app:

- "Test Play" (⌘R) in the menu opens after Studio's pending saves are done (the same as "Test play" in the top bar)
- The start screen closes only once, when a project window has opened and its dev server is up (it doesn't wait for Studio to finish loading; clicking a project window doesn't close it along with what you were typing for a new project).
  Recent projects also scroll sideways with the vertical wheel
- A new project lets you choose the project ID (made from the title and shown, and editable; the same rules as `lim new`) and the source language (the app's language by default, or Japanese when importing a TyranoScript project).
  The sample is made from Waiting for Stars, the English sample story, when English is chosen, or from 星を待つ丘 for Japanese (the same as `lim new --lang en`; the character IDs are Akari and Sou).
  The ID is made from the letters, digits and kana of the title (kana become Hepburn romaji); kanji can't be read, so they're dropped (`chooseProjectId` in `@liminalia/project`). If the title is mostly kanji, the date and time are used,
  and when only part of the title or the date was used, the note under the field says the ID names the export folder and the save data and that you can type your own
  The location is remembered from the last project you made (`new-project.json` in userData; Documents/Liminalia if it's gone)
- With the new project template "A TyranoScript or TyranoBuilder project," choosing the folder to import from fills in the title and the screen size, and creating it imports the scripts,
  copies the assets and sets "New game" all at once (the same as `lim new --from-tyrano`; [tyrano-import.md](tyrano-import.md)). After opening the new project,
  it reports the import counts, and "Open report" opens `import-report.md` in the default browser in a readable form. When "Open Project" is used on a TyranoScript project folder
  (`data` or `data/scenario` is fine too), "Import into a new project" opens the new project form with the import source filled in
- Plugins that can't be loaded (packages that can't be found and so on) are left out when opening, as with `lim studio` (shown in the bar at the top of Studio and in the "Plugins" category of the check)
- Studio is opened after the dev server's Studio API (`/project`) has finished reading the project, showing "Opening" until then (a project opened for the first time can take a while even after the dev server is up;
  it used to give up after 10 seconds and stay on "Not ready"; `shared/studio-wait.ts`). After 10 seconds, "Reopen" (which restarts the dev server) appears on "Opening", and the dev server logs where the time went when opening takes more than 3 seconds.
  When starting the dev server (until it prints "開発サーバー: URL") takes more than 3 seconds, the breakdown is logged too (reading the settings, loading the Vite config file, preparing the Vite plugins,
  creating the Vite server, starting the plugins, dependency scan and listening; `lim studio` and `lim dev` do the same; `StartupTimes` in `packages/cli/src/web.ts`)
- On the Mac, if the project is under Documents, Desktop, Downloads, iCloud Drive and similar places and the dev server isn't up after 4 seconds, "Opening" says
  "macOS is checking access to this folder" and asks you to check whether a confirmation dialog is hidden behind other windows; the log says so too (it goes away once the server is up.
  macOS asks for access to these places per app, and anything reading them waits until the dialog is answered; `shared/mac-access.ts`)
  When the dev server refuses (no Studio API, the project can't be read), the "Not ready" screen shows the reason and "Reopen"
- For Claude Code in "Connect an AI Assistant…," `claude` is looked for in the login shell's PATH and common install locations (`~/.local/bin`, `/opt/homebrew/bin` and so on)
  (they often aren't in the PATH of an app started from the Dock). If it isn't found, the places searched are shown

### Reopening the last project at launch (desktop app)

When the app starts without being given a project (opened from the Dock or the Start menu), it reopens the projects you had open before. If there are none to reopen, it shows the start screen as before
(`packages/studio-desktop/src/main/session-store.ts`; the rules are in `src/shared/session.ts`).

- The record is `session.json` in userData. Each time the open projects change, it becomes the list of open projects. When all projects are closed (returning to the start screen), the previous list is kept,
  so even if you close the project window before quitting the app, that project opens next time. While project windows are closed one by one to quit, it isn't rewritten
- When a project is given through the launch arguments or by opening a file (such as dropping `liminalia.json` or a folder on the icon), only that project opens
- Projects that are gone (folders without `liminalia.json`) are skipped
- Turn it off with "File → Reopen Last Projects at Launch" in the menu (when off, it always starts from the start screen)

### App updates (desktop app)

An app packaged with an update source checks for a new version shortly after launch and with "Check for Updates…" (in the app menu on the Mac, under Help on Windows), and if there is one, shows the version and the changes in a small window
(`packages/studio-desktop/src/main/updater.ts`; the window is `src/pages/update.*`; without an update source, the item isn't shown). "Update and Restart" downloads and verifies it, finishes pending saves the same way as when closing a project window
(canceling the close cancels the update too), replaces the app and restarts. If the app is in a place that can't be written to, it only goes as far as downloading,
and shows where it was downloaded. It doesn't start in the middle of an export. How the release files are made and how it works: ["Distributing the authoring app (Liminalia Studio)" in distribution.md](distribution.md).

### Report a problem (desktop app)

Help → Report a Problem… (or "Report a problem" in Help on the start screen) makes a report with what happened, the app version and OS, an excerpt of the settings of the project that was in front
(title, ID, version, screen, languages, plugins, and only the names of the export settings) and the end of the log (200 lines; the home folder becomes `~`)
(`packages/studio-desktop/src/main/report.ts`). You choose what to include and see exactly what will be sent. Besides Copy and Save…, an app with a report page set opens it
with "Open the report page" ("Where problem reports go" in [distribution.md](distribution.md)).

## When the window crashes or freezes (desktop app)

`packages/studio-desktop/src/main/crash-guard.ts` (`guardCrashes()` in `main.ts`). Everything is recorded in the log ("Help → Open Log").

- If a window's process ends abnormally (`render-process-gone`; a normal end on closing is excluded), that window is reopened. Studio returns to the file and line it had open.
  If the same window ends abnormally 3 times within 1 minute, it stops reopening and tells you ("Reopen," "Open Log," "Close")
- If a window stops responding (`unresponsive`), it waits 30 seconds, and if it doesn't recover, asks for pending saves, then stops the process and reopens it (counted the same way as above)
- Unhandled exceptions and Promise rejections in the main process, and abnormal ends of the GPU and other processes, are recorded in the log, and the app keeps running

What reopening loses: Studio saves every time typing pauses for 1 second (the change history is in `.liminalia/history/`), and nothing can be taken out of a window that ended abnormally.
What is lost is less than the last 1 second of typing before the crash, the undo history, a panel in the middle of choosing between overlapping changes, and unsaved work in plugin screens that keep their own pending saves.

## The game's aspect ratio

The preview, the separate window, full screen, the timeline preview, the game settings preview, command samples, thumbnails and the images on flowchart cards follow the aspect ratio of `screen` in `liminalia.json` (`work-screen.ts`, `work-screen.css`; `work-aspect`, `work-portrait`, `--work-aspect` and `--work-ratio` are written on html; nothing is written for 16:9 games).

- For portrait games, the preview is limited to 56% of the screen height (72% when enlarged) so it doesn't get too tall in the right panel, and is centered
- The separate window opens 1280 wide for landscape, and for portrait at 720×1280 shrunk to fit within 90% of the screen height
- Flowchart cards keep their size (decided by the layout), keep the image height and make the width match the game's aspect ratio
- Thumbnail images and flowchart images crop the middle of the background (`ui.backgroundFocus` isn't used; the preview and screenshots use it)
- Asset guesses: for portrait games, 16:9 images are taken as backgrounds too, besides images with the game's aspect ratio

## Principles

- The single source of truth is the `.lim` text. The screens only read and draw it, and every write goes through `PUT /file` (the write API)
- If the content on disk changed after it was loaded, it isn't saved (409 and the current content are returned). Old content never overwrites new content.
  The parts of `liminalia.json` that the client replaces with its loaded copy (the game settings `ui`, extras `extra`, the basics and export items) and translations (`lang/<language>.json`)
  are also saved with the hash from when they were loaded (for `liminalia.json`, the hash of that part written as JSON), and if they changed, 409 returns the current content (`PartRead`, `PartWrite`).
  The client merges them as it does scripts (`part-sync.ts`, `model/merge-json.ts`; items are compared one by one, changes that don't overlap are both taken in, and when the same item was changed to different values,
  you choose in the merge panel; after merging and saving, it tells you and reloads the panel). Just opening doesn't save
- The content of `liminalia.json` and translations before saving is also kept, by the same rules as the change history, in `.liminalia/history/@config/` and `.liminalia/history/@lang/<language>/` (there is no panel to restore them from the screen)
- The content before each save (the change history) is kept with a date and time in `<project>/.liminalia/history/<file>/`. Automatic saving saves every time typing pauses for 1 second, so recent entries are kept in detail and older ones are thinned more coarsely
  (`server/versions.ts`: the newest 5 as they are, one per minute up to 10 minutes ago, one per hour up to 24 hours ago, and one per day before that, keeping the last one in each interval;
  up to 50 entries and 16 MB per file in total; beyond that, the oldest are deleted, and the newest is always kept). Project data (`@data`) is kept by the same rules.
  Saving writes to a temporary file and then replaces the original (so stopping partway never leaves a half-written file)
- No build output for the preview is made in the project. Read-only APIs (GET, `POST /check`) write nothing. The all-routes test (`POST /coverage`, `POST /coverage/stream`) saves its result only in Studio's data, `.liminalia/coverage.json`.
  Only exports the writer asked for (screenshots in `exports/shots`, performance measurements in `exports/profile`, translations, and recording scripts in `exports/…`) are saved in `exports/`
- Projects made by importing (with `import.tyrano` in `liminalia.json`) have `importManaged: true`. Edits are overwritten by the next `lim import`

## Endpoints

All of them are under `/__liminalia/studio/api`. Files are paths relative to the script folder, without the extension (`start`, `part1/chapter2`).

| API | Returns |
|---|---|
| `GET /project` | Project information, the list of files (line counts, hashes, labels), speakers, characters, command specs, and the asset list (below) |
| `GET /file?file=` | The content and hash (the first 16 characters of SHA-256) |
| `PUT /file` | Saves `{ file, text, baseHash, check? }`. If baseHash differs from the disk, 409 (with the current content). For a new file, baseHash is null. After saving, it checks the whole project once and returns the whole result (`check`, the same as `POST /check`) and that file's part (`diagnostics`). With `check: false`, it doesn't check (for saving several times in a row, such as replacing, and then calling `POST /check` once at the end). `liminalia.json` is reloaded only when its text changes |
| `POST /search` | `SearchRequest` (`{ query, regex?, body?, kana?, caseSensitive?, open? }`) → `SearchResult` (for each matching file, the hash and the lines, matched ranges and regular expression groups; up to 5,000 lines). An unreadable regular expression returns 400 |
| `GET /history?file=` / `GET /history/item?file=&id=` | The list of the change history (newest first), and the content of an entry |
| `POST /check` | The same check as `lim check` (including checking that assets exist). Each diagnostic has its category, with counts per category |
| `POST /coverage` | The same as `lim coverage`: the all-routes test run without a screen, and the diagnostics from running (the body `{ runs }` sets the most runs per file; 8 by default, stopping early when every way of choosing has been tried). Saves the result (`hashes` are the file hashes at the time of the run) in `.liminalia/coverage.json` |
| `POST /coverage/stream` / `GET /coverage` | The same, sending `CoverageEvent`s one line at a time with progress after each run (`progress`, and `done` at the end; closing the request stops it) / the saved result (null if none) |
| `GET /reviews` / `POST /reviews` | Review comments (`ReviewList`: the threads and the name attached to comments) / takes a `ReviewAction` (`create`, `reply`, `edit`, `resolve`, `delete`, `anchor`; `create` and `anchor` also take `end`, the last line of a range; `edit` only for comments whose author name matches the current name), rewrites `reviews/` and returns the list |
| `POST /reviews/import` / `GET /reviews/shot?path=` | Imports feedback from a test build as comments (`{ files: { name, data }[] }`, where data is the content of a `.liminalia-feedback.json` or a list of them; returns `FeedbackImportResult`) / the screenshot attached to feedback (only inside `reviews/shots/`) |
| `GET /stats` / `POST /stats/ignore` / `POST /stats/unignore` | Character counts, spelling variant candidates and excluded groups (`TextReport`, the same tally as `lim stats`) / adds the group `{ id }` to `stats.variants.ignore` / removes it |
| `POST /reload` | Reloads a project changed outside Studio. `ReloadResult` (`{ ok: false, restart }` if the settings or plugins changed) |
| `GET /data?name=` | Project data (.json in `paths.data`). `DataText` (used by plugin screens) |
| `PUT /data` | `DataWriteRequest` → 200 `{ ok: true, hash }`, 409 `{ ok: false, current }`. The change history is in `.liminalia/history/@data/` |
| `POST /asset?kind=&path=[&overwrite=1]` | Adds an asset (the request body is the file itself; only images, sounds, videos, subtitles, fonts and shaders; the extensions are the same table export uses for what goes into the game, `MEDIA_EXTENSIONS` in `@liminalia/lang`). The background, sprite and image folders accept only images, BGM, sound effects and voices only sounds, and videos only videos and subtitles; otherwise 400 with the allowed extensions. Other, and folders the project added, accept anything. The same name returns 409 |
| `GET /voices` | The voice file and status for each line of dialogue (`VoiceList`, the same rules as `lim voice-script`), and the hash of each file |
| `GET /assets/list` / `GET /assets/usage` | The files in each asset folder (with sizes; for images, also `width` and `height` if they can be read) and the folders inside / where assets are used (`"kind/path"` → script lines, characters, project settings) |
| `POST /assets/rename` | Renames with `{ kind, from, to }` (folders too). Also rewrites the script lines that refer to it (through the write API, kept in the history) and the characters, and returns the references that couldn't be rewritten |
| `GET /trash` | The contents of the trash (`TrashEntry[]`, newest first: what (kind and path, up to 20), when it was moved, and the total count) |
| `POST /assets/trash` / `POST /assets/restore` / `POST /assets/folder` | Moves to `.liminalia/trash/<id>/` (up to `TRASH_KEEP` entries) / restores with `{ id }` (409 if the destination is taken) / makes a folder |
| `POST /assets/samples` | Copies the template's sample assets (CC0) into the asset folders (files with the same name aren't copied) → `{ added, skipped }` (`"kind/path"`) |
| `POST /assets/requests` / `GET /assets/requests.csv` | Writes the asset request list (missing assets, variants and voices) to `exports/asset-requests.csv` → `{ path, count }` / that CSV (English headings with `?lang=en`) |
| `POST /assets/trash-many` | Moves an `AssetTrashManyRequest` (`{ items: [{ kind, path }] }`, files only) to the trash under one id. If any is missing, nothing moves |
| `POST /files/create` / `duplicate` / `rename` / `trash` | Creates a script file (`{ file, text? }`), duplicates, renames (`{ from, to }`; jump targets, history and entry too), moves to the trash (`{ file }`; restore with `/assets/restore`) |
| `POST /scenes/move` | `SceneMoveRequest` (`{ file, labels, to }`; labels are scenes placed consecutively in the file) → `SceneMoveResult` (the rename result plus `created`, whether a file was created, and `joins`, the lines added to keep the flow). Creates `to` if it doesn't exist. Non-consecutive scenes, the top of the file, and the same name at the destination return 400 or 409 |
| `POST /labels/rename` | `{ file, from, to }` → `LabelRenameResult` (the rewritten files, the number of lines, the places in liminalia.json, `entry` (applied after a restart), the languages whose translation keys were replaced, and `left`, the references that couldn't be rewritten). Invalid names return 400, and duplicates within the same file 409 |
| `GET /settings` / `POST /settings` | Reads the basics (including `check` for the check and `format` for formatting) and export items and their hash / saves `{ settings, baseHash }` (200 `{ ok: true, hash, restart }`, 409 `{ ok: false, current }`) |
| `POST /check/severity` | Writes the severity for a code to `check.severity` in liminalia.json with `{ code, level }` (removes it if `level` is null; "Don't show this kind" is `off`) |
| `GET /scenes` / `POST /scenes` | Scene info (`scenes` in liminalia.json) / saves the info of one scene with `{ key, info: { pov, date, place } }` (empty strings are removed, and other fields are kept; 404 for a scene that doesn't exist) |
| `POST /script-export` | Exports the script for proofreading to `exports/script/` with `{ format: "text" \| "html" }` and opens the folder (`{ folder, files, lines }`) |
| `GET /extra` / `POST /extra` | Reads the extras lists (`extra` in liminalia.json) and their hash / saves `{ extra, baseHash }` (removed if empty; 409 as for `/settings`) |
| `GET /i18n` / `GET /i18n/file?lang=` / `PUT /i18n/file` / `POST /i18n/languages` | Languages, translation progress and the hash of the language list / the translations synced to the current script, the script locations and the file hash (null if none) / saves translations with `{ lang, file, baseHash }` (409 returns the current translations) / saves the playable languages with `{ languages, baseHash }` (409 returns the current list; the client applies the same change to the current list and saves again) |
| `GET /plugins` / `POST /plugins` | `{ plugins, hash }` (the project's plugins, their contents and the hash of the list) / saves the plugin list with `{ plugins, baseHash }` (400 if one can't be found; 409 returns the current list, and the client applies the same change and saves again; takes effect after a restart) |
| `POST /plugins/create` | `{ name, parts }` → `{ spec }`. Creates a plugin with a sample in `plugins/<name>` and adds it (409 if it exists) |
| `POST /plugins/update` | `{ spec, name?, description? }`. Rewrites the package.json of a plugin inside the project folder |
| `POST /plugins/reveal` | `{ spec }`. Opens the folder of a plugin inside the project folder in the OS file browser |
| `GET /ui` / `POST /ui` | Reads the game settings (`ui` in liminalia.json) and their hash / saves `{ ui, baseHash }` (400 if the shape is wrong; removed if empty; 409 as for `/settings`) |
| `GET /command-defaults` / `POST /command-defaults` | Reads / saves the command defaults (`commandDefaults` in liminalia.json) (unknown commands or parameters and type errors return 400; removed if empty) |
| `GET /ui/themes` / `POST /ui/theme` | The list of available themes (the bundled ones and the project's `themes/<id>/theme.json`) / applies the theme `{ id }` (copies its assets to `assets/image/themes/<id>/`, saves `ui` and returns it; applying a portrait-only theme to a landscape game is refused with 400) |
| `GET /screens/rules` | The rules for screens that can be built from a template (`ScreenTemplateRules`; whatever starts the dev server passes it with `setScreenTemplateRules`; `null` if not) |
| `GET /screens/files?screen=` / `PUT /screens/file` | The screen's template and screen JS, whether it is registered, and the plugin that replaces it first (`ScreenFiles`) / `{ screen, kind, text, before }` writes the whole template or screen JS (409 if it changed after it was read) |
| `POST /screens/copy` / `POST /screens/script` / `POST /screens/reset` / `GET /screens/diff?screen=` | The same as `lim screens copy`, `js`, `reset` and `diff` (`@liminalia/project/screen-copy`). Writes return an `undo` entry for ⌘Z |
| `GET /screens` | The list of built-in screens (`ScreenInfo[]`: name, owning package, whether Game screens can open it, the content it provides, why it can't be opened, and the hooks for the four tiers in the table in screens.md). Studio doesn't load the player side, so whatever starts the dev server (`packages/web/vite.config.ts`, the mobile version's Service Worker) passes it with `setScreenTable` |
| `POST /ui/theme/save` / `POST /ui/theme/trash` | `{ name, overwrite? }` saves the current look to `themes/<id>/theme.json` (`ThemeSaveResult`; the same name returns 409; for portrait games, `orientation: "portrait"` is written too) / `{ id }` moves a project theme to the trash (restore with `/assets/restore`; bundled themes return 400) |
| `GET /variables` / `POST /variables/set` / `POST /variables/rename` | The list of variables (initial values, and the lines that read and assign them) / sets or removes an initial value / renames |
| `POST /macros/rename` | `{ from, to, file? }` → `MacroRenameResult` (the files rewritten, the number of lines, and whether keys of `commandDefaults` were rewritten). An invalid name is 400, and 409 if a macro with that name already exists. When the `@define` of `from` is in two or more files, `file` chooses one (409 without it, 404 if that file doesn't have it) |
| `GET /cast/lines?speaker=` | `SpeakerLine[]` (the dialogue of the given speakers, in file name order and line order) |
| `GET /cast/backups` / `GET /cast/backups/item?id=` | The change history of cast.json (newest first; `HistoryEntry`) / the content of one entry (`current` gives the current cast.json) |
| `GET /undo/state` / `POST /undo/apply` | The state of the record (`undo`) of an action that moved files (`applied`, `undone`, `changed`, `gone`) / undoes or redoes with `{ id, to: "undone" \| "applied" }` (`server/file-undo.ts`) |
| `GET /cast/usage` / `POST /cast/rename` | The number of script lines per character ID, the number of lines of dialogue per speaker name, and the number of lines that specify each variant (`variants`) / renames with `{ kind: "cast" \| "speaker", from, to }`, rewriting the script references and cast.json (with `speakerToo: true`, the display name with the same name as the character ID changes too, as one action) |
| `GET /studio-state` / `PUT /studio-state` | Studio's data (the shared part `STUDIO_SHARED_KEYS` in `.liminalia/shared.json`, the rest in `.liminalia/studio.json`: face crops `faces`, positions of scenes moved on the flowchart `mapPositions`, parts panel favorites `favorites`, bookmarks `bookmarks`, the character goal and daily counts `textGoal` and `textDaily`, breakpoints `breakpoints`, character notes `castNotes`) / replaces the whole thing with `{ state }` (items with the wrong shape are dropped). Nothing is saved to the game data |
| `GET /map/cast` | Scene (flowchart id) → the people who speak in that scene (in the order written; for the flowchart's character filter; `sceneSpeakers` in `model/map-filter.ts`) |
| `GET /sweep?file=[&from=&to=]` | The state of each line of that file as in the real game (below). from and to narrow the range of lines (the states of command lines are narrowed too, and the screen states are limited to those used in the range and renumbered) |
| `POST /shot` | `ShotRequest` (`{ file, line, show, cast? }`; show is the `stage-show` or `stage-still` requested from the preview) → `ShotResult` (`{ path, width, height }`). Captures the preview's screen at the game's size and saves it in `exports/shots`. Without Chromium, `CHROMIUM_MISSING_STATUS` (424) |
| `GET /shots/file?name=` | A PNG directly under `exports/shots` (for "Download" in the browser) |
| `POST /shot/play` | `{ start?, skip?, title?, lang? }` → PNG. As with `lim shot`, captures the click wait of the page skip pages after start (`[N]` in `lim trace`; when skip is 1 or less, it also stops at choices and screens waiting for input before the first page), or the title screen, at the game's size and returns it (in the language `lang`, if given; `lim shot --lang`) (not saved to a file; the `screenshot` of the AI's MCP; [mcp.md](mcp.md)) |
| `GET /server` | `{ root, pid }`. Answers without waiting for the project to load. The AI's MCP uses it to check the dev server in `.liminalia/studio-server.json` |
| `POST /profile` | `ProfileRequest` (`{ target?, pages? }`) → sends `ProfileEvent`s one line at a time (`application/x-ndjson`; each line is a `StreamLine`): `progress` as it advances, and `done` at the end (the `ProfileReport` and the folder it was saved in). Closing the request stops the measurement |
| `POST /regress` / `GET /regress/file?kind=&name=` | `{ update?, threshold? }` → sends `RegressEvent`s one line at a time (`progress`, and at the end `done` with the `RegressResult`) / the `baseline`, `current` and `diff` images in `.liminalia/regress` |
| `POST /voice-lock` | Locks the numbers of numbered voices, and returns `VoiceLockResult` (the saved file, the number of lines, the breakdown of carried-over and added numbers, and lines whose numbers split) |
| `GET /sweep/stage?file=` | The data for the duration bars. Returns, for the whole file, the background, BGM (file, volume, loop), looping sound effects (per channel) and sprites (name, variant, sprite set, position, flip) at each line (identical states are merged into one, and lines point to its number) |

The write APIs accept only requests from the same origin. The dev server watches the script folder and `cast.json`, and sends outside changes (other editors, AIs, imports)
through the Vite WebSocket custom event `liminalia:studio` (`file-changed`, `file-added`, `file-removed`, `cast-changed`).
It doesn't send them for the client's own writes. It also watches the asset folders and sends `assets-changed` when files are added or removed (once for a run of additions).
Large responses (16 KB or more) are returned gzipped if the request accepts it.

The asset list (`ProjectInfo.assets`) is the paths relative to each asset folder (`bgimage`, `fgimage`, `image`, `bgm`, `sound`, `video`, and
the folders the command specs list as places to look) (in name order; names starting with `.` are left out).

Check categories (`category` of each item in `CheckResult.diagnostics`, and `counts`): `syntax` (syntax errors), `command` (commands and parameters),
`cast` (characters, sprite sets, variants, standing positions, the shape of cast.json), `target` (jump target files and labels), `asset` (missing assets),
`plugin` (diagnostics returned by a plugin's `check`, and exceptions thrown by `check`; [plugins.md](plugins.md#命令commands)).

## Current position (the state at each line)

The preview, the state at this line and the duration bars share the "state as in the real game" at the cursor line (the result of running from the beginning along a route).

1. **Route**: run from "New game" without a screen, and find a route that first enters that file (first runs a command in that file).
   The point of entry is just before running the first command of that file (running the inside of `@define` as a macro doesn't count as entering).
   The search is the same backtracking search as `lim build --seed` (`findRoute` in `@liminalia/runtime`). At choices, it picks the next one each time it returns to the same choice,
   and if a run ends without arriving, it changes the last choice to the next number and tries again. It also records the entry points of other files it passes on the way
   (the search order doesn't depend on the target, so the route is the same whichever file is asked for first).
   If none is found in 2 seconds, it runs from the top of that file in an empty state (`how: "file-start"`)
2. **Within the file**: from the point of entry, it runs several times, varying the choices (up to the number of choices, at most 8), and records the state when each text line and choice line is first passed.
   For other lines (effect commands, `@set`, `@if`, labels and so on), it records the state right after the line first finishes running (`Sweep.after`).
   It learns that a line has finished running just before the next command runs (`RuntimeOptions.onStep`), when the call depth is the same as or shallower than that line's.
   So `@call` and `@define` call lines get the state at the point of returning from what they called.
   When the run leaves that file (except on the way back from `@call`), that run is cut off
3. The state of a text or choice line (`Sweep.lines`) is a save that resumes just before showing that line (the screen state is `save.stage`, and game variables are `save.game`), temp,
   the line that set each variable's value (collected with `RuntimeOptions.onAssign`), and the choices made in that file.
   The state of a command line (`Sweep.after`) has no save; it has the screen state (a number into `Sweep.stages`; there are many command lines, so identical states are merged into one),
   game variables, temp, the lines that set them, and the choices made

Line states aren't stored redundantly. Large projects have hundreds of variables, and keeping all of them on every line would make tens of MB per file:

- Game variables and the lines that set their values are stored only where they changed since the point of entering the file (`Sweep.base`) (removed variables are `unset`).
  The save passed to the player is restored to the full form with `lineSave(sweep, state)`, the game variables of command lines with `afterGame(sweep, state)`,
  and the lines that set them with `lineAssigned(sweep, state)`
- The choices made within the file point to the first few entries of each run's list (`Sweep.runs`) (`lineChoices(sweep, state)`)

4. **Unreached lines**: the route in 1 is the route that first enters the file, so some lines aren't passed on that route, such as the branch of an `@if` that depends on variables set in other files
   (the hatched effect bars). Put the cursor on such a line, and it looks for a route that passes that line and redoes step 2
   (`GET /sweep/reach`, `Sweeper.entryReaching`), and shows "Route (to line N)" below the preview. While searching, and when the line isn't reached or isn't found
   in time, the line display below the preview says so (still showing the screen of the nearest earlier line that has a state). How it searches:
   - At choices, it tries first the ones that move to scenes closer to the target scene on the flowchart (the jump targets of choices are the `targets` the runner passes to the rendering side)
   - It takes as candidates the `@set` lines that set the variables in the conditions for entering that line (the `@if` around the line, and the conditions of the arrows into that line's scene) to values that meet the conditions,
     and for each candidate searches in the order "pass that line first, then go to the target line"
   - A run that enters a file once and leaves it without passing that line is cut off there and moves to the next set of choices (it doesn't run to the end of the game)
   - Up to 15 seconds. A route found is used for that file's current position data until the file changes or it searches again for another unreached line
   - The dev server doesn't stop while searching. Each time the runner sends to the rendering side and before it picks a choice (`pause` of walk in `@liminalia/runtime`),
     it lets go once every 30ms, so saves (`PUT /file`) and other requests don't have to wait (the phone app's Service Worker uses the same mechanism with its own way of letting go).
     If another line is requested, any `.lim` changes, or the request is closed, it stops searching and returns `cancelled` (not remembered; the client asks again if it is still on that line)

Routes and line states are remembered until any `.lim` changes. From the second time, they return right away.
The client fetches line states for the preview and "State at this line" only around the visible range (`from`, `to`), and the duration bars fetch the whole file with `GET /sweep/stage`.
`packages/studio/dev/measure.ts <project> [file…]` measures the size per file (before and after gzip) and the time to build it.

The performance of Studio itself is measured with `packages/studio/dev/measure-studio.ts [--out result.json] [--project <project> --file <file> [--edit <line>] [--reach-file <file> --unreachable <line>]] [shape…]`.
The shapes are projects made from the templates in `dev/shapes.ts`: `long` (one 8,000-line file), `many` (300 files in 10 folders, 3,000 variables, 1,500 syntax check warnings, 2,000 backgrounds),
and `branchy` (a line no route reaches, after 14 levels of choices). For each shape, it starts `lim studio` and reports the time to build the current position data, the wait for a save (`PUT /file`) while an unreached line is being searched for,
the time to switch to the block view (blocksOpen), the time to add one character to the text in the block view and the code view, redrawing the scene list (with every file expanded), the time until the Variables, Check and Assets screens appear, and the total of long tasks during that time.
To measure your own project, copy it first and pass the copy to `--project` (the project folder is only read; `node_modules/@liminalia` in the copy is pointed to this repository's `packages`).

## Preview (the player's interface for Studio)

Studio opens the real player in an iframe with `/?studio=1` and passes it line states with `postMessage` (only when served by the dev server).

- The player shows neither "クリックで開始" (Click to start) nor the title, and returns `{ type: "liminalia:stage-ready" }` when it opens
- On receiving `{ type: "liminalia:stage-show", save }`, it starts from that save, shows the page (or choices),
  and returns `{ type: "liminalia:stage-shown", at }` (at is the position of that page or choice; null if it ended before getting there).
  Even with system screens where `loadSave` resolves before the page appears, it waits until the page appears or it stops at choices before returning
  (up to 3 seconds; after that, the runner's current position). The client doesn't use the returned position for display
- While the preview doesn't have the focus, elements' `focus()` is suppressed. Even if choice buttons, input fields, system screens or plugin screens
  try to move the focus, what you type in Studio doesn't go into the preview. When the writer clicks the preview, the focus moves as usual
- On receiving `{ type: "liminalia:stage-still", stage }`, it stops the current play (the runner) without advancing, builds the screen for that state (`stage`) only by the rendering side's rebuilding
  (the same `restore` as loading, and plugins' `restorers`), empties the text and name box of the message window,
  and returns `{ type: "liminalia:stage-still-shown" }`. It doesn't touch system screens, so it works the same in projects that replaced them.
  Clicking the preview doesn't move it forward
- Requests to the preview (`stage-show`, `stage-still`) are handled in order, and the next doesn't start while the previous one is still rebuilding. If newer ones arrive while waiting, the older ones are skipped
- On receiving `{ type: "liminalia:stage-cast", cast }`, it replaces the characters and redraws the sprites on screen
- After showing the page requested by `stage-show` and returning `stage-shown`, each time the preview moves forward by itself and starts showing the next page (or choices),
  it returns `{ type: "liminalia:stage-progress", at: { file, line }, played }` (when the writer clicked the preview, auto, skip, or a choice).
  It isn't returned for the requested page itself or for `stage-still` screens, and when the next request arrives, it stops until that request's `stage-shown`. The client's cursor sync uses it.
  `played` (`StagePlayed`; `null` if there is no runner) is the state reached in the preview at that page:
  - `save`: a save that resumes from that page (choices) (`runtime.save()`, the same point as the save in `Sweep.lines` of the current position data). `temp`: temp at that time
  - `assigned`: variable paths that were given values after the requested page (the last `stage-show`) → their lines (collected with `SystemEnv.onAssign`; later assignments come later)
  - `choices`: the choices made after the requested page (`RouteStep`, in the order made)

  Where values came from and the choices cover only what happened after the requested page, so the client uses them on top of that page's current position data (where variables came from, and the route up to that page)
- `{ type: "liminalia:stage-pause" }` and `{ type: "liminalia:stage-resume" }` freeze the preview and let it continue.
  `{ type: "liminalia:stage-mute", muted }` silences sound and brings it back. All of these act right away without waiting their turn among requests,
  and return `{ type: "liminalia:stage-controlled", paused, muted }`. While paused, the client doesn't send `stage-show` or `stage-still`,
  and when the player reopens (`stage-ready`), it sends mute and pause again. How it pauses (`packages/web/src/studio-stage.ts`):
  - Sound: suspends the AudioContext of the rendering side's `AudioPlayer`. `<audio>` and `<video>` get `pause()` (including those that start playing after pausing)
  - Effects: `pause()` on `document.getAnimations()`. Web Animations, CSS animations and transitions that start after pausing are paused too
  - Text display, auto, `@wait`, and timers in system screens and plugins: with `?studio=1`, the player wraps the window's
    `setTimeout` and `requestAnimationFrame` in something that can be paused (`TimerGate`) before anything else. Calls whose time comes while paused are held,
    and called in the order they came on resuming (`setInterval` skips the runs while paused). The player's own waiting for requests is counted with the unwrapped timers
  - Input: while paused, the preview doesn't take clicks, keys or the wheel (Studio's keys ⌘⇧… and Esc pass through)
  - Mute is `AudioPlayer.setMuted` (sets the output volume, separate from the config volume, to 0) and `muted` on `<audio>` and `<video>`
    (only those it muted are unmuted)

  It doesn't touch system screens, so it works the same in projects where plugins replaced them. What it can't stop is
  anything that moves without timers (Web Workers, `MessageChannel`, synchronous code that keeps polling `performance.now()` and so on),
  sound from plugins that create their own `AudioContext`, and `new Audio()` played without being added to the document (mute is the same)

- On receiving `{ type: "liminalia:stage-set-var", path, value }`, it puts the value into a variable (`game.…`, `temp.…`, `system.…`) of the runner running in the preview,
  and returns `{ type: "liminalia:stage-var-set", path, value, at, played, error? }` (`at` is the line the preview is showing now, and `played` is the state at that point; the changed value is added to `played.save.game`; `error` if there is no runner or the path is wrong).
  It runs at the back of the request queue, and takes effect even while paused. It isn't saved to files or initial values, and `onAssign` isn't called (it isn't reported as a line that set the value). When `stage-show` or `stage-still` rebuilds, the runner is discarded, so `game.` and `temp.` go back,
  and `system.`, which survives across runners, is put back to its value before the change (`packages/web/src/studio-vars.ts`). It is received only inside `connectStudio`, so it works only with the dev server's `?studio=1`, and isn't included in exported games.
  `system` in `stage-shown` and `StagePlayed.system` return the `system.` variables the runner holds

Starting from a save is done by the system screens' `loadSave(save)` ([plugins.md](plugins.md)). Projects that replace the system screens can use the preview by implementing it.

## Screenshots and performance measurement

Both open the dev server's player in a headless browser at the game's size (`screen`) and a zoom of 1 (`BrowserProvider` in `server/browser.ts`).

- **Screenshots** (`server/shot.ts`): opens the player with `/?studio=1` (opened the same way as the preview; the position display at the top right, the variable watch and the performance display don't appear),
  and requests the same characters passed to the preview (`stage-cast`) and the same thing requested from the preview (the save of `stage-show` or the state of `stage-still`).
  It waits for `stage-shown` (for text and choice pages, also until the text has finished displaying and it reaches a click wait or choices) or `stage-still-shown`; if the project holds the capture
  (`host.holdShot`), waits until it lets go; waits for fonts and images to load; and finishes moving effects before capturing (the same as `lim shot --settle`)
- **Performance measurement** (`server/profile.ts`; `lim profile` uses it too): opens the player with `?start=…&autostart=1`, and reads the numbers in `window.__liminaliaPerf`
  for each page (after waiting 0.5 seconds; at choices, the first one)
- **Browser**: `lim studio` (Studio opened in a browser) uses Playwright (`playwright-core`) with `LIMINALIA_CHROMIUM` or Playwright's chrome-headless-shell (`findChromium`).
  If none is found, the API refuses with `CHROMIUM_MISSING_STATUS` (424), and the client shows how to install it ("Run `npx playwright install chromium-headless-shell` in a terminal, then try again").
  The desktop app opens it in a hidden Electron window of the app (drawn off screen, with no sound) (the engine side asks with `page`,
  and `packages/studio-desktop/src/main/pages.ts` opens it and answers with `page-reply`; it can open only pages of that project's dev server).
  Packaged apps include neither `playwright-core` nor Chromium, so this works without Chromium. `playwright-core` is loaded when used

## Handing off production work

- **Recording script** (Project → Export → Recording script, or `lim voice-script`): exports, for each line of dialogue, the voice file (from `@voice` before the line, or
  the locked numbers and the `@voice-auto` pattern), the speaker, the line (ruby as `漢字《かんじ》`, base characters followed by the reading), acting notes (the `//!` line directly above the dialogue; plain `//` comments aren't included, and setting `voiceScript.notes` in liminalia.json to `"comments"` includes every `//` line as before), the previous line,
  the scene, the location, why it doesn't play (neither `@voice` nor `@voice-auto` applies, or the locked numbers have no number for it), whether the voice file exists, and whether it needs re-recording (it took over a number from the dialogue before it was rewritten),
  into `exports/voice-script/` as all.csv (everything), a CSV per speaker, and summary.csv (a summary of the number of lines, characters, and lines without a voice), with English headings (in the Japanese display, 全体.csv and 集計.csv with Japanese headings).
  A second `@voice` played at the same time on the same line of dialogue (`who=`, `channel=`) is a row too (its speaker is that voice's speaker), and if the dialogue belongs to another speaker, the acting notes start with "Together with Yui".
  Dialogue in packs (`packs/<id>/scenario`) comes after the main rows (the location is `packs/<id>/scenario/<file>:<line>`; whether it plays and its number are decided with the pack laid over the main scripts)
- **Script for proofreading** (Project → Export → Script for proofreading, or `lim script-export`): writes, for each file, only the text (dialogue, narration and choice text) and the scene headings,
  with speaker names, as text (ruby as `｜base《reading》`, with line numbers) or HTML (`<ruby>`, with `index.html` linking to each file) to `exports/script/`.
  To bring edited text back, use `lim prose extract` and `lim prose apply` ("Proofreading" in [format.md](design/format.md))
- **Translation hand-off** (Project → Translation → Import and export, or `lim i18n <language> --export csv|xliff --out …` / `--import …` / `--count`):
  exports translation files as a table (CSV) or XLIFF 1.2 into `exports/translation/`, and imports files with translations written in (looked up by key; lines whose original differs from the current script
  aren't saved). `--count` gives character counts for estimates (the whole original, and what isn't translated yet).
  The context column of the table and the notes of XLIFF hold the scene, the location, the lines before and after, and a length guide, and in XLIFF the markup in the text (`{r …}`, `{br}` and so on) becomes `<ph>`, `<x/>` and `<g>`.
  On import, the markup in the text is checked, and translations that can't be read aren't saved, with the count reported (`lim i18n` also shows where and why).
  Languages other than Japanese and English also list the text of the system screens, with the English original alongside. For `--untranslated`, `--changed` and the line ID option `--stamp-ids`, see chapter 10 of [design/format.md](design/format.md)
- **Visual check of every branch** (`lim regress [--update] [--threshold 0.05] [--pages 1] [--only text] [--dir folder]`): for each
  scene in the flowchart, starts from the top of that scene and captures `--pages` pages from the top (effects are toned down and motion is stopped, so the same script gives the same screen),
  and compares them with the baseline (`.liminalia/regress/baseline`). It reports those whose differing pixels exceed `--threshold` %, and puts images with the differences painted red in
  `.liminalia/regress/diff`. Ones without a baseline become the baseline, and `--update` makes the current ones the baseline. If anything changed, the exit code is 1.
  In Studio, "Visual check" on the Check screen does the same (`POST /regress`; `server/regress.ts`) (the first page of each scene, a difference ratio of 0.05%).
  "Check" compares, and "Use current look as baseline" makes the baseline without comparing. While capturing, it shows "n / m scenes" and "Cancel"; when done, it lists the scenes that changed
  with images of the differences painted red (`GET /regress/file?kind=diff&name=`) and the ratio; click one to go to that scene in the script. Pages are opened the same way as performance measurement
  (`browser.ts`), so the desktop app works without Chromium. It doesn't run at the same time as a measurement (409)
- **Locking voice numbers** (`lim voice-lock`): in Studio, "Lock numbers" on the Voices screen (`POST /voice-lock`; `server/voice-lock.ts`;
  shown only when some speaker uses `@voice-auto` with a pattern). Current locks don't change, and numbers are added for new lines; if there are no locks, it runs "New game" without a screen
  in 8 ways and records the numbers that play (`observeVoiceNumbers` in `@liminalia/runtime`; lim voice-lock uses the same). The previous content is kept in the change history (`.liminalia/history/@voice-lock/`).
  Lines whose numbers differ by route are listed at the top of the screen; click one to go to that line
