castle-web-cli 0.4.194 → 0.4.196

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (42) hide show
  1. package/dist/agent-prompts.d.ts +1 -0
  2. package/dist/agent-prompts.js +14 -5
  3. package/dist/agent.js +60 -1
  4. package/dist/castleJson.d.ts +0 -2
  5. package/dist/castleJson.js +0 -39
  6. package/dist/devSessionFrameBudget.d.ts +14 -0
  7. package/dist/devSessionFrameBudget.js +64 -0
  8. package/dist/devSessionServer.js +15 -0
  9. package/dist/editorConfig.d.ts +1 -1
  10. package/dist/editorConfig.js +12 -4
  11. package/dist/ide.js +28 -59
  12. package/dist/imports.js +2 -4
  13. package/dist/init.js +9 -8
  14. package/dist/multiplayerDoc.d.ts +1 -0
  15. package/dist/multiplayerDoc.js +228 -0
  16. package/dist/platformDoc.d.ts +1 -0
  17. package/dist/platformDoc.js +21 -2
  18. package/dist/scriptErrors.d.ts +23 -0
  19. package/dist/scriptErrors.js +147 -0
  20. package/dist/serve.js +233 -4
  21. package/dist/shell/assets/index-kMH1qj6D.js +449 -0
  22. package/dist/shell/index.html +1 -1
  23. package/dist/viteClientStub.d.ts +18 -0
  24. package/dist/viteClientStub.js +193 -0
  25. package/kits/base/CLAUDE.md +3 -3
  26. package/kits/base/castle.json +1 -3
  27. package/kits/base/sdk/README.md +17 -0
  28. package/kits/multiplayer-2d/castle.json +0 -9
  29. package/kits/multiplayer-3d/castle.json +0 -8
  30. package/kits/physics-2d/CLAUDE.md +5 -6
  31. package/kits/physics-2d/castle.json +1 -11
  32. package/kits/physics-2d/editors/SceneEditor.jsx +42 -3
  33. package/kits/physics-2d/editors/behaviorRegistry.js +8 -2
  34. package/kits/physics-2d/engine/ErrorOverlay.jsx +69 -0
  35. package/kits/physics-2d/engine/ScenePlayer.jsx +2 -67
  36. package/kits/physics-2d/engine/liveReload.js +5 -4
  37. package/kits/physics-3d/castle.json +0 -11
  38. package/kits/real-time/castle.json +0 -6
  39. package/kits/turn-based/CLAUDE.md +6 -3
  40. package/kits/turn-based/castle.json +1 -14
  41. package/package.json +1 -1
  42. package/dist/shell/assets/index-ColHKJYj.js +0 -449
@@ -10,7 +10,7 @@
10
10
  <link rel="icon" type="image/png" sizes="32x32" href="/__castle/ide/favicon-32x32.png" />
11
11
  <link rel="icon" type="image/png" sizes="16x16" href="/__castle/ide/favicon-16x16.png" />
12
12
  <link rel="icon" href="/__castle/ide/favicon.ico" sizes="any" />
13
- <script type="module" crossorigin src="/__castle/ide/assets/index-ColHKJYj.js"></script>
13
+ <script type="module" crossorigin src="/__castle/ide/assets/index-kMH1qj6D.js"></script>
14
14
  <link rel="stylesheet" crossorigin href="/__castle/ide/assets/index-D6leLNUq.css">
15
15
  </head>
16
16
  <body>
@@ -0,0 +1,18 @@
1
+ import type { Plugin } from 'vite';
2
+ /** The five names the real client entry exports (last line of client.mjs). */
3
+ export declare const VITE_CLIENT_EXPORTS: readonly ["ErrorOverlay", "createHotContext", "injectQuery", "removeStyle", "updateStyle"];
4
+ /**
5
+ * Vite resolves `/@vite/client` to `normalizePath(CLIENT_ENTRY)`, i.e. the
6
+ * client entry's absolute path with forward slashes (see the `vite:client-inject`
7
+ * plugin in vite/dist/node/chunks/node.js). Resolve and normalize it the same
8
+ * way so the id comparison holds on Windows too.
9
+ */
10
+ export declare function viteClientEntryId(): string;
11
+ /**
12
+ * Replaces the body of Vite's HMR client entry with a socket-free stub.
13
+ *
14
+ * `enforce: 'pre'` puts the `load` hook ahead of Vite's own file load for that
15
+ * id, so the stub source is what gets transformed and served for
16
+ * `/@vite/client`. Every other id falls through untouched.
17
+ */
18
+ export declare function viteClientStubPlugin(): Plugin;
@@ -0,0 +1,193 @@
1
+ import * as path from 'path';
2
+ import { createRequire } from 'module';
3
+ // Castle's dev serve runs Vite with `server.hmr: false` on purpose: reload
4
+ // decisions belong to the consumers of the `files_changed` broadcast (the kit
5
+ // engine, editors, the shell), never to Vite -- see the header comment in
6
+ // filesChanged.ts. Vite still injects `<script type="module"
7
+ // src="/@vite/client">` into every HTML page, and its CSS and
8
+ // import-analysis transforms still emit imports of `updateStyle`,
9
+ // `removeStyle`, `injectQuery` and `createHotContext` from `/@vite/client`, so
10
+ // the module cannot simply be removed. But the real client
11
+ // (node_modules/vite/dist/client/client.mjs) opens a `vite-hmr` WebSocket the
12
+ // moment it loads, and with HMR off nothing ever accepts it: every deck open
13
+ // printed `[vite] failed to connect to websocket` plus a direct-connection
14
+ // fallback warning, which reads as a bug and trains people to ignore the
15
+ // console. This plugin swaps the client entry's module body for a stub that
16
+ // never opens a socket while keeping the exact same public exports, so every
17
+ // transformed module keeps working unchanged.
18
+ /** The five names the real client entry exports (last line of client.mjs). */
19
+ export const VITE_CLIENT_EXPORTS = [
20
+ 'ErrorOverlay',
21
+ 'createHotContext',
22
+ 'injectQuery',
23
+ 'removeStyle',
24
+ 'updateStyle',
25
+ ];
26
+ /**
27
+ * Vite resolves `/@vite/client` to `normalizePath(CLIENT_ENTRY)`, i.e. the
28
+ * client entry's absolute path with forward slashes (see the `vite:client-inject`
29
+ * plugin in vite/dist/node/chunks/node.js). Resolve and normalize it the same
30
+ * way so the id comparison holds on Windows too.
31
+ */
32
+ export function viteClientEntryId() {
33
+ const pkgJson = createRequire(import.meta.url).resolve('vite/package.json');
34
+ return path.resolve(path.dirname(pkgJson), 'dist/client/client.mjs').split(path.sep).join('/');
35
+ }
36
+ // The stub's own module body. `updateStyle` / `removeStyle` are copied from the
37
+ // real client.mjs so dev-mode CSS imports behave exactly as before;
38
+ // `injectQuery` is Vite's own `__vite__injectQuery`; `createHotContext` returns
39
+ // an inert context with the same surface as client.mjs's HMRContext (the CSS
40
+ // transform calls `.accept()` and `.prune()` on it); `ErrorOverlay` is a real
41
+ // custom element because Vite's inline-CSS html-proxy error path does
42
+ // `new ErrorOverlay(err)` after dynamically importing `/@vite/client`.
43
+ const STUB_SOURCE = `// Castle stub for Vite's HMR client. HMR is off by design in the Castle dev
44
+ // serve (server.hmr: false; see cli/src/filesChanged.ts) -- reload decisions
45
+ // belong to the consumers of files_changed, not to Vite. The real client opens
46
+ // a vite-hmr socket on load and logs a connection failure forever when nothing
47
+ // accepts it, so this replaces its body with the same five exports and no
48
+ // socket, no ping and no reload.
49
+
50
+ const cspNonce =
51
+ 'document' in globalThis
52
+ ? document.querySelector('meta[property=csp-nonce]')?.nonce
53
+ : undefined;
54
+
55
+ const sheetsMap = /* @__PURE__ */ new Map();
56
+ const linkSheetsMap = /* @__PURE__ */ new Map();
57
+ if ('document' in globalThis) {
58
+ document.querySelectorAll('style[data-vite-dev-id]').forEach((el) => {
59
+ sheetsMap.set(el.getAttribute('data-vite-dev-id'), el);
60
+ });
61
+ document.querySelectorAll('link[rel="stylesheet"][data-vite-dev-id]').forEach((el) => {
62
+ linkSheetsMap.set(el.getAttribute('data-vite-dev-id'), el);
63
+ });
64
+ }
65
+
66
+ let lastInsertedStyle;
67
+
68
+ export function updateStyle(id, content) {
69
+ if (linkSheetsMap.has(id)) return;
70
+ let style = sheetsMap.get(id);
71
+ if (!style) {
72
+ style = document.createElement('style');
73
+ style.setAttribute('type', 'text/css');
74
+ style.setAttribute('data-vite-dev-id', id);
75
+ style.textContent = content;
76
+ if (cspNonce) style.setAttribute('nonce', cspNonce);
77
+ if (!lastInsertedStyle) {
78
+ document.head.appendChild(style);
79
+ setTimeout(() => {
80
+ lastInsertedStyle = undefined;
81
+ }, 0);
82
+ } else {
83
+ lastInsertedStyle.insertAdjacentElement('afterend', style);
84
+ }
85
+ lastInsertedStyle = style;
86
+ } else {
87
+ style.textContent = content;
88
+ }
89
+ sheetsMap.set(id, style);
90
+ }
91
+
92
+ export function removeStyle(id) {
93
+ if (linkSheetsMap.has(id)) {
94
+ document.querySelectorAll('link[rel="stylesheet"][data-vite-dev-id]').forEach((el) => {
95
+ if (el.getAttribute('data-vite-dev-id') === id) el.remove();
96
+ });
97
+ linkSheetsMap.delete(id);
98
+ }
99
+ const style = sheetsMap.get(id);
100
+ if (style) {
101
+ document.head.removeChild(style);
102
+ sheetsMap.delete(id);
103
+ }
104
+ }
105
+
106
+ // Vite's own __vite__injectQuery, used by import-analysis for dynamic imports
107
+ // it could not statically analyze.
108
+ export function injectQuery(url, queryToInject) {
109
+ if (url[0] !== '.' && url[0] !== '/') return url;
110
+ const pathname = url.replace(/[?#].*$/, '');
111
+ const { search, hash } = new URL(url, 'http://vite.dev');
112
+ return \`\${pathname}?\${queryToInject}\${search ? '&' + search.slice(1) : ''}\${hash || ''}\`;
113
+ }
114
+
115
+ // Same surface as client.mjs's HMRContext, all inert: nothing dispatches HMR
116
+ // updates, so a registered callback would never fire anyway.
117
+ export function createHotContext(ownerPath) {
118
+ const noop = () => {};
119
+ return {
120
+ data: {},
121
+ accept: noop,
122
+ acceptExports: noop,
123
+ dispose: noop,
124
+ prune: noop,
125
+ decline: noop,
126
+ invalidate: noop,
127
+ on: noop,
128
+ off: noop,
129
+ send: noop,
130
+ };
131
+ }
132
+
133
+ // Vite's error middleware serves a page that does
134
+ // \`document.body.appendChild(new ErrorOverlay(err))\` and nothing else, so the
135
+ // element has to render the error itself or that 500 page is blank. Styled
136
+ // inline in the same palette as the serve's FRAME_ERROR_CAPTURE redbox, and
137
+ // filled through textContent only -- err.message is untrusted text.
138
+ export class ErrorOverlay extends HTMLElement {
139
+ constructor(err) {
140
+ super();
141
+ this.err = err;
142
+ console.error('[castle] ' + ((err && err.message) || err));
143
+ this.style.cssText =
144
+ 'position:fixed;left:0;top:0;right:0;bottom:0;z-index:2147483000;box-sizing:border-box;padding:18px 20px;overflow:auto;background:rgba(20,8,8,0.96);color:#ffd9dc;font:13px/1.5 SFMono-Regular,Consolas,Liberation Mono,monospace';
145
+ const title = document.createElement('div');
146
+ title.style.cssText = 'font-size:15px;font-weight:700;color:#ff6b74;margin-bottom:10px';
147
+ title.textContent = 'Script error';
148
+ this.appendChild(title);
149
+ const message = document.createElement('div');
150
+ message.style.cssText = 'word-break:break-word;white-space:pre-wrap';
151
+ message.textContent = (err && err.message) || String(err);
152
+ this.appendChild(message);
153
+ const detail = (err && (err.frame || err.stack)) || '';
154
+ if (detail) {
155
+ const pre = document.createElement('pre');
156
+ pre.style.cssText =
157
+ 'margin:6px 0 0;color:#e79aa0;font-size:12px;white-space:pre-wrap;word-break:break-word';
158
+ pre.textContent = detail;
159
+ this.appendChild(pre);
160
+ }
161
+ const hint = document.createElement('div');
162
+ hint.style.cssText = 'margin-top:12px;color:#c98a8f;font-size:12px';
163
+ hint.textContent = 'Fix the file and reload.';
164
+ this.appendChild(hint);
165
+ }
166
+ close() {
167
+ this.remove();
168
+ }
169
+ }
170
+
171
+ if (typeof customElements !== 'undefined' && !customElements.get('castle-vite-error-overlay')) {
172
+ customElements.define('castle-vite-error-overlay', ErrorOverlay);
173
+ }
174
+ `;
175
+ /**
176
+ * Replaces the body of Vite's HMR client entry with a socket-free stub.
177
+ *
178
+ * `enforce: 'pre'` puts the `load` hook ahead of Vite's own file load for that
179
+ * id, so the stub source is what gets transformed and served for
180
+ * `/@vite/client`. Every other id falls through untouched.
181
+ */
182
+ export function viteClientStubPlugin() {
183
+ const clientEntry = viteClientEntryId();
184
+ return {
185
+ name: 'castle:vite-client-stub',
186
+ enforce: 'pre',
187
+ load(id) {
188
+ if (id === clientEntry)
189
+ return STUB_SOURCE;
190
+ return null;
191
+ },
192
+ };
193
+ }
@@ -65,9 +65,9 @@ imports/ other decks this one imports, read-only. `castle.base` (this
65
65
 
66
66
  - `initialPanels` — what the workspace opens with (`files`, `playtest`,
67
67
  `editor`).
68
- - `visiblePaths` / `hiddenPaths` — the Files panel filter. `[]` shows every
69
- file; a deck that lists paths has to add new content directories to it or
70
- they never appear.
68
+ - `hiddenPaths` — globs the Files panel leaves out. Nothing is hidden unless the
69
+ deck names it, and the panel's show-hidden control appears only when something
70
+ is hidden.
71
71
  - `fileTypes` — the deck's own file types; see `## Editors`.
72
72
  - `defaultPlayFile` — what the play panel opens with. A deck that declares none
73
73
  just loads `index.html`.
@@ -1,7 +1,5 @@
1
1
  {
2
2
  "editor": {
3
- "hiddenPaths": [],
4
- "visiblePaths": [],
5
3
  "fileTypes": [
6
4
  {
7
5
  "ext": ".md",
@@ -84,7 +82,7 @@
84
82
  "title": "base",
85
83
  "deckId": "yRcmH4_aYllE",
86
84
  "cardId": "zkFdingmIm3m",
87
- "publishedVersion": "2026-09-11T20:21:04.335Z",
85
+ "publishedVersion": "2026-09-17T20:55:24.712Z",
88
86
  "provides": [
89
87
  "castle-web-sdk"
90
88
  ]
@@ -59,6 +59,23 @@ nothing. `soloReason` says why: `private_deck` or `no_server_bundle` are the
59
59
  creator's to fix (change the deck's visibility, or publish a deck that has a
60
60
  server entry); anything else reports `unavailable`. Client→server frames are limited to 16 KB on the wire.
61
61
 
62
+ ### Limits
63
+
64
+ A client may send about 30 messages per second; going past that closes the
65
+ socket, so throttle pose or input sends rather than sending one per animation
66
+ frame.
67
+
68
+ A session may send about `40 + 40 × connected players` frames per second, with
69
+ roughly two seconds of burst and about 1 MiB/s of bytes. `session.send` costs
70
+ one frame per call, `session.broadcast(data)` costs one frame however many
71
+ players are connected, and `session.broadcast(data, { except })` is a loop of
72
+ sends, so it costs one frame per recipient. Frames over the budget are dropped
73
+ silently and never retried — the session keeps running — so broadcast one
74
+ snapshot per tick instead of sending a tailored message per player. Each client
75
+ reads every entry in that snapshot, its own included: the server's copy of its
76
+ hp, score and match state is authoritative, and only its own position stays
77
+ locally predicted.
78
+
62
79
  ### Binary messages
63
80
 
64
81
  Pass any typed array, `DataView`, or `ArrayBuffer` to client `send`, server `send`,
@@ -1,15 +1,6 @@
1
1
  {
2
2
  "title": "multiplayer-2d",
3
3
  "editor": {
4
- "hiddenPaths": [],
5
- "visiblePaths": [
6
- "code/**",
7
- "behaviors/**",
8
- "scenes/**",
9
- "blueprints/**",
10
- "theme.style",
11
- "fonts.generated.js"
12
- ],
13
4
  "defaultPlayFile": "scenes/main.scene"
14
5
  },
15
6
  "imports": {
@@ -1,14 +1,6 @@
1
1
  {
2
2
  "title": "multiplayer-3d",
3
3
  "editor": {
4
- "hiddenPaths": [],
5
- "visiblePaths": [
6
- "code/**",
7
- "theme.style",
8
- "fonts.generated.js",
9
- "scenes/**",
10
- "blueprints/**"
11
- ],
12
4
  "defaultPlayFile": "scenes/main.scene"
13
5
  },
14
6
  "imports": {
@@ -41,7 +41,7 @@ Reach for one when the deck accumulates content someone will keep iterating
41
41
  on by hand — level layouts, dialogue, item or word catalogs, tuning values —
42
42
  where editing raw JSON in the code editor is the bottleneck.
43
43
 
44
- ### The three steps
44
+ ### The two steps
45
45
 
46
46
  1. **Declare the type** in the deck's own `castle.json` under
47
47
  `editor.fileTypes`:
@@ -136,11 +136,8 @@ That hook is the single definition of the rule. Do not re-derive it from
136
136
  `isImportedFile` or `window.__castleReadOnly` — a fork IS writable, and getting
137
137
  that wrong locks an editor the deck is entitled to use.
138
138
 
139
- 3. **Make it visible.** If the deck's `castle.json` has
140
- `editor.visiblePaths`, add your content directory (e.g. `"dialogue/**"`)
141
- or the files won't appear in the Files panel. A brand-new editor module
142
- is not in the loader's glob until the panel reloads — the person's next
143
- reload picks it up; do not force one.
139
+ A brand-new editor module is not in the loader's glob until the panel reloads —
140
+ the person's next reload picks it up; do not force one.
144
141
 
145
142
  That's the whole integration: no entry-point changes, no registration call.
146
143
  The kit's editor host dispatches any declared module, including ones the kit
@@ -909,6 +906,8 @@ For HUD text prefer a `Text` actor with `space: 'screen'` (or `drawUi` for custo
909
906
 
910
907
  - Don't name a behavior prop with a leading `$` — the engine reserves that prefix (see `$enabled`).
911
908
 
909
+ - Don't revert, replace, or re-scaffold a deck's `scenes/*.scene`, `blueprints/*.scene` or `behaviors/*.jsx` back to this kit's starter content, and don't rewrite or delete a whole scene to diagnose a problem — those files are the creator's game. Fix forward with targeted edits.
910
+ - Don't answer "how do I …" by inserting a demo behavior or actor into the scene. Explain it, or give a standalone snippet; only build it into the game when that's what was asked, and then say which file and which actor or blueprint it landed on.
912
911
  - Don't `console.log` in tight loops — flood the serve log.
913
912
  - Don't keep per-actor state on the behavior class instance; it's recreated each frame. Use `actor.runtime` or component props.
914
913
  - Don't skip `constructor(props) { this.props = props; }`. `this.props` exists because the constructor assigns it; `defaultProps` alone does not put it there.
@@ -17,16 +17,6 @@
17
17
  "file": "scenes/main.scene"
18
18
  }
19
19
  ],
20
- "hiddenPaths": [],
21
- "visiblePaths": [
22
- "drawings/**",
23
- "scenes/**",
24
- "blueprints/**",
25
- "behaviors/**",
26
- "assets/**",
27
- "theme.style",
28
- "fonts.generated.js"
29
- ],
30
20
  "fileTypes": [
31
21
  {
32
22
  "ext": ".scene",
@@ -77,7 +67,7 @@
77
67
  "autoUpdateWhenImported": true,
78
68
  "onUpdate": "scripts/onUpdate.mjs",
79
69
  "title": "physics-2d",
80
- "publishedVersion": "2026-09-16T21:17:53.144Z",
70
+ "publishedVersion": "2026-09-17T20:55:45.193Z",
81
71
  "imports": {
82
72
  "castle.base": {
83
73
  "deckId": "yRcmH4_aYllE",
@@ -28,6 +28,7 @@ import {
28
28
  setActorComponent,
29
29
  } from '../engine/scene';
30
30
  import { fontsReady, ensureOfficialFace } from '../engine/fonts';
31
+ import { ErrorOverlay } from '../engine/ErrorOverlay';
31
32
  import {
32
33
  addActorWithBlueprint,
33
34
  blueprintDropXY,
@@ -309,7 +310,7 @@ export function SceneEditor({
309
310
  const recordSceneSnapshot = readOnly ? () => {} : history.recordSnapshot;
310
311
  const commitScene = readOnly ? () => {} : (next) => history.commit(serialize(next));
311
312
  useMigrateOrphanActors({ isBlueprintFile, sceneData, files, text, onChange, readOnly });
312
- useScenePlayLoop({
313
+ const { loopError, restartLoop } = useScenePlayLoop({
313
314
  sceneData,
314
315
  sprites,
315
316
  files,
@@ -826,6 +827,13 @@ export function SceneEditor({
826
827
  recordSnapshot={recordSceneSnapshot}
827
828
  />
828
829
  )}
830
+ {loopError ? (
831
+ <ErrorOverlay
832
+ error={loopError}
833
+ onRestart={restartLoop}
834
+ title={isPlaying ? 'Play error' : 'Scene error'}
835
+ />
836
+ ) : null}
829
837
  </div>
830
838
  {!isPlaying && (
831
839
  <div style={ZOOM_CONTROLS_STYLE}>
@@ -1715,6 +1723,17 @@ function useScenePlayLoop({
1715
1723
  selectedBlueprintPathRef,
1716
1724
  colliderShapeSelRef,
1717
1725
  }) {
1726
+ // A throw from inside the loop below (a behavior's update/draw, or makeScene
1727
+ // itself on a behavior whose module is broken) kills the loop -- it cannot
1728
+ // schedule the next frame -- and the canvas simply stops updating. Captured
1729
+ // so the editor shows the same redbox the play surface does instead of a
1730
+ // blank scene. `loopRunId` bumps to remount the loop on Restart.
1731
+ const [loopError, setLoopError] = useState(null);
1732
+ const [loopRunId, setLoopRunId] = useState(0);
1733
+ const restartLoop = useCallback(() => {
1734
+ setLoopError(null);
1735
+ setLoopRunId((n) => n + 1);
1736
+ }, []);
1718
1737
  // Spin up / tear down the play-mode runtime as the user toggles play. `text`
1719
1738
  // is the stable identity for `sceneData` (which is re-parsed every render);
1720
1739
  // depending on `sceneData` here would reset the runtime — and any
@@ -1730,8 +1749,10 @@ function useScenePlayLoop({
1730
1749
  // Pressing Stop has to stop what the runtime started -- a sound keeps
1731
1750
  // playing on its own otherwise, with no scene left to stop it.
1732
1751
  return () => runtime.dispose();
1752
+ // `loopRunId` too: Restart has to dispose and rebuild the runtime, not hand
1753
+ // the fresh loop back the one that just threw.
1733
1754
  // eslint-disable-next-line react-hooks/exhaustive-deps
1734
- }, [sprites, isPlaying, text, runtimeRef]);
1755
+ }, [sprites, isPlaying, text, runtimeRef, loopRunId]);
1735
1756
  // Animation loop -- draws edit-mode previews and ticks the play-mode runtime.
1736
1757
  useEffect(() => {
1737
1758
  if (!sceneData || !canvasRef.current) return undefined;
@@ -1759,6 +1780,20 @@ function useScenePlayLoop({
1759
1780
  // Recompute each frame so the edit zoom (mutated on the camera ref by the
1760
1781
  // pinch gesture) takes effect without restarting the loop.
1761
1782
  const frameViewport = isPlaying ? undefined : editViewportForZoom(editCameraRef.current.zoom);
1783
+ try {
1784
+ drawFrame(dt, frameViewport);
1785
+ } catch (error) {
1786
+ // Stop scheduling frames (it would otherwise rethrow 60x/second) and
1787
+ // surface it, the same way the play loop does. Restart remounts a
1788
+ // fresh loop.
1789
+ // eslint-disable-next-line no-console
1790
+ console.error('[castle] scene editor loop error', error);
1791
+ setLoopError(error);
1792
+ return;
1793
+ }
1794
+ raf = requestAnimationFrame(frame);
1795
+ };
1796
+ const drawFrame = (dt, frameViewport) => {
1762
1797
  const scene = isPlaying
1763
1798
  ? runtimeRef.current
1764
1799
  : makeScene(sceneData, behaviorClasses, sprites, files, path);
@@ -1789,8 +1824,10 @@ function useScenePlayLoop({
1789
1824
  colliderShapeSel: isPlaying ? -1 : (colliderShapeSelRef?.current ?? -1),
1790
1825
  });
1791
1826
  }
1792
- raf = requestAnimationFrame(frame);
1793
1827
  };
1828
+ // A loop that is starting is not a loop that is broken -- an edit that
1829
+ // fixes the file resets this effect, and the stale redbox must go with it.
1830
+ setLoopError(null);
1794
1831
  raf = requestAnimationFrame(frame);
1795
1832
  return () => cancelAnimationFrame(raf);
1796
1833
  // eslint-disable-next-line react-hooks/exhaustive-deps -- `text` proxies `sceneData` identity; resetting on every parse churns the loop and wipes runtime state.
@@ -1799,6 +1836,7 @@ function useScenePlayLoop({
1799
1836
  files,
1800
1837
  isPlaying,
1801
1838
  text,
1839
+ loopRunId,
1802
1840
  canvasRef,
1803
1841
  runtimeRef,
1804
1842
  marqueeRef,
@@ -1806,6 +1844,7 @@ function useScenePlayLoop({
1806
1844
  selectedBlueprintPathRef,
1807
1845
  colliderShapeSelRef,
1808
1846
  ]);
1847
+ return { loopError, restartLoop };
1809
1848
  }
1810
1849
  function useScenePlayKeys(runtimeRef) {
1811
1850
  useEffect(() => {
@@ -87,9 +87,15 @@ async function swapBehaviorModule(deckPath) {
87
87
  try {
88
88
  const mod = await import(/* @vite-ignore */ `${key}?t=${Date.now()}`);
89
89
  modules[key] = mod;
90
- } catch {
90
+ } catch (error) {
91
91
  // A file mid-edit may not parse. Keep the last good definition and wait for
92
- // the next save rather than emptying the registry under the editor.
92
+ // the next save rather than emptying the registry under the editor -- but
93
+ // SAY so: swallowing it silently is how a stray `function` inside a
94
+ // behavior becomes a scene that just stops updating with nothing anywhere
95
+ // to read. The console reaches the shell's logs drawer (the SDK's
96
+ // interceptConsole) and the serve log.
97
+ // eslint-disable-next-line no-console
98
+ console.error(`[castle] behavior failed to load: ${deckPath}`, error?.message ?? String(error));
93
99
  return;
94
100
  }
95
101
  behaviorClasses = collectBehaviors();
@@ -0,0 +1,69 @@
1
+ // Redbox overlay shown when a scene loop throws. Covers the canvas with the
2
+ // error name/message and stack so a broken behavior is legible instead of a
3
+ // black screen. Restart remounts the loop; fixing the code and restarting the
4
+ // serve reloads the whole preview fresh.
5
+ //
6
+ // Shared by the play surface (engine/ScenePlayer) and the scene editor's own
7
+ // edit-mode loop (editors/SceneEditor) -- a ReferenceError thrown while drawing
8
+ // a preview blanks the editor canvas exactly the same way, and used to do it
9
+ // without a word.
10
+ export function ErrorOverlay({ error, onRestart, title = 'Play error' }) {
11
+ const name = error?.name ?? 'Error';
12
+ const message = error?.message ?? String(error);
13
+ const stack = typeof error?.stack === 'string' ? error.stack : '';
14
+ return (
15
+ <div
16
+ style={{
17
+ position: 'absolute',
18
+ inset: 0,
19
+ zIndex: 2147483000,
20
+ display: 'flex',
21
+ flexDirection: 'column',
22
+ gap: 12,
23
+ padding: '20px 22px',
24
+ background: 'rgba(20, 8, 8, 0.94)',
25
+ color: '#ffd9dc',
26
+ font: "13px/1.5 'SFMono-Regular', Consolas, 'Liberation Mono', monospace",
27
+ overflow: 'auto',
28
+ boxSizing: 'border-box',
29
+ }}>
30
+ <div style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
31
+ <span style={{ fontSize: 15, fontWeight: 700, color: '#ff6b74' }}>{title}</span>
32
+ <button
33
+ type="button"
34
+ onClick={onRestart}
35
+ style={{
36
+ marginLeft: 'auto',
37
+ padding: '4px 12px',
38
+ border: '1px solid #a02828',
39
+ borderRadius: 4,
40
+ background: '#a02828',
41
+ color: '#fff',
42
+ font: 'inherit',
43
+ cursor: 'pointer',
44
+ }}>
45
+ Restart
46
+ </button>
47
+ </div>
48
+ <div style={{ color: '#fff', fontWeight: 600, wordBreak: 'break-word' }}>
49
+ {name}: {message}
50
+ </div>
51
+ {stack ? (
52
+ <pre
53
+ style={{
54
+ margin: 0,
55
+ whiteSpace: 'pre-wrap',
56
+ wordBreak: 'break-word',
57
+ color: '#e79aa0',
58
+ fontSize: 12,
59
+ }}>
60
+ {stack}
61
+ </pre>
62
+ ) : null}
63
+ <div style={{ color: '#c98a8f', fontSize: 12 }}>
64
+ The preview stopped. Fix the code and restart the serve to reload, or press Restart to
65
+ retry.
66
+ </div>
67
+ </div>
68
+ );
69
+ }
@@ -1,6 +1,7 @@
1
1
  import React, { useCallback, useEffect, useRef, useState } from 'react';
2
2
  import { fontsReady } from './fonts';
3
3
  import { configureSceneCanvas, makeScene } from './scene';
4
+ import { ErrorOverlay } from './ErrorOverlay';
4
5
  import { SceneUI } from './SceneUI';
5
6
  // Engine-level scene player: mount a `SceneRuntime` against a canvas, wire
6
7
  // keyboard / pointer input, run the update+draw loop, and render the
@@ -131,7 +132,7 @@ export function ScenePlayer({ sceneData, sprites, files, behaviorClasses, sceneP
131
132
  }}
132
133
  />
133
134
  <SceneUI getRuntime={getRuntime} />
134
- {error ? <PlayErrorOverlay error={error} onRestart={onRestart} /> : null}
135
+ {error ? <ErrorOverlay error={error} onRestart={onRestart} /> : null}
135
136
  </div>
136
137
  );
137
138
  }
@@ -163,69 +164,3 @@ function startPlayerLoop(canvas, ctx, runtime, onFirstFrame, onError) {
163
164
  raf = requestAnimationFrame(tick);
164
165
  return () => cancelAnimationFrame(raf);
165
166
  }
166
- // Redbox overlay shown when the play loop throws. Covers the canvas with the
167
- // error name/message and stack so a broken behavior is legible instead of a
168
- // black screen. Restart remounts the loop; fixing the code and restarting the
169
- // serve reloads the whole preview fresh.
170
- function PlayErrorOverlay({ error, onRestart }) {
171
- const name = error?.name ?? 'Error';
172
- const message = error?.message ?? String(error);
173
- const stack = typeof error?.stack === 'string' ? error.stack : '';
174
- return (
175
- <div
176
- style={{
177
- position: 'absolute',
178
- inset: 0,
179
- zIndex: 2147483000,
180
- display: 'flex',
181
- flexDirection: 'column',
182
- gap: 12,
183
- padding: '20px 22px',
184
- background: 'rgba(20, 8, 8, 0.94)',
185
- color: '#ffd9dc',
186
- font: "13px/1.5 'SFMono-Regular', Consolas, 'Liberation Mono', monospace",
187
- overflow: 'auto',
188
- boxSizing: 'border-box',
189
- }}
190
- >
191
- <div style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
192
- <span style={{ fontSize: 15, fontWeight: 700, color: '#ff6b74' }}>Play error</span>
193
- <button
194
- type="button"
195
- onClick={onRestart}
196
- style={{
197
- marginLeft: 'auto',
198
- padding: '4px 12px',
199
- border: '1px solid #a02828',
200
- borderRadius: 4,
201
- background: '#a02828',
202
- color: '#fff',
203
- font: 'inherit',
204
- cursor: 'pointer',
205
- }}
206
- >
207
- Restart
208
- </button>
209
- </div>
210
- <div style={{ color: '#fff', fontWeight: 600, wordBreak: 'break-word' }}>
211
- {name}: {message}
212
- </div>
213
- {stack ? (
214
- <pre
215
- style={{
216
- margin: 0,
217
- whiteSpace: 'pre-wrap',
218
- wordBreak: 'break-word',
219
- color: '#e79aa0',
220
- fontSize: 12,
221
- }}
222
- >
223
- {stack}
224
- </pre>
225
- ) : null}
226
- <div style={{ color: '#c98a8f', fontSize: 12 }}>
227
- The preview stopped. Fix the code and restart the serve to reload, or press Restart to retry.
228
- </div>
229
- </div>
230
- );
231
- }