Open-source Grok Bot alternative with a virtual machine that bots can use
TypeScript ai-agentsclaude-codecodexcomputer-usedockerelectrongrokgrok-botgrok-bot-alternativeself-hostedtypescript
Hear the desktop app's private port through one dispatcher, so no start-time message is lost (#8243)
Milind Soni0e546223dc6a
diff --git a/server/browser/egress/registry.ts b/server/browser/egress/registry.tsindex 9c7030f856..0a64e7d9c5 100644--- a/server/browser/egress/registry.ts+++ b/server/browser/egress/registry.ts@@ -5,6 +5,7 @@ import type { Server } from "node:net";import { agentBrowserDevToolsPorts, agentBrowserStreamPorts } from "../../browser-engine.ts";import { sanitizePageText } from "../../browser-page-health.ts";import { FLEET_FIRST_PORT, FLEET_PORT_STRIDE } from "../../fleet.ts";+import { desktopParent } from "../../parent-port.ts";import { botEngineSessions } from "../../procs.ts";import { openGate, resolveTarget, type EgressGate, type GateTarget, type GateUpstream, type ResolvedAddress } from "./gate.ts";import { opensFromHome } from "./home-sites.ts";@@ -45,19 +46,11 @@ subscribe("tracing:net.server.listen:asyncEnd", (message) => {/** The desktop app's own listeners (the companion and its gateway, the client relay), sent each time they change over* Electron's private utility-process port; plain Node has none. */let reportedPorts = new Set<number>();-let hearingReports = false;--/** Attached only once the server's own receiver is: the port starts delivering, once, with its first listener. */-function hearDesktopReports(): void {- const parentPort = (process as NodeJS.Process & { parentPort?: { on(event: "message", listener: (event: { data?: unknown }) => void): void } }).parentPort;- if (hearingReports || !parentPort) return;- hearingReports = true;- parentPort.on("message", ({ data }) => {- const message = data as { type?: unknown; ports?: unknown } | undefined;- if (message?.type !== "openmausbot:own-listeners" || !Array.isArray(message.ports) || message.ports.length > 256) return;- reportedPorts = new Set(message.ports.filter(validPort));- });-}+desktopParent?.on("message", ({ data }) => {+ const message = data as { type?: unknown; ports?: unknown } | undefined;+ if (message?.type !== "openmausbot:own-listeners" || !Array.isArray(message.ports) || message.ports.length > 256) return;+ reportedPorts = new Set(message.ports.filter(validPort));+});export class OwnListeners {private readonly fixed: Set<number>;@@ -118,7 +111,6 @@ export class BrowserEgress {private readonly toldAway = new Map<string, { kind: "away" | "unshared"; text: string }>();configure(setup: EgressSetup): void {- hearDesktopReports();this.setup = {...setup,listeners: setup.listeners ?? new OwnListeners(setup.host),diff --git a/server/browser/pane/link.ts b/server/browser/pane/link.tsindex 6173de28fe..a668e6521f 100644--- a/server/browser/pane/link.ts+++ b/server/browser/pane/link.ts@@ -1,9 +1,10 @@// The server's end of the desktop app's pane messages: one PaneEndpoint per profile the main process shows natively.import { PANE_MESSAGE, paneMessageToServer, type CookieImportResult, type CookieSource, type PaneCookie, type PaneToMain, type PaneToServer } from "../../../electron/browser-pane-wire.mjs";+import { desktopParent } from "../../parent-port.ts";import type { Params } from "../cdp/connection.ts";import { PaneEndpoint, type PaneChannel, type PaneEndpointOptions, type PaneTab } from "./endpoint.ts";-/** Electron's utility-process parent port: only the desktop main process can post on it. */+/** The desktop app's private port (server/parent-port.ts): only the desktop main process can post on it. */export interface PanePort {on(event: "message", listener: (event: { data?: unknown }) => void): void;postMessage(message: object): void;@@ -299,6 +300,5 @@ export class PaneLink {/** The desktop app's link, on the server it starts as a utility process; null anywhere else. */export function desktopPaneLink(managed: boolean): PaneLink | null {- const port = (process as NodeJS.Process & { parentPort?: PanePort }).parentPort;- return managed && port ? new PaneLink(port) : null;+ return managed && desktopParent ? new PaneLink(desktopParent) : null;}diff --git a/server/index.ts b/server/index.tsindex 800c382d07..55be037b28 100644--- a/server/index.ts+++ b/server/index.ts@@ -192,7 +192,7 @@ import { createTraceRecorder } from "./usage-trace/recorder.ts";import { GroupUsageReader } from "./group-thread-usage.ts";import { ledgerCost } from "./model-prices.ts";import type { PriceList } from "./prices.ts";-import type { RequestAuth } from "./request-auth.ts";+import type { RequestAuth } from "./request-auth.ts"; import { desktopParent } from "./parent-port.ts";import { adminAuditPlan, type AuditPlan } from "./admin-audit-plan.ts"; import { departmentGrants, type DepartmentGrant } from "./department-grants.ts";import { onKeyRejectionChange } from "./key-rejections.ts";import { assertWithinBudget, noteSpend, spendAlertText, spendState, takeSpendAlert } from "./spend.ts"; import { personWaiting, personWaitingInRoom, type ThreadStanding } from "./usage-caps.ts"; import { createUsageCapGate, USAGE_CAP_CODE } from "./host/usage-cap-gate.ts"; import { createUsageCapRoutes } from "./routes/usage-caps.ts";@@ -1399,12 +1399,8 @@ const bundledSkills = loadBundledSkills();const availableSkills = () => mergeSkills(bundledSkills, loadUserSkills(join(DATA_DIR, "skills")));const HAS_USB_PORT = !CLOUD_HOME && !HOSTED_WORKSPACE, usbPhoneTakeoverOn = () => HAS_USB_PORT && usbPhoneTakeoverEnabled(cfg); // A Cloud home or a hosted workspace has no USB port.-type UtilityParentPort = {- on(event: "message", listener: (event: { data?: object }) => void): void;- postMessage(message: object): void;-};-// Only Electron's utility process supplies parentPort, private to the desktop main process; plain Node leaves it absent.-const utilityParentPort = (process as NodeJS.Process & { parentPort?: UtilityParentPort }).parentPort; const linkLimits = createLinkLimits({ cloud: () => Boolean(CLOUD_HOME) || botLink.link.role() === "acceptor", node: (id) => coordinator.node(id), confinable: (bot) => registry.get(store.bot(bot.id)?.modelSelection.instanceId ?? "")?.adapter.capabilities.guestTurns === "confined" });+// The desktop app's private port, heard only through its one dispatcher (parent-port.ts); plain Node leaves it absent.+const utilityParentPort = desktopParent; const linkLimits = createLinkLimits({ cloud: () => Boolean(CLOUD_HOME) || botLink.link.role() === "acceptor", node: (id) => coordinator.node(id), confinable: (bot) => registry.get(store.bot(bot.id)?.modelSelection.instanceId ?? "")?.adapter.capabilities.guestTurns === "confined" });type DesktopPrivateMessage = BrowserCleanupWireRequest | import("./login-handoff.ts").LoginHandoffResult | {type: "openmausbot:browser-control";botId: string;@@ -1472,7 +1468,7 @@ const browserCleanup: BrowserCleanupCoordinator = new BrowserCleanupCoordinator(const phoneSecrets = new PhoneSecretBridge(postDesktopPrivateMessage, undefined, undefined, DESKTOP_MANAGED); const phonePushAccess = new PhonePushAccessSource({ tunnelFile: join(DATA_DIR, TUNNEL_CREDENTIALS_FILE), defaultControlPlane: DEFAULT_COMPANION_CONTROL_PLANE_URL, cloudHome: CLOUD_HOME });const boatSignInHost = createBoatSignInHost({ desktop: DESKTOP_MANAGED, hosted: Boolean(CLOUD_HOME) || HOSTED_WORKSPACE, port: PORT, dataDir: DATA_DIR, cfg, refresh: () => { Object.assign(cfg, loadConfig()); broadcast({ kind: "config", ...configStatus() }); }, managedBoatOwners: () => managedBoatOwners(), operationConflict: () => providerOperationConflict("box"), transitions: { add: (provider) => computerProviderConfigTransitions.add(provider), delete: (provider) => computerProviderConfigTransitions.delete(provider), has: (provider) => computerProviderConfigTransitions.has(provider) }, post: (message) => postDesktopPrivateMessage(message as unknown as DesktopPrivateMessage) }); Object.assign(cfg, loadConfig()); ROUTES.push(boatSignInHost.routes);utilityParentPort?.on("message", (event) => {- const message = event?.data;+ const message = event?.data as object | undefined;try {if (applyDesktopMutationTokenMessage(message) || desktopComputer.receive(message) || tailnetShare.receive(message, (answer) => utilityParentPort?.postMessage(answer))) return;if (handleDesktopTrustedApprovalMessage(message) || linkLimits.receive(message)) return;@@ -15020,7 +15016,7 @@ if (CLOUD_HOME) registerCloudPower(cloudPower = createCloudPower({ dataDir: DATAbotLink.start(); let pausedSent = starterAwake.paused().join(); store.onChange((change) => { if (change.type === "bot.deleted") botHolds.forget("bot", change.botId); if (change.type !== "bot" && change.type !== "bot.deleted") return; const paused = starterAwake.paused().join(); if (paused !== pausedSent) { pausedSent = paused; broadcast({ kind: "config", ...configStatus() }); } });server.listen(PORT, listenHost(server), async () => {- companyRuntimeReady(); cloudHealth?.speed.ready(); signInTrace?.recover(); void tailnetShare.start(process.env);+ utilityParentPort?.seal(); companyRuntimeReady(); cloudHealth?.speed.ready(); signInTrace?.recover(); void tailnetShare.start(process.env);console.log(`openmausbot server on http://127.0.0.1:${PORT}`); launchListening();personWaits.boot(); handoffRequests.boot(); browserSweep.start(); startCloudTeamPolicy({ cloudHome: CLOUD_HOME, dataDir: DATA_DIR, managed: managedPolicy, sessions }); startCloudTeamRoster({ cloudHome: CLOUD_HOME, sessions }); moveFreeze.hold(() => appTriggers.start(), () => void appTriggers.stop()); startCloudHomeConnectedApps({ cloudHome: CLOUD_HOME !== null, dataDir: DATA_DIR, cloudGrant: CLOUD_ENV.OMB_CLOUD_CONNECTED_APPS_GRANT, ownKey: () => composio.connectionMode(cfg) === "self-hosted", apply: (access) => { composio.setManagedBrokerAccess(access); broadcast({ kind: "config", ...configStatus() }); } });void afterFirstEngineRead().then(() => { if (builtInBrowserEnabled(cfg)) chromeLauncher.start(); checkpointSeeds.start(); });diff --git a/server/parent-port.e2e.test.ts b/server/parent-port.e2e.test.tsnew file mode 100644index 0000000000..f6ddd1c344--- /dev/null+++ b/server/parent-port.e2e.test.ts@@ -0,0 +1,34 @@+// The real server, started as the desktop app starts it, behind a parent port that delivers as Electron's does: what the+// app posted while the server was starting is handed over once, to the listeners attached by then+// (server/testing/desktop-parent.mjs). The app's owner capability is such a message, and its own window is turned away+// to the pairing screen if the server never hears it.+import { randomBytes } from "node:crypto";+import { afterAll, beforeAll, expect, it } from "vitest";+import { launchVerificationServer } from "../scripts/control-omb.ts";++const owner = randomBytes(32).toString("base64url");+const realFetch = globalThis.fetch;+let fixture: Awaited<ReturnType<typeof launchVerificationServer>>;++beforeAll(async () => {+ // The launcher's own first requests are the app's, so they carry its capability, as its window's do.+ globalThis.fetch = (input, init = {}) => realFetch(input, { ...init, headers: { ...Object.fromEntries(new Headers(init.headers)), "x-openmausbot-desktop-owner": owner } });+ fixture = await launchVerificationServer({ ...process.env, OMB_TEST_DESKTOP_OWNER_TOKEN: owner });+}, 90_000);+afterAll(async () => {+ globalThis.fetch = realFetch;+ await fixture?.close();+});++it("hears the owner capability the app posted before the server's own receiver was attached", async () => {+ const { bots } = await (await realFetch(`${fixture.info.url}/api/bots?messages=0`)).json() as { bots: Array<{ id: string }> };+ const rename = (name: string, capability?: string) => realFetch(`${fixture.info.url}/api/bots/${bots[0].id}/profile`, {+ method: "PATCH",+ headers: { "content-type": "application/json", origin: fixture.info.url, ...(capability ? { "x-openmausbot-desktop-owner": capability } : {}) },+ body: JSON.stringify({ name }),+ });+ // Posted once, as the server starts, and never again here: only its arrival lets the app's own window make a change.+ expect((await rename("Heard", owner)).status).toBe(200);+ expect((await rename("No capability")).status).toBe(403);+ expect((await rename("Another capability", randomBytes(32).toString("base64url"))).status).toBe(403);+}, 60_000);diff --git a/server/parent-port.test.ts b/server/parent-port.test.tsnew file mode 100644index 0000000000..4ea705d16e--- /dev/null+++ b/server/parent-port.test.ts@@ -0,0 +1,193 @@+import { readdirSync, readFileSync } from "node:fs";+import { join, relative, sep } from "node:path";+import { fileURLToPath } from "node:url";+import { describe, expect, it, vi } from "vitest";++import { createParentDispatcher, desktopParent, type ParentMessageListener } from "./parent-port.ts";++/** A port that delivers as the desktop app's does: what was posted is held until the first listener is attached, then+ * handed over a turn later, once, to the listeners attached by then. */+function appPort() {+ const listeners: ParentMessageListener[] = [];+ const held: unknown[] = [];+ const sent: object[] = [];+ let started = false;+ let turn: (() => void) | null = null;+ const deliver = (data: unknown) => { for (const listener of listeners.slice()) listener({ data }); };+ return {+ port: {+ on(_event: "message", listener: ParentMessageListener) {+ listeners.push(listener);+ if (started) return;+ started = true;+ turn = () => { for (const data of held.splice(0)) deliver(data); };+ },+ postMessage(message: object) { sent.push(message); },+ },+ sent,+ /** The app posts. */+ post(data: unknown) { if (turn === null && started) deliver(data); else held.push(data); },+ /** The turn after the first listener: the held messages arrive. */+ turn() { turn?.(); turn = null; },+ };+}++/** Deferred work, run when the test says the registering code has run on. */+function deferred() {+ const waiting: Array<() => void> = [];+ return { defer: (work: () => void) => { waiting.push(work); }, run() { for (const work of waiting.splice(0)) work(); } };+}++const TOKEN = { type: "openmausbot:desktop-mutation-token", token: "t" };+const KEY = { type: "openmausbot:phone-secret-key" };++describe("the desktop app's private port", () => {+ it("loses what the app posted at start for a receiver that listens on the port itself, after another did", () => {+ const app = appPort();+ app.post(TOKEN);+ const early: unknown[] = [];+ const late: unknown[] = [];+ app.port.on("message", ({ data }) => early.push(data)); // a module that listens as it is imported+ app.turn(); // the server's start waits on something+ app.port.on("message", ({ data }) => late.push(data)); // the server's own receiver+ expect(early).toEqual([TOKEN]);+ expect(late).toEqual([]);+ });++ it("hands every receiver what the app posted at start, whenever it registers", () => {+ const app = appPort();+ const later = deferred();+ app.post(TOKEN);+ app.post(KEY);+ const parent = createParentDispatcher(app.port, { defer: later.defer });+ const early: unknown[] = [];+ const late: unknown[] = [];+ parent.on("message", ({ data }) => early.push(data));+ app.turn();+ later.run();+ parent.on("message", ({ data }) => late.push(data));+ later.run();+ app.post({ type: "after" });+ expect(early).toEqual([TOKEN, KEY, { type: "after" }]);+ expect(late).toEqual([TOKEN, KEY, { type: "after" }]);+ });++ it("never runs a receiver inside the call that registers it", () => {+ const app = appPort();+ const later = deferred();+ const parent = createParentDispatcher(app.port, { defer: later.defer });+ app.post(TOKEN);+ app.turn();+ const heard: unknown[] = [];+ parent.on("message", ({ data }) => heard.push(data));+ expect(heard).toEqual([]);+ later.run();+ expect(heard).toEqual([TOKEN]);+ });++ it("keeps arrival order when a message arrives before the earlier ones were handed over", () => {+ const app = appPort();+ const later = deferred();+ const parent = createParentDispatcher(app.port, { defer: later.defer });+ app.post(TOKEN);+ app.turn();+ const heard: unknown[] = [];+ parent.on("message", ({ data }) => heard.push(data));+ app.post(KEY);+ expect(heard).toEqual([]);+ later.run();+ app.post({ type: "after" });+ expect(heard).toEqual([TOKEN, KEY, { type: "after" }]);+ });++ it("lets no receiver consume or drop a message meant for another", () => {+ const app = appPort();+ const later = deferred();+ const parent = createParentDispatcher(app.port, { defer: later.defer });+ const failed = vi.spyOn(console, "error").mockImplementation(() => {});+ try {+ const heard: unknown[] = [];+ parent.on("message", () => { throw new Error("not mine"); });+ parent.on("message", ({ data }) => heard.push(data));+ app.post(TOKEN);+ app.turn();+ later.run();+ app.post(KEY);+ expect(heard).toEqual([TOKEN, KEY]);+ expect(failed).toHaveBeenCalledTimes(2);+ } finally {+ failed.mockRestore();+ }+ });++ it("keeps nothing once startup is over, and a later receiver hears only what follows", () => {+ const app = appPort();+ const later = deferred();+ const parent = createParentDispatcher(app.port, { defer: later.defer });+ const before: unknown[] = [];+ parent.on("message", ({ data }) => before.push(data));+ app.post(TOKEN);+ app.turn();+ parent.seal();+ later.run();+ const after: unknown[] = [];+ parent.on("message", ({ data }) => after.push(data));+ later.run();+ app.post(KEY);+ expect(before).toEqual([TOKEN, KEY]);+ expect(after).toEqual([KEY]);+ });++ it("stops keeping messages at its limit, for a process that never says startup is over", () => {+ const app = appPort();+ const later = deferred();+ const parent = createParentDispatcher(app.port, { defer: later.defer, limit: 3 });+ parent.on("message", () => {});+ app.turn();+ for (let n = 0; n < 5; n++) app.post({ n });+ const heard: unknown[] = [];+ parent.on("message", ({ data }) => heard.push(data));+ later.run();+ app.post({ n: 5 });+ expect(heard).toEqual([{ n: 5 }]);+ });++ it("posts to the app through the same port", () => {+ const app = appPort();+ createParentDispatcher(app.port).postMessage({ type: "answer" });+ expect(app.sent).toEqual([{ type: "answer" }]);+ });++ it("is absent under plain Node, where there is no app", () => {+ expect(desktopParent).toBeUndefined();+ });+});++// A second listener on the port itself can be attached after the port started delivering, and then misses what the app+// posted at start. Every receiver registers with parent-port.ts instead; these files name a worker thread's port, which+// is another thing.+const WORKER_THREAD_PORTS = new Set(["server/text-changes.worker.ts", "server/message-search.worker.ts", "server/workspace-backup.worker.ts", "server/host/transcript-mentions.ts"]);++describe("listening on the desktop app's port", () => {+ it("happens only in parent-port.ts", () => {+ const root = fileURLToPath(new URL("..", import.meta.url));+ const offenders: string[] = [];+ const seen = new Set<string>();+ const walk = (dir: string) => {+ for (const entry of readdirSync(dir, { withFileTypes: true })) {+ const path = join(dir, entry.name);+ if (entry.isDirectory()) { if (entry.name !== "node_modules") walk(path); continue; }+ if (!/\.(?:ts|mts|cts|mjs|cjs|js)$/.test(entry.name) || /\.test\.[a-z]+$/.test(entry.name)) continue;+ const name = relative(root, path).split(sep).join("/");+ if (name === "server/parent-port.ts" || name.startsWith("server/testing/")) continue;+ if (!/\bparentPort\b/.test(readFileSync(path, "utf8"))) continue;+ seen.add(name);+ if (!WORKER_THREAD_PORTS.has(name)) offenders.push(name);+ }+ };+ walk(join(root, "server"));+ expect(offenders, "register with desktopParent (server/parent-port.ts) instead of naming process.parentPort").toEqual([]);+ // A file that no longer names a port leaves the list, so the list never excuses a new one by an old name.+ expect([...WORKER_THREAD_PORTS].filter((name) => !seen.has(name))).toEqual([]);+ });+});diff --git a/server/parent-port.ts b/server/parent-port.tsnew file mode 100644index 0000000000..4c08f3d4ff--- /dev/null+++ b/server/parent-port.ts@@ -0,0 +1,74 @@+// The desktop app's private port to this server, and the only place in the server that listens on it.+//+// Electron's utility-process port holds what the app posted until its first listener is attached, then delivers it+// once, to whoever listens at that moment. A receiver that attaches later never sees those messages: the app's owner+// capability, posted as the server starts, was lost that way whenever a module listening at import ran ahead of the+// server's own receiver. So one listener is attached here, as this module loads, and every receiver registers with it+// instead. Each receiver is handed every message in arrival order, including the ones that arrived before it+// registered, and none can consume or drop a message meant for another.+//+// Plain Node (`openmausbot serve`, a Cloud home) has no such port: `desktopParent` is undefined and nothing is kept.++export type ParentMessageEvent = { data?: unknown };+export type ParentMessageListener = (event: ParentMessageEvent) => void;+export interface ParentPortLike {+ on(event: "message", listener: ParentMessageListener): void;+ postMessage(message: object): void;+}+export interface DesktopParent extends ParentPortLike {+ /** Startup is over: receivers that register from now on hear only what arrives after them, and nothing is kept. */+ seal(): void;+}++/** A sealed backlog is the normal state; this only bounds a process that never says its startup is over. */+export const PARENT_BACKLOG_LIMIT = 1024;++type Receiver = { listener: ParentMessageListener; waiting: ParentMessageEvent[] | null };++export function createParentDispatcher(port: ParentPortLike, options: { defer?: (work: () => void) => void; limit?: number } = {}): DesktopParent {+ const defer = options.defer ?? ((work) => void setImmediate(work));+ const limit = options.limit ?? PARENT_BACKLOG_LIMIT;+ const receivers: Receiver[] = [];+ let backlog: ParentMessageEvent[] | null = [];++ const hand = (receiver: Receiver, event: ParentMessageEvent) => {+ try {+ receiver.listener(event);+ } catch (error) {+ console.error(`[desktop-sync] a private parent message receiver failed: ${error instanceof Error ? error.message : String(error)}`);+ }+ };++ port.on("message", (event) => {+ if (backlog && backlog.push(event) >= limit) backlog = null;+ // A snapshot: a receiver registered by another's handling starts with the backlog, which already holds this one.+ for (const receiver of receivers.slice()) {+ if (receiver.waiting) receiver.waiting.push(event);+ else hand(receiver, event);+ }+ });++ return {+ on(event, listener) {+ if (event !== "message") return;+ const receiver: Receiver = { listener, waiting: backlog ? [...backlog] : [] };+ receivers.push(receiver);+ // Never inside the registering call: a receiver registered part-way through a module would run before the+ // values declared after it exist. Earlier messages reach it once the registering code has run on, as the+ // port's own delivery does.+ defer(() => {+ const waiting = receiver.waiting ?? [];+ // Emptied in place, so a message that arrives while these are handled still follows them.+ while (waiting.length) hand(receiver, waiting.shift()!);+ receiver.waiting = null;+ });+ },+ postMessage(message) { port.postMessage(message); },+ seal() { backlog = null; },+ };+}++const port = (process as NodeJS.Process & { parentPort?: ParentPortLike }).parentPort;++/** Only Electron's utility process supplies the port, private to the desktop main process; plain Node leaves it absent. */+export const desktopParent: DesktopParent | undefined = port ? createParentDispatcher(port) : undefined;diff --git a/server/places/place-proxy.ts b/server/places/place-proxy.tsindex 87cd90f20c..6a5158c9bb 100644--- a/server/places/place-proxy.ts+++ b/server/places/place-proxy.ts@@ -16,6 +16,7 @@ import { timingSafeEqual } from "node:crypto";import type { ServerResponse } from "node:http";import { intoPlace, isPlaceId, outOfPlace, ownId, PLACE_FILE_PREFIX, PLACE_KEY } from "../../shared/place-ids.ts";+import { desktopParent } from "../parent-port.ts";import { fromOwnPage } from "../request-auth.ts";import { userError, type UserErrorKey } from "../user-errors.ts";import { PASS, type RouteContext, type RouteHandler } from "../routes/pass.ts";@@ -450,7 +451,7 @@ export function listenPlacePort(port: Port | undefined, proxy: PlaceProxy = placif (record(message) && message.type === "openmausbot:desktop-mutation-token" && typeof message.token === "string") proxy.setOwnerToken(message.token);});}-listenPlacePort((process as NodeJS.Process & { parentPort?: Port }).parentPort);+listenPlacePort(desktopParent);export const placeProxyRoutes: RouteHandler = (ctx) => placeProxy.route(ctx);diff --git a/server/testing/desktop-parent.mjs b/server/testing/desktop-parent.mjsindex 1caa27330e..fa912705b9 100644--- a/server/testing/desktop-parent.mjs+++ b/server/testing/desktop-parent.mjs@@ -26,6 +26,7 @@ const cuaGrant = () => {if (token || cuaFile) {const listeners = [];+ let started = false;if (cuaFile) {watchFile(cuaFile, { interval: 25, persistent: false }, () => {const grant = cuaGrant();@@ -38,10 +39,19 @@ if (token || cuaFile) {on(event, listener) {if (event !== "message") return;listeners.push(listener);- if (token) queueMicrotask(() => listener({ data: { type: "openmausbot:desktop-mutation-token", token } }));- if (pages) queueMicrotask(() => listener({ data: { type: "openmausbot:included-pages", access: JSON.parse(pages) } }));- if (cuaFile) queueMicrotask(() => listener({ data: cuaGrant() }));- if (tailnetShare) queueMicrotask(() => listener({ data: { type: "openmausbot:tailnet-share", share: JSON.parse(tailnetShare) } }));+ if (started) return;+ started = true;+ // As Electron's port does: what the app posted while the server started is delivered once, a turn after the+ // first listener is attached, to the listeners there are by then. One attached later never sees it.+ setImmediate(() => {+ const queued = [];+ if (token) queued.push({ type: "openmausbot:desktop-mutation-token", token });+ if (pages) queued.push({ type: "openmausbot:included-pages", access: JSON.parse(pages) });+ if (cuaFile) queued.push(cuaGrant());+ if (tailnetShare) queued.push({ type: "openmausbot:tailnet-share", share: JSON.parse(tailnetShare) });+ const present = [...listeners];+ for (const data of queued) for (const hear of present) hear({ data });+ });},postMessage() {},},