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(editor): every launch was a new origin, so every preference started over

yhh7e98a125c916
diff --git a/desktop/electron/loopbackServer.ts b/desktop/electron/loopbackServer.ts
index 831699ebb..edccc386a 100644
--- a/desktop/electron/loopbackServer.ts
+++ b/desktop/electron/loopbackServer.ts
@@ -36,7 +36,7 @@ const servers = new Map<string, { server: http.Server; url: string }>();
* (with a trailing slash). Throws if the directory has no `index.html` — a clear
* failure beats silently serving 404s.
*/
-export async function loopbackServer(rootDir: string): Promise<string> {
+export async function loopbackServer(rootDir: string, preferredPort = 0): Promise<string> {
const root = path.resolve(rootDir);
if (!existsSync(path.join(root, 'index.html'))) {
throw new Error(`no index.html in ${root} — nothing to serve`);
@@ -59,7 +59,13 @@ export async function loopbackServer(rootDir: string): Promise<string> {
res.writeHead(404).end('not found');
}
});
- await new Promise<void>((resolve) => server.listen(0, '127.0.0.1', resolve));
+ // The port IS the origin, and the origin is where the renderer's localStorage
+ // lives. A caller that wants its preferences back next launch asks for the
+ // port it had; anything already holding it falls back rather than failing.
+ await new Promise<void>((resolve) => {
+ server.once('error', () => { server.listen(0, '127.0.0.1', resolve); });
+ server.listen(preferredPort, '127.0.0.1', resolve);
+ });
const addr = server.address();
const port = typeof addr === 'object' && addr ? addr.port : 0;
const url = `http://127.0.0.1:${port}/`;
diff --git a/desktop/electron/main.ts b/desktop/electron/main.ts
index 68777e4d0..662cfe947 100644
--- a/desktop/electron/main.ts
+++ b/desktop/electron/main.ts
@@ -3,7 +3,7 @@
import { app, BrowserWindow, Menu, shell, ipcMain, dialog, protocol } from 'electron';
import { fileURLToPath } from 'node:url';
import { readFile, writeFile, open, stat } from 'node:fs/promises';
-import { existsSync } from 'node:fs';
+import { existsSync, readFileSync, writeFileSync } from 'node:fs';
import path from 'node:path';
import {
openProject,
@@ -145,6 +145,34 @@ protocol.registerSchemesAsPrivileged([
// (see appBaseUrl) so dockview popouts get the same-origin http opener they require.
const APP_ORIGIN = 'app://local';
+/**
+ * The port the renderer was served on last time.
+ *
+ * An ephemeral port makes a NEW ORIGIN every launch, and localStorage belongs to
+ * the origin — so the dock layout, the model beside the composer and every other
+ * preference the window keeps came back to its default each time, silently.
+ */
+const rendererPortFile = (): string => path.join(app.getPath('userData'), 'renderer-origin.json');
+
+function rememberedRendererPort(): number {
+ try {
+ const port = (JSON.parse(readFileSync(rendererPortFile(), 'utf8')) as { port?: unknown }).port;
+ return typeof port === 'number' && port > 0 && port < 65536 ? port : 0;
+ } catch {
+ return 0; // never served, or a torn write — an ephemeral port is the fallback
+ }
+}
+
+function rememberRendererPort(baseUrl: string): void {
+ const port = Number(new URL(baseUrl).port);
+ if (!port) return;
+ try {
+ writeFileSync(rendererPortFile(), `${JSON.stringify({ port }, null, 2)}\n`);
+ } catch (err) {
+ console.warn('[loopback] could not remember the renderer port', err);
+ }
+}
+
// Where the renderer is served from: Vite dev server, a loopback http origin when
// packaged (set in whenReady), or app:// as a last resort. Trailing slash so
// `${appBaseUrl}index.html` composes cleanly.
@@ -1657,7 +1685,8 @@ app.whenReady().then(async () => {
// and is unaffected. Fall back to app:// if the server can't start.
if (!VITE_DEV_SERVER_URL) {
try {
- appBaseUrl = await loopbackServer(RENDERER_DIST);
+ appBaseUrl = await loopbackServer(RENDERER_DIST, rememberedRendererPort());
+ rememberRendererPort(appBaseUrl);
} catch (err) {
console.error('[loopback] renderer server failed; falling back to app://', err);
appBaseUrl = `${APP_ORIGIN}/`;
diff --git a/desktop/tests/loopback-origin.test.ts b/desktop/tests/loopback-origin.test.ts
new file mode 100644
index 000000000..53da89176
--- /dev/null
+++ b/desktop/tests/loopback-origin.test.ts
@@ -0,0 +1,58 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file The renderer's origin, which is where its preferences live.
+ *
+ * Served on an ephemeral port, the packaged editor got a new origin every launch
+ * — and localStorage belongs to the origin, so the dock layout, the model beside
+ * the composer and every other window preference came back to its default with
+ * nothing said. A port that is asked for and given back is the whole fix.
+ */
+import { describe, it, expect, afterEach } from 'vitest';
+import { mkdtemp, writeFile, rm } from 'node:fs/promises';
+import { tmpdir } from 'node:os';
+import net from 'node:net';
+import path from 'node:path';
+import { loopbackServer, closeAllLoopbackServers } from '../electron/loopbackServer';
+
+const roots: string[] = [];
+
+const served = async (): Promise<string> => {
+ const dir = await mkdtemp(path.join(tmpdir(), 'estella-loopback-'));
+ await writeFile(path.join(dir, 'index.html'), '<!doctype html>');
+ roots.push(dir);
+ return dir;
+};
+
+const portOf = (url: string) => Number(new URL(url).port);
+
+afterEach(async () => {
+ closeAllLoopbackServers();
+ for (const dir of roots.splice(0)) await rm(dir, { recursive: true, force: true });
+});
+
+describe('the origin the renderer is served on', () => {
+ it('takes the port it is asked for, so the origin is the same one as last time', async () => {
+ const first = await loopbackServer(await served());
+ const port = portOf(first);
+ closeAllLoopbackServers();
+
+ const again = await loopbackServer(await served(), port);
+ expect(portOf(again)).toBe(port);
+ });
+
+ it('falls back rather than failing when something else holds it', async () => {
+ const squatter = net.createServer();
+ await new Promise<void>((resolve) => squatter.listen(0, '127.0.0.1', resolve));
+ const taken = (squatter.address() as net.AddressInfo).port;
+
+ const url = await loopbackServer(await served(), taken);
+ expect(portOf(url)).toBeGreaterThan(0);
+ expect(portOf(url)).not.toBe(taken);
+ await new Promise<void>((resolve) => squatter.close(() => resolve()));
+ });
+
+ it('still serves an ephemeral port to a caller that wants any', async () => {
+ expect(portOf(await loopbackServer(await served()))).toBeGreaterThan(0);
+ });
+});