Skip to content

Commit 8b816f8

Browse files
committed
fix(desktop): queue pairing links so a loading renderer cannot drop them
Review found three ways a one-time pairing link could be lost: two links arriving before the renderer was ready overwrote each other in a single slot; a macOS open-url at cold start could fire before the service's listener existed; and readiness stayed true across a renderer reload, so a link pushed at did-finish-load landed before the new coordinator subscribed. Replace push with pull. The main process appends every link to a queue and only pings the renderer that something is waiting. The renderer drains the queue on mount and on each ping, so a reload picks up whatever arrived while it was away. A tiny pre-ready layer installs the open-url listener alongside the other synchronous Electron setup and buffers URLs until the service subscribes.
1 parent 43456e2 commit 8b816f8

14 files changed

Lines changed: 199 additions & 94 deletions

‎apps/desktop/src/app/DesktopLifecycle.test.ts‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -96,7 +96,7 @@ function makeDesktopWindowLayer(
9696
prepareCaptureReveal: Effect.void,
9797
dispatchMenuAction: () => Effect.void,
9898
dispatchSnapShotEvent: () => Effect.void,
99-
dispatchPairingLink: () => Effect.void,
99+
dispatchPairingLinkAvailable: Effect.void,
100100
zoomMain: () => Effect.void,
101101
syncAppearance: Effect.void,
102102
});

‎apps/desktop/src/app/DesktopPairingLink.test.ts‎

Lines changed: 94 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,24 @@
1-
import { describe, expect, it } from "vite-plus/test";
1+
import { assert, it as effectIt } from "@effect/vitest";
2+
import * as Effect from "effect/Effect";
3+
import * as Layer from "effect/Layer";
4+
import { describe, expect, it, vi } from "vite-plus/test";
25

3-
import { extractPairingLink } from "./DesktopPairingLink.ts";
6+
import * as ElectronApp from "../electron/ElectronApp.ts";
7+
import * as DesktopWindow from "../window/DesktopWindow.ts";
8+
import * as DesktopEnvironment from "./DesktopEnvironment.ts";
9+
10+
const { appOnMock } = vi.hoisted(() => ({ appOnMock: vi.fn() }));
11+
12+
vi.mock("electron", () => ({ app: { on: appOnMock } }));
13+
14+
import * as DesktopPairingLink from "./DesktopPairingLink.ts";
415

516
const link = "t3code://pair?host=https%3A%2F%2Fbackend.example.com&label=Work#token=ABCD1234";
17+
const otherLink = "t3code://pair?host=https%3A%2F%2Fother.example.com#token=WXYZ5678";
618

719
describe("extractPairingLink", () => {
20+
const { extractPairingLink } = DesktopPairingLink;
21+
822
it("finds the pairing link among launcher argv noise", () => {
923
expect(
1024
extractPairingLink(["/usr/bin/t3code", "--no-sandbox", link, "--foo=bar"], "t3code"),
@@ -42,3 +56,81 @@ describe("extractPairingLink", () => {
4256
expect(extractPairingLink(["t3code:", "t3code://", link], "t3code")).toBe(link);
4357
});
4458
});
59+
60+
/** Builds the service against a fake Electron app whose open-url emitter we drive by hand. */
61+
const makeScenario = () => {
62+
appOnMock.mockReset();
63+
const listeners = new Map<string, (...args: Array<unknown>) => void>();
64+
appOnMock.mockImplementation((eventName: string, listener: (...args: Array<unknown>) => void) => {
65+
listeners.set(eventName, listener);
66+
});
67+
const availableNotices = { count: 0 };
68+
const electronApp = {
69+
on: (eventName: string, listener: (...args: Array<unknown>) => void) =>
70+
Effect.sync(() => {
71+
listeners.set(eventName, listener);
72+
}),
73+
} as unknown as ElectronApp.ElectronApp["Service"];
74+
const desktopWindow = {
75+
dispatchPairingLinkAvailable: Effect.sync(() => {
76+
availableNotices.count += 1;
77+
}),
78+
} as unknown as DesktopWindow.DesktopWindow["Service"];
79+
const environment = {
80+
isDevelopment: false,
81+
} as unknown as DesktopEnvironment.DesktopEnvironment["Service"];
82+
// Build the pre-ready open-url buffer first, as main.ts does, so the emitter
83+
// exists before the service.
84+
const layer = DesktopPairingLink.layer.pipe(
85+
Layer.provideMerge(DesktopPairingLink.layerOpenUrls),
86+
Layer.provide(Layer.succeed(ElectronApp.ElectronApp, electronApp)),
87+
Layer.provide(Layer.succeed(DesktopWindow.DesktopWindow, desktopWindow)),
88+
Layer.provide(Layer.succeed(DesktopEnvironment.DesktopEnvironment, environment)),
89+
);
90+
const emit = (eventName: string, ...args: Array<unknown>) => {
91+
listeners.get(eventName)?.({}, ...args);
92+
};
93+
return { layer, emit, availableNotices };
94+
};
95+
96+
/** The service notifies the renderer via a fire-and-forget promise; let it settle. */
97+
const settle = Effect.promise(() => new Promise<void>((resolve) => queueMicrotask(resolve)));
98+
99+
describe("DesktopPairingLink", () => {
100+
effectIt.effect("queues links in arrival order and hands them out once", () => {
101+
const scenario = makeScenario();
102+
return Effect.scoped(
103+
Effect.gen(function* () {
104+
const pairingLink = yield* DesktopPairingLink.DesktopPairingLink;
105+
yield* pairingLink.register;
106+
107+
scenario.emit("open-url", link);
108+
scenario.emit("second-instance", ["/usr/bin/t3code", otherLink], "/");
109+
scenario.emit("open-url", "t3code://app/");
110+
yield* settle;
111+
112+
assert.deepEqual(yield* pairingLink.takePending, [link, otherLink]);
113+
assert.deepEqual(yield* pairingLink.takePending, []);
114+
assert.equal(scenario.availableNotices.count, 2);
115+
}),
116+
).pipe(Effect.provide(scenario.layer));
117+
});
118+
119+
effectIt.effect("keeps an open-url that fires before the service registers", () => {
120+
const scenario = makeScenario();
121+
return Effect.scoped(
122+
Effect.gen(function* () {
123+
// The Electron listener exists as soon as the layer is built.
124+
scenario.emit("open-url", link);
125+
126+
const pairingLink = yield* DesktopPairingLink.DesktopPairingLink;
127+
assert.deepEqual(yield* pairingLink.takePending, []);
128+
129+
yield* pairingLink.register;
130+
yield* settle;
131+
132+
assert.deepEqual(yield* pairingLink.takePending, [link]);
133+
}),
134+
).pipe(Effect.provide(scenario.layer));
135+
});
136+
});

‎apps/desktop/src/app/DesktopPairingLink.ts‎

Lines changed: 55 additions & 42 deletions
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,10 @@
11
import * as Context from "effect/Context";
22
import * as Effect from "effect/Effect";
33
import * as Layer from "effect/Layer";
4-
import * as Option from "effect/Option";
54
import * as Ref from "effect/Ref";
65
import * as Scope from "effect/Scope";
76

8-
import type * as Electron from "electron";
7+
import * as Electron from "electron";
98

109
import * as ElectronApp from "../electron/ElectronApp.ts";
1110
import * as ElectronProtocol from "../electron/ElectronProtocol.ts";
@@ -41,19 +40,52 @@ export function extractPairingLink(
4140
return null;
4241
}
4342

43+
/**
44+
* macOS delivers a cold-start URL through `open-url` moments after launch,
45+
* before async startup reaches `DesktopPairingLink.register`. This listener is
46+
* installed with the synchronous pre-ready setup and holds URLs until the
47+
* service subscribes.
48+
*/
49+
export class DesktopOpenUrls extends Context.Service<
50+
DesktopOpenUrls,
51+
{
52+
readonly subscribe: (listener: (url: string) => void) => Effect.Effect<void>;
53+
}
54+
>()("@t3tools/desktop/app/DesktopPairingLink/DesktopOpenUrls") {}
55+
56+
export const layerOpenUrls = Layer.effect(
57+
DesktopOpenUrls,
58+
Effect.sync(() => {
59+
const buffered: Array<string> = [];
60+
let subscriber: ((url: string) => void) | null = null;
61+
Electron.app.on("open-url", (_event, url) => {
62+
if (subscriber === null) {
63+
buffered.push(url);
64+
return;
65+
}
66+
subscriber(url);
67+
});
68+
return DesktopOpenUrls.of({
69+
subscribe: (listener) =>
70+
Effect.sync(() => {
71+
subscriber = listener;
72+
for (const url of buffered.splice(0)) listener(url);
73+
}),
74+
});
75+
}),
76+
);
77+
4478
export class DesktopPairingLink extends Context.Service<
4579
DesktopPairingLink,
4680
{
47-
/**
48-
* Start listening for pairing deep links. Registers before `ready` so a
49-
* macOS `open-url` delivered at cold start is not missed.
50-
*/
81+
/** Start collecting pairing deep links from the OS. */
5182
readonly register: Effect.Effect<void, never, Scope.Scope>;
5283
/**
53-
* The renderer signals when its coordinator is mounted; a link that
54-
* arrived earlier (cold start) is delivered then.
84+
* Hand every queued link to the renderer, oldest first. Links only leave
85+
* the queue this way, so a renderer that is reloading or not yet mounted
86+
* cannot lose one; it drains the queue when its coordinator mounts.
5587
*/
56-
readonly setRendererReady: (ready: boolean) => Effect.Effect<void>;
88+
readonly takePending: Effect.Effect<ReadonlyArray<string>>;
5789
}
5890
>()("@t3tools/desktop/app/DesktopPairingLink") {}
5991

@@ -63,29 +95,19 @@ const { logInfo, logWarning } = makeComponentLogger("desktop-pairing-link");
6395
export const make = Effect.gen(function* () {
6496
const environment = yield* DesktopEnvironment.DesktopEnvironment;
6597
const electronApp = yield* ElectronApp.ElectronApp;
98+
const openUrls = yield* DesktopOpenUrls;
6699
const desktopWindow = yield* DesktopWindow.DesktopWindow;
67100
const runPromise = Effect.runPromiseWith(yield* Effect.context<never>());
68101
const scheme = ElectronProtocol.getDesktopScheme(environment.isDevelopment);
69102

70-
const pendingRef = yield* Ref.make(Option.none<string>());
71-
const rendererReadyRef = yield* Ref.make(false);
72-
73-
const deliver = Effect.fn("desktop.pairingLink.deliver")(function* (link: string) {
74-
yield* logInfo("delivering pairing link to renderer");
75-
yield* desktopWindow.dispatchPairingLink(link);
76-
});
103+
const queueRef = yield* Ref.make<ReadonlyArray<string>>([]);
77104

78-
// Reveal the window right away so the click feels acknowledged, but hold
79-
// the link until the renderer says it can act on it.
105+
// Queue first, then nudge. A running renderer pulls on the nudge; one that
106+
// is still loading pulls when it mounts and finds the link waiting.
80107
const receive = Effect.fn("desktop.pairingLink.receive")(function* (link: string) {
81-
yield* Ref.set(pendingRef, Option.some(link));
82-
if (yield* Ref.get(rendererReadyRef)) {
83-
yield* Ref.set(pendingRef, Option.none());
84-
yield* deliver(link);
85-
return;
86-
}
87-
yield* logInfo("holding pairing link until renderer is ready");
88-
yield* desktopWindow.activate;
108+
yield* Ref.update(queueRef, (queue) => [...queue, link]);
109+
yield* logInfo("queued pairing link");
110+
yield* desktopWindow.dispatchPairingLinkAvailable;
89111
});
90112

91113
const receiveFromCandidates = (candidates: ReadonlyArray<string>) => {
@@ -99,9 +121,9 @@ export const make = Effect.gen(function* () {
99121
};
100122

101123
const register = Effect.gen(function* () {
102-
// macOS hands URLs to the running (or launching) app via open-url. The
103-
// Clerk bridge also listens here but only claims its own renderer origin.
104-
yield* electronApp.on<[Electron.Event, string]>("open-url", (_event, url) => {
124+
// macOS: open-url, including any buffered from before this service existed.
125+
// The Clerk bridge also listens here but only claims its own renderer origin.
126+
yield* openUrls.subscribe((url) => {
105127
receiveFromCandidates([url]);
106128
});
107129
// Windows and Linux launch a second process with the URL in argv; the
@@ -116,20 +138,11 @@ export const make = Effect.gen(function* () {
116138
receiveFromCandidates(process.argv);
117139
}).pipe(Effect.withSpan("desktop.pairingLink.register"));
118140

119-
const setRendererReady = Effect.fn("desktop.pairingLink.setRendererReady")(function* (
120-
ready: boolean,
121-
) {
122-
yield* Ref.set(rendererReadyRef, ready);
123-
if (!ready) return;
124-
const pending = yield* Ref.getAndSet(pendingRef, Option.none());
125-
if (Option.isSome(pending)) {
126-
yield* deliver(pending.value).pipe(
127-
Effect.catchCause((cause) => logWarning("failed to deliver pairing link", { cause })),
128-
);
129-
}
130-
});
141+
const takePending = Ref.getAndSet(queueRef, []).pipe(
142+
Effect.withSpan("desktop.pairingLink.takePending"),
143+
);
131144

132-
return DesktopPairingLink.of({ register, setRendererReady });
145+
return DesktopPairingLink.of({ register, takePending });
133146
});
134147

135148
export const layer = Layer.effect(DesktopPairingLink, make);

‎apps/desktop/src/backend/DesktopBackendPool.test.ts‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -99,7 +99,7 @@ function makePoolLayer(
9999
prepareCaptureReveal: Effect.void,
100100
dispatchMenuAction: () => Effect.die("unexpected menu action"),
101101
dispatchSnapShotEvent: () => Effect.void,
102-
dispatchPairingLink: () => Effect.die("unexpected pairing link"),
102+
dispatchPairingLinkAvailable: Effect.die("unexpected pairing link"),
103103
zoomMain: () => Effect.die("unexpected zoom"),
104104
syncAppearance: Effect.void,
105105
} satisfies DesktopWindow.DesktopWindow["Service"]),

‎apps/desktop/src/ipc/DesktopIpcHandlers.ts‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -79,7 +79,7 @@ export const installDesktopIpcHandlers = Effect.fn("desktop.ipc.installHandlers"
7979

8080
yield* ipc.handle(AppActivationIpc.setReady);
8181
yield* ipc.handle(AppActivationIpc.complete);
82-
yield* ipc.handle(PairingLinkIpc.setReady);
82+
yield* ipc.handle(PairingLinkIpc.takePending);
8383

8484
yield* ipc.handleSync(getAppBranding);
8585
yield* ipc.handleSync(getSystemLocale);

‎apps/desktop/src/ipc/channels.ts‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -16,8 +16,8 @@ export const WINDOW_FULLSCREEN_STATE_CHANNEL = "desktop:window-fullscreen-state"
1616
export const DESKTOP_APP_ACTIVATION_READY_CHANNEL = "desktop:app-activation-ready";
1717
export const DESKTOP_APP_ACTIVATION_COMPLETE_CHANNEL = "desktop:app-activation-complete";
1818
export const DESKTOP_APP_ACTIVATION_REQUEST_CHANNEL = "desktop:app-activation-request";
19-
export const PAIRING_LINK_READY_CHANNEL = "desktop:pairing-link-ready";
20-
export const PAIRING_LINK_CHANNEL = "desktop:pairing-link";
19+
export const PAIRING_LINK_AVAILABLE_CHANNEL = "desktop:pairing-link-available";
20+
export const TAKE_PAIRING_LINKS_CHANNEL = "desktop:pairing-link-take";
2121
export const UPDATE_STATE_CHANNEL = "desktop:update-state";
2222
export const UPDATE_GET_STATE_CHANNEL = "desktop:update-get-state";
2323
export const UPDATE_SET_CHANNEL_CHANNEL = "desktop:update-set-channel";

‎apps/desktop/src/ipc/methods/pairingLink.ts‎

Lines changed: 6 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -5,12 +5,12 @@ import * as DesktopPairingLink from "../../app/DesktopPairingLink.ts";
55
import * as IpcChannels from "../channels.ts";
66
import * as DesktopIpc from "../DesktopIpc.ts";
77

8-
export const setReady = DesktopIpc.makeIpcMethod({
9-
channel: IpcChannels.PAIRING_LINK_READY_CHANNEL,
10-
payload: Schema.Boolean,
11-
result: Schema.Void,
12-
handler: Effect.fn("desktop.ipc.pairingLink.setReady")(function* (ready) {
8+
export const takePending = DesktopIpc.makeIpcMethod({
9+
channel: IpcChannels.TAKE_PAIRING_LINKS_CHANNEL,
10+
payload: Schema.Void,
11+
result: Schema.Array(Schema.String),
12+
handler: Effect.fn("desktop.ipc.pairingLink.takePending")(function* () {
1313
const pairingLink = yield* DesktopPairingLink.DesktopPairingLink;
14-
yield* pairingLink.setRendererReady(ready);
14+
return yield* pairingLink.takePending;
1515
}),
1616
});

‎apps/desktop/src/main.ts‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -227,6 +227,7 @@ const desktopRuntimeLayer = desktopClerkLayer.pipe(
227227
desktopApplicationRuntimeLayer.pipe(Layer.provideMerge(Layer.succeedContext(clerkContext))),
228228
),
229229
Layer.provideMerge(DesktopPreReadyPlatform.layer),
230+
Layer.provideMerge(DesktopPairingLink.layerOpenUrls),
230231
);
231232

232233
DesktopApp.program.pipe(Effect.provide(desktopRuntimeLayer), NodeRuntime.runMain);

‎apps/desktop/src/preload.ts‎

Lines changed: 6 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -276,15 +276,14 @@ contextBridge.exposeInMainWorld("desktopBridge", {
276276
},
277277
},
278278
pairingLink: {
279-
setReady: (ready) => ipcRenderer.invoke(IpcChannels.PAIRING_LINK_READY_CHANNEL, ready),
280-
onLink: (listener) => {
281-
const wrappedListener = (_event: Electron.IpcRendererEvent, url: unknown) => {
282-
if (typeof url !== "string") return;
283-
listener(url);
279+
takePending: () => ipcRenderer.invoke(IpcChannels.TAKE_PAIRING_LINKS_CHANNEL),
280+
onAvailable: (listener) => {
281+
const wrappedListener = () => {
282+
listener();
284283
};
285-
ipcRenderer.on(IpcChannels.PAIRING_LINK_CHANNEL, wrappedListener);
284+
ipcRenderer.on(IpcChannels.PAIRING_LINK_AVAILABLE_CHANNEL, wrappedListener);
286285
return () => {
287-
ipcRenderer.removeListener(IpcChannels.PAIRING_LINK_CHANNEL, wrappedListener);
286+
ipcRenderer.removeListener(IpcChannels.PAIRING_LINK_AVAILABLE_CHANNEL, wrappedListener);
288287
};
289288
},
290289
},

‎apps/desktop/src/window/DesktopApplicationMenu.test.ts‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -87,7 +87,7 @@ const makeDesktopWindowLayer = (selectedAction: Deferred.Deferred<string>) =>
8787
prepareCaptureReveal: Effect.void,
8888
dispatchMenuAction: (action) => Deferred.succeed(selectedAction, action).pipe(Effect.asVoid),
8989
dispatchSnapShotEvent: () => Effect.void,
90-
dispatchPairingLink: () => Effect.void,
90+
dispatchPairingLinkAvailable: Effect.void,
9191
zoomMain: (direction) =>
9292
Deferred.succeed(selectedAction, `zoom-${direction}`).pipe(Effect.asVoid),
9393
syncAppearance: Effect.void,

0 commit comments

Comments
 (0)