Skip to content

Commit 5e7ec52

Browse files
shivamhwpclaude
andcommitted
Merge commit '4c924ff4e6d0828e0a5810336ec7d7827d752645' into issue-watch/30384
Resolves DesktopBrowserHost conflicts with #32861: a tab still loading its first page reports its popup windows when it is announced, not before. Co-Authored-By: Claude Opus 5.5 <[email protected]>
2 parents 9028a57 + 4c924ff commit 5e7ec52

53 files changed

Lines changed: 2044 additions & 250 deletions

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

‎apps/desktop/src/preview/DesktopBrowserHost.test.ts‎

Lines changed: 75 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -35,6 +35,8 @@ const makeDebuggee = (
3535
options: {
3636
readonly targetId?: string;
3737
readonly deferFocus?: boolean;
38+
/** The guest is still loading its first page. */
39+
readonly loading?: boolean;
3840
readonly refuse?: (method: string, sessionId: string | undefined) => boolean;
3941
} = {},
4042
) => {
@@ -86,6 +88,7 @@ const makeDebuggee = (
8688
getURL: () => "http://localhost/",
8789
getTitle: () => "Page",
8890
getUserAgent: () => "Electron",
91+
isLoadingMainFrame: () => options.loading === true,
8992
isDestroyed: () => destroyed,
9093
isDevToolsOpened: () => devToolsOpened,
9194
close: vi.fn(),
@@ -111,6 +114,9 @@ const makeDebuggee = (
111114
webContents.emit("destroyed");
112115
},
113116
navigate: () => webContents.emit("did-navigate"),
117+
domReady: () => webContents.emit("dom-ready"),
118+
failLoad: (code: number) =>
119+
webContents.emit("did-fail-load", {}, code, "Failed", "http://localhost/", true),
114120
/** Ids of the commands the debugger received, in order. */
115121
sent,
116122
focusEmulation,
@@ -176,6 +182,75 @@ describe("DesktopBrowserHost", () => {
176182
}),
177183
);
178184

185+
it.effect("announces a guest still loading its first page only once that page is up", () =>
186+
Effect.gen(function* () {
187+
const host = yield* DesktopBrowserHost.make;
188+
const loading = makeDebuggee({ loading: true });
189+
const other = { ...key, tabId: "tab-2" };
190+
const reader = yield* takeEvents(host, 4).pipe(Effect.forkScoped);
191+
192+
yield* Effect.yieldNow;
193+
host.attach(key, loading.tab);
194+
host.setShown(key, true);
195+
host.openedPopup(loading.tab.webContents, makeDebuggee().tab.webContents);
196+
host.attach(other, makeDebuggee().tab);
197+
loading.domReady();
198+
199+
expect(yield* Fiber.join(reader)).toEqual([
200+
{ type: "attached", ...other },
201+
{ type: "attached", ...key },
202+
{ type: "popupWindows", ...key, open: true },
203+
{ type: "shown", ...key, shown: true },
204+
]);
205+
}),
206+
);
207+
208+
it.effect(
209+
"keeps a loading guest unannounced across a replaced navigation and a new backend",
210+
() =>
211+
Effect.gen(function* () {
212+
const host = yield* DesktopBrowserHost.make;
213+
const loading = makeDebuggee({ loading: true });
214+
const other = { ...key, tabId: "tab-2" };
215+
host.attach(key, loading.tab);
216+
loading.failLoad(-3);
217+
const reader = yield* takeEvents(host, 2).pipe(Effect.forkScoped);
218+
219+
yield* Effect.yieldNow;
220+
host.attach(other, makeDebuggee().tab);
221+
loading.domReady();
222+
223+
expect(yield* Fiber.join(reader)).toEqual([
224+
{ type: "attached", ...other },
225+
{ type: "attached", ...key },
226+
]);
227+
}),
228+
);
229+
230+
it.effect(
231+
"announces a first page that never comes up, but never a tab closed or destroyed first",
232+
() =>
233+
Effect.gen(function* () {
234+
const host = yield* DesktopBrowserHost.make;
235+
const closed = { ...key, tabId: "tab-2" };
236+
const destroyed = { ...key, tabId: "tab-3" };
237+
const destroyedGuest = makeDebuggee({ loading: true });
238+
const reader = yield* takeEvents(host, 1).pipe(Effect.forkScoped);
239+
240+
yield* Effect.yieldNow;
241+
const closedGuest = makeDebuggee({ loading: true });
242+
host.attach(closed, closedGuest.tab);
243+
host.openedPopup(closedGuest.tab.webContents, makeDebuggee().tab.webContents);
244+
host.detach(closed);
245+
host.attach(destroyed, destroyedGuest.tab);
246+
destroyedGuest.destroy();
247+
host.attach(key, makeDebuggee({ loading: true }).tab);
248+
yield* TestClock.adjust("5 seconds");
249+
250+
expect(yield* Fiber.join(reader)).toEqual([{ type: "attached", ...key }]);
251+
}),
252+
);
253+
179254
it.effect("re-sends shown to a backend that starts later and when a tab attaches again", () =>
180255
Effect.gen(function* () {
181256
const host = yield* DesktopBrowserHost.make;

‎apps/desktop/src/preview/DesktopBrowserHost.ts‎

Lines changed: 61 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,7 @@ import {
88
import * as Context from "effect/Context";
99
import * as NodePath from "node:path";
1010
import * as Effect from "effect/Effect";
11+
import * as Fiber from "effect/Fiber";
1112
import * as Layer from "effect/Layer";
1213
import * as Option from "effect/Option";
1314
import * as PubSub from "effect/PubSub";
@@ -28,6 +29,9 @@ const lineEncoder = new TextEncoder();
2829
const AGENT_INPUT_METHOD = /^(?:Input\.|Page\.navigate$|Runtime\.(?:evaluate|callFunctionOn)$)/;
2930
const AGENT_DOWNLOAD_WINDOW_MS = 5_000;
3031
const FOCUS_IDLE = "5 seconds";
32+
/** Well inside the server's 10 s DESKTOP_ATTACH_TIMEOUT, for a first page that never reports it is up. */
33+
const FIRST_PAGE_TIMEOUT = "5 seconds";
34+
const ERR_ABORTED = -3;
3135

3236
export interface DesktopBrowserTabKey {
3337
readonly threadId: string;
@@ -96,6 +100,8 @@ interface AttachedTab extends AttachedTarget {
96100
/** Set while the server drives the tab for an agent, whose popups become its tabs too. */
97101
showsPopups: boolean;
98102
readonly popups: Map<Electron.WebContents, AttachedPopup>;
103+
/** Stops waiting for the first page; set until the tab is announced. */
104+
stopWaiting: (() => void) | null;
99105
}
100106

101107
interface AttachedPopup extends AttachedTarget {
@@ -548,7 +554,10 @@ export const make = Effect.gen(function* () {
548554
};
549555
const report = (open: boolean) => {
550556
for (const tab of tabs.values()) {
551-
if (tab.debuggee.webContents === opener) emit({ type: "popupWindows", ...tab.key, open });
557+
// A tab still waiting for its first page reports them when it is announced.
558+
if (tab.debuggee.webContents === opener && tab.stopWaiting === null) {
559+
emit({ type: "popupWindows", ...tab.key, open });
560+
}
552561
}
553562
};
554563
popup.on("devtools-closed", show);
@@ -590,11 +599,13 @@ export const make = Effect.gen(function* () {
590599
if (!tab) return;
591600
for (const popup of tab.popups.values()) hidePopup(popup);
592601
tabs.delete(id);
602+
const announced = tab.stopWaiting === null;
603+
tab.stopWaiting?.();
593604
tab.relay = null;
594605
tab.debuggee.debugger.off("message", tab.onMessage);
595606
tab.debuggee.webContents.off("did-navigate", tab.onNewDocument);
596607
syncPainting(tab);
597-
emit({ type: "detached", ...key });
608+
if (announced) emit({ type: "detached", ...key });
598609
};
599610

600611
const attach = (key: DesktopBrowserTabKey, debuggee: DesktopBrowserTabDebugger) => {
@@ -613,18 +624,58 @@ export const make = Effect.gen(function* () {
613624
painting: false,
614625
showsPopups: false,
615626
popups: new Map(),
627+
stopWaiting: null,
616628
},
617629
() => tab.relay,
618630
);
619631
tabs.set(id, tab);
620632
debuggee.debugger.on("message", tab.onMessage);
621633
debuggee.webContents.on("did-navigate", tab.onNewDocument);
622-
emit({ type: "attached", ...key });
623-
if (openedPopups.get(debuggee.webContents)?.size) {
624-
emit({ type: "popupWindows", ...key, open: true });
634+
const announce = () => {
635+
emit({ type: "attached", ...key });
636+
if (openedPopups.get(debuggee.webContents)?.size) {
637+
emit({ type: "popupWindows", ...key, open: true });
638+
}
639+
const shown = shownTabs.get(id);
640+
if (shown !== undefined) emit({ type: "shown", ...key, shown });
641+
};
642+
if (!debuggee.webContents.isLoadingMainFrame()) {
643+
announce();
644+
return;
625645
}
626-
const shown = shownTabs.get(id);
627-
if (shown !== undefined) emit({ type: "shown", ...key, shown });
646+
// Electron does not pause a guest for the debugger, so Playwright connecting during its first
647+
// commit builds its utility world in the discarded document and every wait on it hangs.
648+
const { webContents } = debuggee;
649+
// ERR_ABORTED is a newer navigation replacing this one, whose commit is still to come.
650+
const onFailLoad = (
651+
_event: Electron.Event,
652+
code: number,
653+
_description: string,
654+
_url: string,
655+
isMainFrame: boolean,
656+
) => {
657+
if (isMainFrame && code !== ERR_ABORTED) ready();
658+
};
659+
const ready = () => {
660+
if (tab.stopWaiting === null) return;
661+
// The manager's cleanup for a destroyed guest can still be queued behind another tab's attach.
662+
if (webContents.isDestroyed()) return detach(key);
663+
tab.stopWaiting();
664+
announce();
665+
};
666+
const timeout = runFork(
667+
Effect.sleep(FIRST_PAGE_TIMEOUT).pipe(Effect.andThen(Effect.sync(ready))),
668+
);
669+
tab.stopWaiting = () => {
670+
tab.stopWaiting = null;
671+
webContents.off("dom-ready", ready);
672+
webContents.off("did-stop-loading", ready);
673+
webContents.off("did-fail-load", onFailLoad);
674+
runFork(Fiber.interrupt(timeout));
675+
};
676+
webContents.on("dom-ready", ready);
677+
webContents.on("did-stop-loading", ready);
678+
webContents.on("did-fail-load", onFailLoad);
628679
};
629680

630681
const setShown = (key: DesktopBrowserTabKey, shown: boolean | undefined) => {
@@ -635,7 +686,7 @@ export const make = Effect.gen(function* () {
635686
}
636687
if (shownTabs.get(id) === shown) return;
637688
shownTabs.set(id, shown);
638-
if (tabs.has(id)) emit({ type: "shown", ...key, shown });
689+
if (tabs.get(id)?.stopWaiting === null) emit({ type: "shown", ...key, shown });
639690
};
640691

641692
const handleCommandLine = (line: string) =>
@@ -681,6 +732,8 @@ export const make = Effect.gen(function* () {
681732
[...tabs.values()],
682733
(tab) => {
683734
dropRelay(tab);
735+
// Announced once its first page is up.
736+
if (tab.stopWaiting !== null) return Effect.void;
684737
const shown = shownTabs.get(keyOf(tab.key));
685738
return PubSub.publish(outbox, { type: "attached", ...tab.key }).pipe(
686739
Effect.andThen(

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

Lines changed: 52 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -233,7 +233,7 @@ function layerTest(input: {
233233
readonly destroyAll?: Effect.Effect<void>;
234234
readonly onWindowCreate?: Effect.Effect<void>;
235235
readonly openedExternalUrls?: unknown[];
236-
readonly copiedTexts?: string[];
236+
readonly onCopyText?: (text: string) => Effect.Effect<void>;
237237
readonly onPopupTemplate?: (input: ElectronMenu.ElectronMenuTemplateInput) => Effect.Effect<void>;
238238
readonly previewZoomReapplies?: number[];
239239
readonly onReveal?: (window: Electron.BrowserWindow) => void;
@@ -325,10 +325,7 @@ function layerTest(input: {
325325
return true;
326326
}),
327327
openSystemSettings: () => Effect.succeed(true),
328-
copyText: (text) =>
329-
Effect.sync(() => {
330-
input.copiedTexts?.push(text);
331-
}),
328+
copyText: input.onCopyText ?? (() => Effect.void),
332329
} satisfies ElectronShell.ElectronShell["Service"]),
333330
layerElectronTheme,
334331
layerElectronWindow,
@@ -1186,6 +1183,56 @@ describe("DesktopWindow", () => {
11861183
}),
11871184
);
11881185

1186+
it.effect("offers to copy the bare address when right-clicking a mailto link", () =>
1187+
Effect.gen(function* () {
1188+
const fakeWindow = makeFakeBrowserWindow();
1189+
const createCount = yield* Ref.make(0);
1190+
const mainWindow = yield* Ref.make<Option.Option<Electron.BrowserWindow>>(Option.none());
1191+
const popup = yield* Deferred.make<ElectronMenu.ElectronMenuTemplateInput>();
1192+
const copied = yield* Deferred.make<string>();
1193+
const layer = layerTest({
1194+
window: fakeWindow.window,
1195+
createCount,
1196+
mainWindow,
1197+
onPopupTemplate: (input) => Deferred.succeed(popup, input),
1198+
onCopyText: (text) => Deferred.succeed(copied, text),
1199+
});
1200+
1201+
yield* Effect.gen(function* () {
1202+
const desktopWindow = yield* DesktopWindow.DesktopWindow;
1203+
yield* desktopWindow.handleBackendReady(new URL("http://127.0.0.1:3773"));
1204+
1205+
const contextMenu = fakeWindow.webContentsListeners.get("context-menu");
1206+
if (!contextMenu) {
1207+
return yield* Effect.die("context-menu listener was not registered");
1208+
}
1209+
contextMenu(
1210+
{ preventDefault: vi.fn() },
1211+
{
1212+
linkURL: "mailto:restaurant%40example.com?subject=Hi",
1213+
misspelledWord: "",
1214+
dictionarySuggestions: [],
1215+
mediaType: "none",
1216+
editFlags: { canCut: false, canCopy: false, canPaste: false, canSelectAll: true },
1217+
},
1218+
);
1219+
1220+
const { template } = yield* Deferred.await(popup);
1221+
const copyEmail = template.find((item) => item.label === "Copy Email Address");
1222+
assert.isDefined(
1223+
copyEmail,
1224+
`no "Copy Email Address" item in ${JSON.stringify(template.map((item) => item.label ?? item.role ?? item.type))}`,
1225+
);
1226+
copyEmail?.click?.(
1227+
{} as Electron.MenuItem,
1228+
fakeWindow.window,
1229+
{} as Electron.KeyboardEvent,
1230+
);
1231+
assert.equal(yield* Deferred.await(copied), "[email protected]");
1232+
}).pipe(Effect.provide(layer));
1233+
}),
1234+
);
1235+
11891236
it.effect(
11901237
"retries opening the real main on activate when a failed post-readiness open left only the splash",
11911238
() =>

‎apps/desktop/src/window/DesktopWindow.ts‎

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -53,6 +53,21 @@ class ContextMenuImageCopyError extends Schema.TaggedError<ContextMenuImageCopyE
5353
const MACOS_WORKSPACE_TOPBAR_HEIGHT = 52;
5454
const MACOS_WINDOW_BUTTON_RADIUS = 7;
5555

56+
function parseMailtoAddress(rawUrl: string): Option.Option<string> {
57+
let url: URL;
58+
try {
59+
url = new URL(rawUrl);
60+
} catch {
61+
return Option.none();
62+
}
63+
if (url.protocol !== "mailto:" || url.pathname === "") return Option.none();
64+
try {
65+
return Option.some(decodeURIComponent(url.pathname));
66+
} catch {
67+
return Option.some(url.pathname);
68+
}
69+
}
70+
5671
function syncMacosWindowButtons(window: Electron.BrowserWindow): void {
5772
if (window.isDestroyed() || window.isFullScreen()) return;
5873
window.setWindowButtonPosition({
@@ -590,6 +605,19 @@ export const make = Effect.gen(function* () {
590605
);
591606
}
592607

608+
const mailtoAddress = parseMailtoAddress(params.linkURL);
609+
if (Option.isSome(mailtoAddress)) {
610+
menuTemplate.push(
611+
{
612+
label: "Copy Email Address",
613+
click: () => {
614+
void runPromise(electronShell.copyText(mailtoAddress.value));
615+
},
616+
},
617+
{ type: "separator" },
618+
);
619+
}
620+
593621
if (params.mediaType === "image") {
594622
menuTemplate.push({
595623
label: "Copy Image",

0 commit comments

Comments
 (0)