Skip to content

Commit a5fe254

Browse files
committed
Hand over URLs reliably and keep dev data apart from the installed app
From review of the main process: - The debugging port stays closed whenever the data folder is the default one, also when CONSOLE_EDITOR_USER_DATA names it (links and relative paths resolved), not only when the variable is unset. - CONSOLE_EDITOR_USER_DATA may be relative; it used to crash at startup. - A URL handed over by a second launch while the app is still starting replaces the one it was about to open, instead of being overwritten by it (new e2e test, which fails without the fix). On macOS, URLs sent to the running app arrive as open-url and take the same path. - Runs from source use a separate 'Console Editor (dev)' data folder, so npm run dev works while an installed copy is open and never touches its overrides or logins.
1 parent 319989a commit a5fe254

5 files changed

Lines changed: 69 additions & 16 deletions

File tree

‎CONTRIBUTING.md‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -22,7 +22,7 @@ npm run dev # the app, with hot reload
2222
npm run demo-site # in another terminal: pages to try it on (port 5174)
2323
```
2424

25-
Node.js 22.18 or newer is required. On Linux as root (containers), start Electron without its sandbox: `npm run dev -- --noSandbox`.
25+
Node.js 22.18 or newer is required. Runs from source keep their data in a `Console Editor (dev)` folder, apart from an installed copy's, so both can run at once. On Linux as root (containers), start Electron without its sandbox: `npm run dev -- --noSandbox`.
2626

2727
## Before opening a pull request
2828

‎README.md‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -114,7 +114,7 @@ Type a URL in the preview's address bar (`https://…` or `localhost:3000`), pic
114114
| `http://127.0.0.1:5174/` | Files built to be awkward: gzip, SRI, a hashed bundle, source maps |
115115
| `http://127.0.0.1:5174/frames.html` | Cross-site and nested iframes |
116116

117-
To open a URL on start, pass it to the app (`console-editor https://example.com` after installing the Linux package) or set `CONSOLE_EDITOR_URL`: `CONSOLE_EDITOR_URL=https://example.com npm run dev`. Launching the app again while it runs opens the URL in the existing window.
117+
To open a URL on start, pass it to the app (`console-editor https://example.com` after installing the Linux package) or set `CONSOLE_EDITOR_URL`: `CONSOLE_EDITOR_URL=https://example.com npm run dev`. On Linux and Windows, starting the app again with a URL opens it in the window that's already running.
118118

119119
<details>
120120
<summary><b>Keyboard shortcuts</b></summary>
@@ -187,7 +187,7 @@ Everything stays on your machine: no telemetry, no uploads.
187187
| Open tabs, unsaved drafts, last page | `session/` |
188188
| The site's cookies, logins, storage | A persistent browser profile used only by the site view |
189189

190-
The data folder is `~/.config/Console Editor` on Linux, `~/Library/Application Support/Console Editor` on macOS and `%APPDATA%\Console Editor` on Windows. Uninstalling the app keeps it. Set `CONSOLE_EDITOR_USER_DATA` to use another one.
190+
The data folder is `~/.config/Console Editor` on Linux, `~/Library/Application Support/Console Editor` on macOS and `%APPDATA%\Console Editor` on Windows. Uninstalling the app keeps it. Running from source uses a separate `Console Editor (dev)` folder next to it, so a dev build never touches your real data. Set `CONSOLE_EDITOR_USER_DATA` to use another folder.
191191

192192
## Limitations
193193

‎docs/SPEC.md‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -245,8 +245,8 @@ Auto-attach uses `filter: [{type: 'iframe'}, {exclude: true}]` on every session;
245245
- A page's `beforeunload` guard cannot block reloads or navigation: editor-initiated reloads after a save must win, and Electron would cancel them without showing a dialog.
246246
- **Trade-off:** Chromium's Local Network Access checks are disabled for the whole app (feature switches are process-wide), because documents served through `Fetch.fulfillRequest` have no address space and would otherwise be blocked from reaching localhost/intranet hosts (§6.5). Any page opened in the app can therefore reach local-network addresses, as in Chrome before these checks shipped. Browse only sites you are working on.
247247
- Packaged builds flip Electron's fuses: `ELECTRON_RUN_AS_NODE`, `NODE_OPTIONS` and the `--inspect` switches are ignored, the app loads only from its `app.asar`, whose integrity is checked on macOS and Windows, and the site view's cookies are encrypted with the OS keystore (not yet on macOS: an ad-hoc signed app would be asked for the Keychain password after every update). `file://` keeps its extra privileges because the editor UI and its module workers load from it.
248-
- Packaged builds drop `--remote-debugging-port`/`--remote-debugging-pipe` unless `CONSOLE_EDITOR_USER_DATA` points elsewhere, as Chrome does for its default profile: otherwise any local program could start the app with a port and read the site view's logins.
249-
- One instance per data folder (`app.requestSingleInstanceLock`), so two processes never write the same overrides and session files. A second launch hands its URL to the running window and exits.
248+
- Packaged builds drop `--remote-debugging-port`/`--remote-debugging-pipe` when the data folder is the default one (compared after resolving links, so pointing `CONSOLE_EDITOR_USER_DATA` at it doesn't count as another), as Chrome does for its default profile: otherwise any local program could start the app with a port and read the site view's logins.
249+
- One instance per data folder (`app.requestSingleInstanceLock`), so two processes never write the same overrides and session files. A second launch hands its URL to the running window and exits; if the first is still starting, that URL replaces the one it was about to open. On macOS, where reopening the app starts no second process, URLs arrive as `open-url` and take the same path. Runs from source use a separate `… (dev)` data folder, so they never share one with an installed copy.
250250
- IPC inputs are type-checked; matchers are validated before storage; settings are filtered to known boolean keys.
251251
- The site sees a standard Chrome user agent (Electron tokens removed).
252252
- All data stays local: nothing is uploaded, and there are no telemetry or network calls besides the page and out-of-page fetches for the files you open.

‎src/main/index.ts‎

Lines changed: 45 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
import { app, BrowserWindow, dialog } from 'electron';
2-
import { join } from 'node:path';
2+
import { realpathSync } from 'node:fs';
3+
import { join, resolve } from 'node:path';
34
import appIcon from '../../build/icons/512x512.png?asset&asarUnpack';
45
import type { AppEvent } from '../shared/types';
56
import { APP_ID, REPO_URL } from './appInfo';
@@ -11,12 +12,31 @@ import { OverrideStore } from './store/OverrideStore';
1112
import { SessionStore } from './store/SessionStore';
1213
import { SettingsStore } from './store/SettingsStore';
1314

15+
// Runs from source (npm run dev, npm start) keep their data apart from an installed copy's, so the two can
16+
// run side by side and a dev build never touches your real overrides and logins.
17+
if (!app.isPackaged) app.setPath('userData', `${app.getPath('userData')} (dev)`);
18+
const defaultUserData = app.getPath('userData');
19+
1420
// Allow tests and power users to keep data elsewhere (e.g. a throwaway profile).
15-
if (process.env.CONSOLE_EDITOR_USER_DATA) app.setPath('userData', process.env.CONSOLE_EDITOR_USER_DATA);
21+
if (process.env.CONSOLE_EDITOR_USER_DATA) app.setPath('userData', resolve(process.env.CONSOLE_EDITOR_USER_DATA));
22+
23+
/** Whether two paths name the same folder (following links; case-insensitive where the file system usually is). */
24+
function sameFolder(a: string, b: string): boolean {
25+
const canonical = (path: string) => {
26+
let real: string;
27+
try {
28+
real = realpathSync.native(path);
29+
} catch {
30+
real = resolve(path);
31+
}
32+
return process.platform === 'linux' ? real : real.toLowerCase();
33+
};
34+
return canonical(a) === canonical(b);
35+
}
1636

1737
// As Chrome does, open no debugging port onto the real profile: any local program could start the app
1838
// with one and read the site view's logins. With a data folder of its own (tests) it still works.
19-
if (app.isPackaged && !process.env.CONSOLE_EDITOR_USER_DATA) {
39+
if (app.isPackaged && sameFolder(app.getPath('userData'), defaultUserData)) {
2040
app.commandLine.removeSwitch('remote-debugging-port');
2141
app.commandLine.removeSwitch('remote-debugging-pipe');
2242
}
@@ -37,6 +57,20 @@ const initialUrl = () => urlArgument(process.argv.slice(1)) ?? process.env.CONSO
3757

3858
/** The open window, for a second launch to hand over to. */
3959
let running: { win: BrowserWindow; page: PageController } | undefined;
60+
/** Set once the first page load has been chosen; a URL handed over before that replaces it. */
61+
let started = false;
62+
let handedUrl: string | undefined;
63+
64+
/** Brings the window forward and opens `url` in it: a second launch's URL, or one macOS sends. */
65+
function handOver(url: string | undefined): void {
66+
if (running && !running.win.isDestroyed()) {
67+
if (running.win.isMinimized()) running.win.restore();
68+
if (running.win.isVisible()) running.win.focus();
69+
}
70+
if (!url) return;
71+
if (started && running) void running.page.navigate(url);
72+
else handedUrl = url;
73+
}
4074

4175
async function createWindow(): Promise<void> {
4276
app.setAboutPanelOptions({
@@ -133,7 +167,8 @@ async function createWindow(): Promise<void> {
133167
}
134168

135169
await attached;
136-
const url = initialUrl() ?? session.get().url;
170+
const url = handedUrl ?? initialUrl() ?? session.get().url;
171+
started = true;
137172
if (url) void page.navigate(url);
138173
}
139174

@@ -143,13 +178,12 @@ if (!app.requestSingleInstanceLock()) {
143178
console.log(`Console Editor is already running with the data folder ${app.getPath('userData')}; switching to it.`);
144179
app.quit();
145180
} else {
146-
app.on('second-instance', (_event, argv) => {
147-
if (!running || running.win.isDestroyed()) return;
148-
const { win, page } = running;
149-
if (win.isMinimized()) win.restore();
150-
if (win.isVisible()) win.focus();
151-
const url = urlArgument(argv.slice(1));
152-
if (url) void page.navigate(url);
181+
app.on('second-instance', (_event, argv) => handOver(urlArgument(argv.slice(1))));
182+
// macOS starts no second process when the app is opened again (Finder, `open -a`): it sends the URL here.
183+
app.on('open-url', (event, url) => {
184+
if (!/^https?:\/\//i.test(url)) return;
185+
event.preventDefault();
186+
handOver(url);
153187
});
154188
app.whenReady().then(createWindow, (err) => {
155189
console.error(err);

‎test/e2e/app.e2e.test.ts‎

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -221,4 +221,23 @@ describe.skipIf(!built)('Console Editor app', () => {
221221
await expect.poll(() => inSite('location.pathname'), { timeout: 15_000 }).toBe('/frames.html');
222222
expect(await app.evaluate(({ BrowserWindow }) => BrowserWindow.getAllWindows().length)).toBe(1);
223223
});
224+
225+
it("a URL handed over while the app is still starting wins over the one it was starting with", async () => {
226+
const electronBinary = await app.evaluate(() => process.execPath);
227+
await app.close();
228+
// Not waiting for the window: the second launch arrives while the first is loading its stores and UI.
229+
app = await electron.launch({
230+
args: [...sandboxArgs, root],
231+
cwd: root,
232+
env: { ...process.env, CONSOLE_EDITOR_USER_DATA: userData, CONSOLE_EDITOR_URL: `${site.url}/store/` } as Record<string, string>,
233+
});
234+
await promisify(execFile)(electronBinary, [...sandboxArgs, root, `${site.url}/?from=second-launch`], {
235+
env: { ...process.env, CONSOLE_EDITOR_USER_DATA: userData },
236+
timeout: 20_000,
237+
});
238+
await expect.poll(() => inSite('location.search'), { timeout: 15_000 }).toBe('?from=second-launch');
239+
// And stays there: the startup URL doesn't replace it afterwards.
240+
await new Promise((r) => setTimeout(r, 2000));
241+
expect(await inSite('location.search')).toBe('?from=second-launch');
242+
});
224243
});

0 commit comments

Comments
 (0)