Skip to content

A fast 2D and 3D game engine — TypeScript SDK, C++/WebAssembly core, visual editor. Ship one project to web, desktop, WeChat MiniGames, playable ads, and native Android / iOS.

fix(replication): the client role commits synchronously — no authority window during the handshake

esengineacdcc7f421fe
diff --git a/desktop/src/playHost.ts b/desktop/src/playHost.ts
index a5639b7b1..f5d116322 100644
--- a/desktop/src/playHost.ts
+++ b/desktop/src/playHost.ts
@@ -180,6 +180,10 @@ async function buildAppAndRun(msg: InitMessage): Promise<void> {
setEditorMode(false);
setPlayMode(true);
+ // Role first, runtime second: initPlayRealmRuntime ends in app.run(), and by
+ // then the Net role must already be decided (see beginNet).
+ const netReady = beginNet(msg);
+
await initPlayRealmRuntime({
app,
module,
@@ -198,26 +202,38 @@ async function buildAppAndRun(msg: InitMessage): Promise<void> {
// host's __estellaHeadless): the editor can't reach into this OOPIF except by
// main-process frame eval, and the eval needs SOMETHING to query.
(window as unknown as { __estellaPlay?: unknown }).__estellaPlay = { app };
+
+ // Surface a failed handshake as a boot error rather than a silent
+ // half-session (the app keeps running; the role reverted to offline).
+ await netReady;
}
/**
- * Wire this realm's replication role. The ports arrived transferred with
- * `init`; a MessagePort queues until both ends attach, so the server and
- * client realms may boot in any order — the client's `connect` handshake
- * simply resolves once the server side comes up.
+ * Commit this realm's replication role. MUST run before the app loop starts:
+ * the role gates authority systems from the very first tick (a client realm
+ * that ticked as 'offline' while the handshake was in flight ran authority
+ * gameplay locally and left orphan state beside the replicated ghosts). The
+ * ports arrived transferred with `init`; a MessagePort queues until both ends
+ * attach, so the server and client realms may boot in any order. Returns the
+ * handshake completion for the caller to await before reporting ready.
*/
-async function wireNet(msg: InitMessage): Promise<void> {
- if (!msg.net || !app) return;
+function beginNet(msg: InitMessage): Promise<void> {
+ if (!msg.net || !app) return Promise.resolve();
const session = app.getResource(Net);
const ports = msg.netPorts ?? [];
+ const player = msg.net.player;
if (msg.net.role === 'server') {
const server = session.startServer();
for (const port of ports) server.attachConnection(new MessagePortTransport(port));
- console.log(`[play] listen server up (player ${msg.net.player}, ${ports.length} client port(s))`);
- } else if (ports[0]) {
- await session.connect(new MessagePortTransport(ports[0]));
- console.log(`[play] connected as player ${msg.net.player}`);
+ console.log(`[play] listen server up (player ${player}, ${ports.length} client port(s))`);
+ return Promise.resolve();
}
+ if (!ports[0]) return Promise.resolve();
+ // connect() commits the 'client' role synchronously; the await is only the
+ // handshake completing once the server realm comes up.
+ return session.connect(new MessagePortTransport(ports[0])).then(() => {
+ console.log(`[play] connected as player ${player}`);
+ });
}
async function boot(msg: InitMessage): Promise<void> {
@@ -235,7 +251,6 @@ async function boot(msg: InitMessage): Promise<void> {
}
await ensureEngine();
await buildAppAndRun(msg);
- await wireNet(msg);
post({ type: 'estella:play:ready' });
} catch (err) {
const message = err instanceof Error ? err.message : String(err);
diff --git a/sdk/src/net/replication/ReplicationPlugin.ts b/sdk/src/net/replication/ReplicationPlugin.ts
index 43ec906fe..7c03fc306 100644
--- a/sdk/src/net/replication/ReplicationPlugin.ts
+++ b/sdk/src/net/replication/ReplicationPlugin.ts
@@ -46,13 +46,25 @@ export class NetSession {
return this.server_;
}
- /** Become a replica: handshake over the given transport. */
+ /** Become a replica: handshake over the given transport. The role commits
+ * SYNCHRONOUSLY — from this call on, the session never simulates as the
+ * authority, even while the handshake is still in flight. (A role that
+ * only flipped on completion let authority-gated systems run for the
+ * first few ticks of a client realm and spawn local state that then
+ * lingered beside the replicated ghosts.) A failed handshake reverts to
+ * offline. */
async connect(transport: NetTransport, options?: ReplicationClientOptions): Promise<ReplicationClient> {
if (this.role_ !== 'offline') throw new Error(`[repl] session already ${this.role_}`);
const client = new ReplicationClient(this.app_.world, options);
- await client.connect(transport);
this.role_ = 'client';
this.client_ = client;
+ try {
+ await client.connect(transport);
+ } catch (err) {
+ this.client_ = null;
+ this.role_ = 'offline';
+ throw err;
+ }
return client;
}
diff --git a/sdk/tests/replication.test.ts b/sdk/tests/replication.test.ts
index b2a471d52..37725a97a 100644
--- a/sdk/tests/replication.test.ts
+++ b/sdk/tests/replication.test.ts
@@ -61,6 +61,34 @@ describe('replication handshake', () => {
expect(client.connectionId).toBeGreaterThan(0);
});
+ it('commits the client role synchronously — authority never runs during the handshake', async () => {
+ const clientApp = makeApp();
+ const session = clientApp.getResource(Net);
+ // Manual flush keeps the handshake in flight indefinitely.
+ const [, tb] = MemoryTransport.pair({ manualFlush: true });
+ const pending = session.connect(tb, { interpolationDelayTicks: 0 });
+ // The moment connect() is called the session is a client — ticks that
+ // run while the server is still booting must gate authority systems.
+ expect(session.role).toBe('client');
+ await clientApp.tick(STEP);
+ await clientApp.tick(STEP);
+ expect(session.role).toBe('client');
+ session.stop();
+ await expect(pending).rejects.toThrow();
+ });
+
+ it('a refused handshake reverts the session to offline', async () => {
+ const clientApp = makeApp();
+ const session = clientApp.getResource(Net);
+ const [ta, tb] = MemoryTransport.pair();
+ // A hostile peer that refuses every hello.
+ const raw = new NetChannel(ta);
+ raw.handle(ReplMsg.hello, () => ({ ok: false, error: 'go away' }));
+ await expect(session.connect(tb)).rejects.toThrow(/go away/);
+ expect(session.role).toBe('offline');
+ expect(session.client).toBeNull();
+ });
+
it('refuses a protocol version mismatch', async () => {
const serverApp = makeApp();
serverApp.getResource(Net).startServer().attachConnection(MemoryTransport.pair()[0]);