castle-web-cli 0.4.207 → 0.4.209

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 (55) hide show
  1. package/dist/api.d.ts +5 -0
  2. package/dist/castle-host/host.js +151 -0
  3. package/dist/castleJson.d.ts +4 -0
  4. package/dist/castleJson.js +3 -1
  5. package/dist/devSessionServer.js +1 -0
  6. package/dist/editorConfig.d.ts +12 -0
  7. package/dist/editorConfig.js +72 -6
  8. package/dist/ide.d.ts +18 -0
  9. package/dist/ide.js +44 -1
  10. package/dist/init.js +1 -1
  11. package/dist/native/loop.js +1 -1
  12. package/dist/native/playtest-executor.js +36 -4
  13. package/dist/native/playtest-remote.d.ts +1 -0
  14. package/dist/native/playtest-remote.js +61 -5
  15. package/dist/native/playtest.d.ts +35 -2
  16. package/dist/native/playtest.js +162 -18
  17. package/dist/platformDoc.d.ts +1 -0
  18. package/dist/platformDoc.js +24 -3
  19. package/dist/playUrl.d.ts +3 -0
  20. package/dist/playUrl.js +12 -0
  21. package/dist/save-deck.js +1 -0
  22. package/dist/shell/assets/{index-b_bebkRb.css → index-BCrgYh76.css} +1 -1
  23. package/dist/shell/assets/{index-C6SXXPwm.js → index-DzLbNBc7.js} +68 -68
  24. package/dist/shell/index.html +2 -2
  25. package/kits/base/CLAUDE.md +1 -0
  26. package/kits/base/castle.json +1 -1
  27. package/kits/base/sdk/README.md +70 -7
  28. package/kits/base/sdk/castle.d.ts +1 -0
  29. package/kits/base/sdk/commands.d.ts +48 -0
  30. package/kits/base/sdk/commands.js +25 -0
  31. package/kits/base/sdk/multiplayer.d.ts +3 -0
  32. package/kits/base/sdk/multiplayer.js +13 -0
  33. package/kits/base/sdk/multiplayerVoice.d.ts +67 -0
  34. package/kits/base/sdk/multiplayerVoice.js +309 -0
  35. package/kits/base/sdk/transport.d.ts +2 -1
  36. package/kits/base/sdk/transport.js +15 -1
  37. package/kits/multiplayer-2d/castle.json +2 -2
  38. package/kits/multiplayer-2d/code/systems/multiplayer.js +7 -1
  39. package/kits/multiplayer-3d/castle.json +2 -2
  40. package/kits/multiplayer-3d/code/systems/multiplayer.js +8 -4
  41. package/kits/physics-2d/castle.json +1 -1
  42. package/kits/physics-2d/editors/SceneEditor.jsx +18 -4
  43. package/kits/physics-2d/systems/media.js +3 -5
  44. package/kits/physics-3d/castle.json +2 -2
  45. package/kits/physics-3d/engine3d/PxModelEditor.jsx +2 -2
  46. package/kits/physics-3d/engine3d/pxmodel.js +7 -0
  47. package/kits/real-time/CLAUDE.md +3 -0
  48. package/kits/real-time/castle.json +1 -1
  49. package/kits/real-time/code/client/connection.js +17 -2
  50. package/kits/real-time/code/client/gameHooks.js +5 -0
  51. package/kits/real-time/code/client/joinOverlay.js +23 -5
  52. package/kits/real-time/code/client/messages.js +4 -0
  53. package/kits/real-time/code/server/persist.js +19 -10
  54. package/kits/real-time/code/server/session.js +19 -0
  55. package/package.json +2 -2
@@ -0,0 +1,309 @@
1
+ import { hostRequest, setVoiceEventHandler } from "./transport";
2
+ // Voice chat in a multiplayer session. The host (castle.xyz or the Castle app) owns
3
+ // the microphone, the call and playback, and shows its own prompt and live-mic badge; a
4
+ // deck never touches audio. What a deck gets: whether voice is on, a way to ask the
5
+ // player to join, who is speaking, and a suggested volume and stereo position per
6
+ // player (proximity chat). Push-to-talk and muting are the player's, in the host's UI.
7
+ // A deck driving proximity every frame sends far more than the host needs.
8
+ export const VOICE_MIX_INTERVAL_MS = 100;
9
+ const DEFAULT_MIX = { gain: 1, pan: 0 };
10
+ let activeVoice = null;
11
+ function dispatchVoiceEvent(event) {
12
+ activeVoice?.receive(event);
13
+ }
14
+ // One multiplayer connection is live at a time, so one voice receives host events.
15
+ function setActiveVoice(voice, current) {
16
+ if (current && activeVoice !== current)
17
+ return;
18
+ activeVoice = voice;
19
+ }
20
+ export class MultiplayerVoiceImpl {
21
+ access;
22
+ currentState = "unavailable";
23
+ // The session this voice state belongs to; "" before the first attach or in solo.
24
+ voiceSessionId = "";
25
+ attaching = null;
26
+ // Bumped on every host state event, so a join reply never overrides a newer one.
27
+ hostStateVersion = 0;
28
+ pendingJoin = null;
29
+ joinRequest = null;
30
+ speakingUserIds = [];
31
+ speaking = [];
32
+ pendingMix = {};
33
+ sentMix = {};
34
+ mixTimer = null;
35
+ lastMixSentAt = 0;
36
+ disposed = false;
37
+ states = new Set();
38
+ speakers = new Set();
39
+ constructor(access) {
40
+ this.access = access;
41
+ }
42
+ get state() {
43
+ return this.currentState;
44
+ }
45
+ // Called by the connection whenever it (re)gains a session. A reconnect keeps the
46
+ // session; a re-acquisition may land in a different one, or in solo, and voice for
47
+ // the old session ends with it. Asks the host where voice stands; a host without
48
+ // voice (an older app, local dev) answers with an error or "unavailable".
49
+ attach() {
50
+ if (this.disposed)
51
+ return Promise.resolve();
52
+ setActiveVoice(this);
53
+ setVoiceEventHandler(dispatchVoiceEvent);
54
+ const sessionId = this.access.isSolo() ? "" : this.access.sessionId();
55
+ if (this.voiceSessionId !== sessionId) {
56
+ this.endSession();
57
+ // The old session's state means nothing for the new one until the host answers.
58
+ this.setState("unavailable");
59
+ }
60
+ this.voiceSessionId = sessionId;
61
+ if (!sessionId) {
62
+ this.setState("unavailable");
63
+ this.attaching = null;
64
+ return Promise.resolve();
65
+ }
66
+ const attaching = hostRequest("voice.getState", { sessionId }).then((result) => {
67
+ if (this.isCurrent(sessionId))
68
+ this.setState(result.state);
69
+ }, () => {
70
+ if (this.isCurrent(sessionId))
71
+ this.setState("unavailable");
72
+ });
73
+ this.attaching = attaching;
74
+ return attaching;
75
+ }
76
+ // A second call while the player is still choosing shares the first one's answer.
77
+ requestJoin() {
78
+ if (!this.joinRequest) {
79
+ const request = this.askToJoin().finally(() => {
80
+ if (this.joinRequest === request)
81
+ this.joinRequest = null;
82
+ });
83
+ this.joinRequest = request;
84
+ }
85
+ return this.joinRequest;
86
+ }
87
+ async askToJoin() {
88
+ // Registered before any waiting, so leave() or a session change can withdraw a
89
+ // request that hasn't reached the host yet.
90
+ const pending = new AbortController();
91
+ this.pendingJoin = pending;
92
+ // `join()` resolves at hello, before the host has said whether voice is on. A
93
+ // reconnect can attach again meanwhile; wait for the latest answer.
94
+ let awaited = null;
95
+ while (this.attaching && this.attaching !== awaited) {
96
+ awaited = this.attaching;
97
+ await awaited;
98
+ }
99
+ if (pending.signal.aborted ||
100
+ this.disposed ||
101
+ !this.voiceSessionId ||
102
+ this.currentState === "unavailable" ||
103
+ this.currentState === "live") {
104
+ if (this.pendingJoin === pending)
105
+ this.pendingJoin = null;
106
+ if (pending.signal.aborted || this.currentState !== "live")
107
+ return "unavailable";
108
+ return "joined";
109
+ }
110
+ const sessionId = this.voiceSessionId;
111
+ const version = this.hostStateVersion;
112
+ this.setState("joining");
113
+ let status;
114
+ try {
115
+ ({ status } = await hostRequest("voice.requestJoin", { sessionId }, { signal: pending.signal }));
116
+ }
117
+ catch {
118
+ status = "unavailable";
119
+ }
120
+ finally {
121
+ if (this.pendingJoin === pending)
122
+ this.pendingJoin = null;
123
+ }
124
+ if (pending.signal.aborted || !this.isCurrent(sessionId)) {
125
+ // Withdrawn, or the game connection ended, while the player was choosing. The
126
+ // abort already cancelled the request at the host, whose executor undoes a
127
+ // "yes" that lands anyway.
128
+ return "unavailable";
129
+ }
130
+ if (version === this.hostStateVersion) {
131
+ this.setState(status === "joined" ? "live" : status === "unavailable" ? "unavailable" : "off");
132
+ }
133
+ return status;
134
+ }
135
+ leave() {
136
+ if (this.disposed)
137
+ return;
138
+ const inVoice = this.currentState === "live" || this.currentState === "joining";
139
+ if (!inVoice && this.pendingJoin === null)
140
+ return;
141
+ this.withdraw();
142
+ if (inVoice) {
143
+ this.setState("off");
144
+ this.sendLeave(this.voiceSessionId);
145
+ }
146
+ }
147
+ setMix(mix) {
148
+ if (this.disposed || !mix || typeof mix !== "object")
149
+ return;
150
+ const players = this.access.players();
151
+ for (const [playerId, entry] of Object.entries(mix)) {
152
+ const player = players.find((candidate) => candidate.playerId === playerId);
153
+ if (!player || !entry || typeof entry !== "object")
154
+ continue;
155
+ const next = { ...this.pendingMix[player.userId] };
156
+ if (typeof entry.gain === "number" && Number.isFinite(entry.gain)) {
157
+ next.gain = clamp(entry.gain, 0, 1);
158
+ }
159
+ if (typeof entry.pan === "number" && Number.isFinite(entry.pan)) {
160
+ next.pan = clamp(entry.pan, -1, 1);
161
+ }
162
+ this.pendingMix[player.userId] = next;
163
+ }
164
+ this.scheduleMix();
165
+ }
166
+ onState(callback) {
167
+ this.states.add(callback);
168
+ callListener(callback, this.currentState);
169
+ return () => this.states.delete(callback);
170
+ }
171
+ onSpeaking(callback) {
172
+ this.speakers.add(callback);
173
+ callListener(callback, this.speaking.slice());
174
+ return () => this.speakers.delete(callback);
175
+ }
176
+ receive(event) {
177
+ if (this.disposed || !this.voiceSessionId || event.sessionId !== this.voiceSessionId) {
178
+ return;
179
+ }
180
+ if (event.type === "state") {
181
+ this.hostStateVersion += 1;
182
+ this.setState(event.state);
183
+ return;
184
+ }
185
+ this.speakingUserIds = event.userIds.slice();
186
+ this.emitSpeaking();
187
+ }
188
+ // The roster changed: speakers are re-mapped, and mixes for players who left dropped.
189
+ rosterChanged() {
190
+ if (this.disposed)
191
+ return;
192
+ const userIds = new Set(this.access.players().map((player) => player.userId));
193
+ for (const userId of Object.keys(this.pendingMix)) {
194
+ if (!userIds.has(userId))
195
+ delete this.pendingMix[userId];
196
+ }
197
+ for (const userId of Object.keys(this.sentMix)) {
198
+ if (!userIds.has(userId))
199
+ delete this.sentMix[userId];
200
+ }
201
+ this.emitSpeaking();
202
+ }
203
+ // The game connection ended: voice for its session goes with it.
204
+ dispose() {
205
+ if (this.disposed)
206
+ return;
207
+ this.endSession();
208
+ this.setState("unavailable");
209
+ this.disposed = true;
210
+ if (this.mixTimer !== null)
211
+ clearTimeout(this.mixTimer);
212
+ this.mixTimer = null;
213
+ setActiveVoice(null, this);
214
+ }
215
+ isCurrent(sessionId) {
216
+ return !this.disposed && sessionId !== "" && sessionId === this.voiceSessionId;
217
+ }
218
+ // Cancels a pending request, so a retry starts a fresh prompt.
219
+ withdraw() {
220
+ this.pendingJoin?.abort();
221
+ this.pendingJoin = null;
222
+ this.joinRequest = null;
223
+ }
224
+ // Leaves the current voice session, if the player is in it or being asked.
225
+ endSession() {
226
+ const inVoice = this.currentState === "live" || this.currentState === "joining" || this.pendingJoin !== null;
227
+ this.withdraw();
228
+ if (inVoice && this.voiceSessionId)
229
+ this.sendLeave(this.voiceSessionId);
230
+ this.speakingUserIds = [];
231
+ this.pendingMix = {};
232
+ this.sentMix = {};
233
+ this.emitSpeaking();
234
+ }
235
+ sendLeave(sessionId) {
236
+ void hostRequest("voice.leave", { sessionId }).catch(() => { });
237
+ }
238
+ setState(state) {
239
+ if (this.currentState === state)
240
+ return;
241
+ this.currentState = state;
242
+ if (state !== "live")
243
+ this.speakingUserIds = [];
244
+ this.emitSpeaking();
245
+ for (const callback of this.states)
246
+ callListener(callback, state);
247
+ if (state === "live") {
248
+ // A rejoined call starts from scratch at the host: send the deck's mix again.
249
+ for (const userId of Object.keys(this.sentMix)) {
250
+ this.pendingMix[userId] ??= {};
251
+ }
252
+ this.scheduleMix();
253
+ }
254
+ }
255
+ emitSpeaking() {
256
+ const userIds = new Set(this.speakingUserIds);
257
+ const playerIds = this.access
258
+ .players()
259
+ .filter((player) => userIds.has(player.userId))
260
+ .map((player) => player.playerId)
261
+ .sort();
262
+ if (playerIds.join("\n") === this.speaking.join("\n"))
263
+ return;
264
+ this.speaking = playerIds;
265
+ for (const callback of this.speakers)
266
+ callListener(callback, playerIds.slice());
267
+ }
268
+ scheduleMix() {
269
+ if (this.mixTimer !== null || Object.keys(this.pendingMix).length === 0)
270
+ return;
271
+ const wait = Math.max(0, this.lastMixSentAt + VOICE_MIX_INTERVAL_MS - Date.now());
272
+ this.mixTimer = setTimeout(() => {
273
+ this.mixTimer = null;
274
+ this.flushMix();
275
+ }, wait);
276
+ }
277
+ // Held until the player is in voice, then sent: the latest mix is what matters. Each
278
+ // entry goes out whole, so a field the deck didn't name keeps its last value.
279
+ flushMix() {
280
+ if (this.disposed || !this.voiceSessionId || this.currentState !== "live")
281
+ return;
282
+ const userIds = new Set(this.access.players().map((player) => player.userId));
283
+ const mix = {};
284
+ for (const [userId, entry] of Object.entries(this.pendingMix)) {
285
+ if (!userIds.has(userId))
286
+ continue;
287
+ const previous = this.sentMix[userId] ?? DEFAULT_MIX;
288
+ const full = { gain: entry.gain ?? previous.gain, pan: entry.pan ?? previous.pan };
289
+ this.sentMix[userId] = full;
290
+ mix[userId] = full;
291
+ }
292
+ this.pendingMix = {};
293
+ if (Object.keys(mix).length === 0)
294
+ return;
295
+ this.lastMixSentAt = Date.now();
296
+ void hostRequest("voice.setMix", { sessionId: this.voiceSessionId, mix }).catch(() => { });
297
+ }
298
+ }
299
+ function clamp(value, min, max) {
300
+ return Math.min(max, Math.max(min, value));
301
+ }
302
+ function callListener(callback, value) {
303
+ try {
304
+ callback(value);
305
+ }
306
+ catch {
307
+ // One deck listener must not break voice or other listeners.
308
+ }
309
+ }
@@ -1,4 +1,4 @@
1
- import { type CommandName, type CommandParams, type CommandResult, type LifecycleEvent } from "./commands";
1
+ import { type CommandName, type CommandParams, type CommandResult, type LifecycleEvent, type VoiceEvent } from "./commands";
2
2
  type PostChannel = "mobile" | "web";
3
3
  export interface HostStreamOptions {
4
4
  onStream?: (event: unknown) => void;
@@ -20,5 +20,6 @@ export declare function getCommandChannel(): PostChannel | "local";
20
20
  export declare function hostNotify(event: LifecycleEvent): void;
21
21
  export declare function postUnloadDone(unloadId: string, state?: string): void;
22
22
  export declare function setUnloadHandler(handler: (unloadId: string) => void): void;
23
+ export declare function setVoiceEventHandler(handler: ((event: VoiceEvent) => void) | null): void;
23
24
  export declare function installHostListener(): void;
24
25
  export {};
@@ -11,7 +11,7 @@
11
11
  // A streaming command (agent.chat) gets stream envelopes on its requestId before
12
12
  // its response. Each one goes to the caller's onStream and restarts the wait,
13
13
  // and the caller's AbortSignal sends the host a cancel envelope.
14
- import { CASTLE_SDK_PROTOCOL, COMMAND_TIMEOUTS_MS, STREAM_IDLE_TIMEOUT_MS, isResponseEnvelope, isStreamEnvelope, unloadRequestId, } from "./commands";
14
+ import { CASTLE_SDK_PROTOCOL, COMMAND_TIMEOUTS_MS, STREAM_IDLE_TIMEOUT_MS, isResponseEnvelope, isStreamEnvelope, unloadRequestId, voiceEventFrom, } from "./commands";
15
15
  import { getCastleEmbed } from "./context";
16
16
  import { CastleError } from "./errors";
17
17
  import { cancelLocalCommand, releaseLocalCommand, sendLocalCommand } from "./runtime";
@@ -23,6 +23,8 @@ const INTERACTIVE_COMMANDS = new Set([
23
23
  "pass.offer",
24
24
  "snapshot.offer",
25
25
  "portal.open",
26
+ // The host's voice prompt and the browser's microphone permission.
27
+ "voice.requestJoin",
26
28
  ]);
27
29
  // Request ids carry a per-page prefix so that a host serving several decks at
28
30
  // once can key a cancel by requestId alone.
@@ -31,6 +33,7 @@ let nextRequestId = 1;
31
33
  const pending = new Map();
32
34
  let listenersInstalled = false;
33
35
  let unloadHandler = null;
36
+ let voiceEventHandler = null;
34
37
  export async function hostRequest(command, params, stream = {}) {
35
38
  try {
36
39
  const env = await sendCommand(resolveChannel(), command, params, stream);
@@ -93,6 +96,12 @@ export function postUnloadDone(unloadId, state) {
93
96
  export function setUnloadHandler(handler) {
94
97
  unloadHandler = handler;
95
98
  }
99
+ // Registered by multiplayerVoice.ts, the same way, for host voice events.
100
+ export function setVoiceEventHandler(handler) {
101
+ voiceEventHandler = handler;
102
+ if (handler)
103
+ installHostListener();
104
+ }
96
105
  function resolveChannel() {
97
106
  if (typeof window === "undefined")
98
107
  return "local";
@@ -218,6 +227,11 @@ function receive(message) {
218
227
  deliverStream(message.requestId, message.stream);
219
228
  return;
220
229
  }
230
+ const voiceEvent = voiceEventFrom(message);
231
+ if (voiceEvent) {
232
+ voiceEventHandler?.(voiceEvent);
233
+ return;
234
+ }
221
235
  const unloadId = unloadRequestId(message);
222
236
  if (unloadId !== null)
223
237
  unloadHandler?.(unloadId);
@@ -7,7 +7,7 @@
7
7
  "imports": {
8
8
  "castle.real-time": {
9
9
  "deckId": "xFVr-afOLuUQ",
10
- "version": "2026-09-24T07:00:06.238Z"
10
+ "version": "2026-09-25T17:53:47.749Z"
11
11
  },
12
12
  "castle.physics-2d": {
13
13
  "deckId": "ckRZGFW4iPrx",
@@ -27,5 +27,5 @@
27
27
  },
28
28
  "deckId": "oiFu96LkwZ09",
29
29
  "cardId": "nkJgrvrCby3H",
30
- "publishedVersion": "2026-09-24T18:05:54.492Z"
30
+ "publishedVersion": "2026-09-25T17:54:26.340Z"
31
31
  }
@@ -157,7 +157,13 @@ class MultiplayerSystem {
157
157
  this.starting = true;
158
158
  this.joinStartedAt ||= performance.now();
159
159
  try {
160
- this.net = await connectSession({ onLog: (text) => console.log(`[multiplayer] ${text}`) });
160
+ this.net = await connectSession({
161
+ onLog: (text) => console.log(`[multiplayer] ${text}`),
162
+
163
+ // A deck message can be handled on arrival through the `arrive` hook,
164
+ // which still runs in a hidden tab. State messages always wait for a frame.
165
+ onArrival: (msg) => msg.k !== STATE && msg.k !== WORLD && game.arrive?.(msg, this) === true,
166
+ });
161
167
  } catch (err) {
162
168
  console.log(`[multiplayer] could not join: ${err?.message ?? err}`);
163
169
  this.starting = false;
@@ -7,7 +7,7 @@
7
7
  "imports": {
8
8
  "castle.real-time": {
9
9
  "deckId": "xFVr-afOLuUQ",
10
- "version": "2026-09-24T08:31:35.178Z"
10
+ "version": "2026-09-25T17:53:47.749Z"
11
11
  },
12
12
  "castle.physics-3d": {
13
13
  "deckId": "JH0SclbPVP0y",
@@ -26,7 +26,7 @@
26
26
  "autoUpdateWhenImported": true,
27
27
  "deckId": "ZwA_P_-VO-Qh",
28
28
  "cardId": "bvRmCzyUpt_a",
29
- "publishedVersion": "2026-09-24T18:45:09.264Z",
29
+ "publishedVersion": "2026-09-25T17:54:30.097Z",
30
30
  "main": "main.jsx",
31
31
  "server": {
32
32
  "main": "code/server/index.js",
@@ -214,7 +214,13 @@ class MultiplayerSystem {
214
214
  this.starting = true;
215
215
  this.joinStartedAt ||= performance.now();
216
216
  try {
217
- this.net = await connectSession({ onLog: (text) => console.log(`[multiplayer] ${text}`) });
217
+ this.net = await connectSession({
218
+ onLog: (text) => console.log(`[multiplayer] ${text}`),
219
+
220
+ // A deck message can be handled on arrival through the `arrive` hook,
221
+ // which still runs in a hidden tab. State messages always wait for a frame.
222
+ onArrival: (msg) => msg.k !== STATE && msg.k !== WORLD && game.arrive?.(msg, this) === true,
223
+ });
218
224
  } catch (err) {
219
225
  console.log(`[multiplayer] could not join: ${err?.message ?? err}`);
220
226
  this.starting = false;
@@ -598,9 +604,7 @@ class MultiplayerSystem {
598
604
  const pose = body
599
605
  ? Poses.packPose(body.translation(), body.rotation())
600
606
  : Poses.poseOf(transform);
601
- const velocity = body
602
- ? Poses.packVelocity(body.linvel(), body.angvel())
603
- : [0, 0, 0, 0, 0, 0];
607
+ const velocity = body ? Poses.packVelocity(body.linvel(), body.angvel()) : [0, 0, 0, 0, 0, 0];
604
608
  owned.set(id, [id, ...pose, ...velocity, ...this.reportTail(id)]);
605
609
  }
606
610
  const releases = Ownership.toRelease(this.own, objects, me, Poses.REACH, now);
@@ -68,7 +68,7 @@
68
68
  "onUpdate": "scripts/onUpdate.mjs",
69
69
  "title": "physics-2d",
70
70
  "description": "Scene Editor. Works like classic Castle: actors, blueprints, behaviors and drawing tools, with physics built in.",
71
- "publishedVersion": "2026-09-23T02:16:34.231Z",
71
+ "publishedVersion": "2026-09-25T17:51:55.024Z",
72
72
  "imports": {
73
73
  "castle.base": {
74
74
  "deckId": "yRcmH4_aYllE",
@@ -1807,10 +1807,21 @@ function useScenePlayLoop({
1807
1807
  }
1808
1808
  raf = requestAnimationFrame(frame);
1809
1809
  };
1810
+ // Edit mode draws one runtime built from the current `sceneData`. The effect
1811
+ // reruns when the scene, sprites or files change, and a behavior hot swap
1812
+ // drops it so the next frame builds it again.
1813
+ //
1814
+ // It is built inside a frame, so a broken behavior module throws into the
1815
+ // frame's catch and shows the redbox.
1816
+ let editScene = null;
1817
+ const unsubscribeBehaviors = subscribeBehaviors(() => {
1818
+ editScene = null;
1819
+ });
1810
1820
  const drawFrame = (dt, frameViewport) => {
1811
- const scene = isPlaying
1812
- ? runtimeRef.current
1813
- : makeScene(sceneData, behaviorClasses, sprites, files, path);
1821
+ if (!isPlaying && !editScene) {
1822
+ editScene = makeScene(sceneData, behaviorClasses, sprites, files, path);
1823
+ }
1824
+ const scene = isPlaying ? runtimeRef.current : editScene;
1814
1825
  if (scene) {
1815
1826
  const snap = getSnapSettings(sceneData);
1816
1827
  if (isPlaying) scene.update(dt);
@@ -1843,7 +1854,10 @@ function useScenePlayLoop({
1843
1854
  // fixes the file resets this effect, and the stale redbox must go with it.
1844
1855
  setLoopError(null);
1845
1856
  raf = requestAnimationFrame(frame);
1846
- return () => cancelAnimationFrame(raf);
1857
+ return () => {
1858
+ cancelAnimationFrame(raf);
1859
+ unsubscribeBehaviors();
1860
+ };
1847
1861
  // eslint-disable-next-line react-hooks/exhaustive-deps -- `text` proxies `sceneData` identity; resetting on every parse churns the loop and wipes runtime state.
1848
1862
  }, [
1849
1863
  sprites,
@@ -20,11 +20,9 @@ import { initialMedia, mediaFilesOfKind } from '../engine/files';
20
20
  import { reapUnusedMedia, stopAllMedia } from '../engine/media';
21
21
  import { Sound, initSounds, stopAllSounds } from '../engine/sound';
22
22
 
23
- // Preloading is the DECK's, not a scene's, so it starts here at module load
24
- // rather than per-runtime -- the editor builds a throwaway runtime every frame
25
- // to draw its preview, and decoding the deck's sounds sixty times a second is
26
- // not a thing to do. Vite evaluates a module once, which is exactly the scope
27
- // wanted.
23
+ // Preloading is the deck's, not a scene's, so it runs once at module load.
24
+ // The editor builds a new preview runtime on every scene edit; each would
25
+ // decode the deck's sounds again. Vite evaluates a module once.
28
26
  initSounds(
29
27
  Object.fromEntries(mediaFilesOfKind('audio').map((path) => [path, initialMedia[path]]))
30
28
  );
@@ -54,12 +54,12 @@
54
54
  },
55
55
  "castle.base": {
56
56
  "deckId": "yRcmH4_aYllE",
57
- "version": "2026-09-23T05:44:46.889Z"
57
+ "version": "2026-09-24T21:25:28.679Z"
58
58
  }
59
59
  },
60
60
  "main": "main.jsx",
61
61
  "autoUpdateWhenImported": true,
62
62
  "deckId": "JH0SclbPVP0y",
63
63
  "cardId": "eXfAaUdbSU5A",
64
- "publishedVersion": "2026-09-24T18:05:44.539Z"
64
+ "publishedVersion": "2026-09-25T17:46:00.903Z"
65
65
  }
@@ -19,7 +19,7 @@ import {
19
19
  } from '@imports/castle.physics-2d/engine/ui';
20
20
  import { useEditHistory, useHostUndoRedo } from '@imports/castle.physics-2d/editors/editorHistory';
21
21
  import { useLiveDeckFiles3D, useStableSprites, fetchMissingFile } from './modelFiles';
22
- import { parseModelCached, parseModel, serializeModel, STARTER_MODEL_TEXT } from './pxmodel';
22
+ import { makePart, parseModelCached, parseModel, serializeModel, STARTER_MODEL_TEXT } from './pxmodel';
23
23
  import { boxMesh, extrudeFace, roundMeshInPlace } from './meshops';
24
24
  import {
25
25
  createModelEditorWorld,
@@ -171,7 +171,7 @@ export function PxModelEditor({ path }) {
171
171
  part.height = 0.9;
172
172
  }
173
173
  if (kind === 'box') part.size = [0.6, 0.6, 0.6];
174
- next.parts.push(part);
174
+ next.parts.push(makePart(part, next.parts.length));
175
175
  });
176
176
  if (id) setSelectedPartId(id);
177
177
  };
@@ -72,6 +72,13 @@ function normalizePart(raw, index) {
72
72
  return part;
73
73
  }
74
74
 
75
+ // A part built in editor code carries only the fields the editor set. Every
76
+ // other field, the vec3s included, comes from PART_DEFAULTS here; serializeModel
77
+ // reads all of them.
78
+ export function makePart(raw, index = 0) {
79
+ return normalizePart(raw, index);
80
+ }
81
+
75
82
  // Parse model text into { name, parts } with defaults applied, or null when
76
83
  // it isn't a model. Duplicate ids get suffixed; a parent ref that doesn't
77
84
  // resolve (or cycles) is dropped to root rather than rejected.
@@ -30,6 +30,9 @@ imports these modules from here directly.
30
30
  - `restore(sim, saved)` receives the last `save` result before `ready`. Storage
31
31
  is keyed by deck, so the deck must be published; `castle-web serve` brokers it
32
32
  as the deck's creator.
33
+ - **A failed room read does not start the room.** No hook runs and nothing is
34
+ saved, so the stored room is kept; players see a message to reload. An
35
+ unpublished deck's reads count as empty, not failed.
33
36
  - A pose is an opaque array of numbers here, so anything reading inside one takes
34
37
  the kit's `code/client/poses.js` as an argument. That is the seam to use when
35
38
  something genuinely needs a lower level.
@@ -9,5 +9,5 @@
9
9
  "autoUpdateWhenImported": true,
10
10
  "deckId": "xFVr-afOLuUQ",
11
11
  "cardId": "w6G45sy3_P_m",
12
- "publishedVersion": "2026-09-24T18:05:46.175Z"
12
+ "publishedVersion": "2026-09-25T17:53:47.749Z"
13
13
  }
@@ -4,6 +4,7 @@
4
4
 
5
5
  import { Multiplayer } from 'castle-web-sdk';
6
6
  import * as Messages from './messages.js';
7
+ import { showLoadFailed } from './joinOverlay.js';
7
8
 
8
9
  const SEND_MS = 1000 / Messages.MOVE_HZ;
9
10
 
@@ -33,14 +34,28 @@ function makeNet(connection) {
33
34
  // Join the deck's public session and return the interface its client system
34
35
  // uses. The SDK assigns the session and supplies authenticated roster names, so
35
36
  // a deck message carries no sender-chosen username.
36
- export async function connectSession({ onLog = () => {} } = {}) {
37
+ //
38
+ // `onArrival(msg)` sees each message the moment it arrives, before it is
39
+ // queued, and returning true keeps it out of the queue. It runs whether or not
40
+ // frames do: a hidden tab stops `requestAnimationFrame`, so a reply left in the
41
+ // queue would wait until the tab is shown again.
42
+ export async function connectSession({ onLog = () => {}, onArrival = () => false } = {}) {
37
43
  const connection = await Multiplayer.join({ mode: 'public' });
38
44
  const net = makeNet(connection);
39
45
 
40
46
  // Messages are queued with this page's clock at arrival. The client system
41
47
  // drains the queue on its own frame and pairs `localMs` with the message's `t`
42
48
  // in `clock.js`.
43
- connection.onMessage((data) => net.inbox.push({ ...data, localMs: performance.now() }));
49
+ connection.onMessage((data) => {
50
+ if (data?.k === Messages.UNLOADED) {
51
+ showLoadFailed();
52
+ return;
53
+ }
54
+ const msg = { ...data, localMs: performance.now() };
55
+ if (!onArrival(msg)) {
56
+ net.inbox.push(msg);
57
+ }
58
+ });
44
59
  connection.onRoster(({ players, you }) => {
45
60
  // The roster arrives after the connection, so this is the first point at
46
61
  // which the local player's own name can be read.
@@ -18,6 +18,11 @@ const modules = {
18
18
  // The 2D and 3D multiplayer systems import this value and call the hooks at the
19
19
  // stages listed below.
20
20
  //
21
+ // arrive(msg, system) a message that is neither STATE nor WORLD,
22
+ // the moment it arrives, with or without
23
+ // frames. Returning true handles it there, and
24
+ // it skips the queue and `message`. It runs
25
+ // outside a frame, so it has no scene
21
26
  // message(scene, msg, system) a message that is neither STATE nor WORLD,
22
27
  // after the queue is drained
23
28
  // state(scene, msg, system) a STATE or WORLD message, after the kit has