From c916341ec6b4d630e3774b62cbb92de45fcc7ae1 Mon Sep 17 00:00:00 2001 From: Ramavtar Yadav Date: Sat, 14 Nov 2026 01:09:34 +0530 Subject: [PATCH 1/3] fix(desktop): same-origin window.open keeps window.opener Featureless same-origin window.open is a Chromium tab, and T3 was opening it as a fresh URL tab, which dropped the opener HTML5 apps need. Co-authored-by: Cursor --- apps/desktop/src/preview/Manager.test.ts | 35 +++++++++++++++++++ apps/desktop/src/preview/Manager.ts | 43 ++++++++++++++++++------ 2 files changed, 67 insertions(+), 11 deletions(-) diff --git a/apps/desktop/src/preview/Manager.test.ts b/apps/desktop/src/preview/Manager.test.ts index 530a1200378b1..6344452ca408d 100644 --- a/apps/desktop/src/preview/Manager.test.ts +++ b/apps/desktop/src/preview/Manager.test.ts @@ -95,6 +95,29 @@ describe("previewWindowOpenAction", () => { } }); + it("keeps the opener for a same-origin window.open that Chromium reports as a tab", () => { + for (const disposition of ["foreground-tab", "background-tab"] as const) { + expect( + PreviewManager.previewWindowOpenAction( + details({ + url: "https://vdid.sbigeneral.in/appremote/#/client/CAMS_VDI-2", + disposition, + }), + "https://vdid.sbigeneral.in/", + ), + ).toBe("popup"); + } + }); + + it("still opens a cross-origin target=_blank link in a preview tab", () => { + expect( + PreviewManager.previewWindowOpenAction( + details({ disposition: "foreground-tab" }), + "https://vdid.sbigeneral.in/", + ), + ).toBe("new-tab"); + }); + it("keeps a form POST with a body on the in-place path", () => { const postBody = { data: [], contentType: "application/x-www-form-urlencoded" }; expect( @@ -103,6 +126,18 @@ describe("previewWindowOpenAction", () => { postBody, }), ).toBe("navigate"); + expect( + PreviewManager.previewWindowOpenAction( + { + ...details({ + url: "https://vdid.sbigeneral.in/submit", + disposition: "foreground-tab", + }), + postBody, + }, + "https://vdid.sbigeneral.in/", + ), + ).toBe("navigate"); }); it("does not hand a window to schemes that cannot be hardened", () => { diff --git a/apps/desktop/src/preview/Manager.ts b/apps/desktop/src/preview/Manager.ts index 49b61c73316f3..5fc469937c132 100644 --- a/apps/desktop/src/preview/Manager.ts +++ b/apps/desktop/src/preview/Manager.ts @@ -484,24 +484,44 @@ const POPUP_WINDOW_OPTIONS = { }, } satisfies Electron.BrowserWindowConstructorOptions; +const isSameOriginHttpUrl = (left: string, right: string): boolean => { + const from = URL.parse(left); + const to = URL.parse(right); + return ( + from !== null && + to !== null && + (from.protocol === "http:" || from.protocol === "https:") && + from.origin === to.origin + ); +}; + /** - * OAuth needs a surviving popup opener. `blob:`, app links (behind the session's `openExternal` - * prompt) and form POSTs stay in place. + * OAuth needs a surviving popup opener. Same-origin `window.open` without features is a Chromium + * foreground-tab; opening it as a T3 tab via URL navigation drops `window.opener`. + * `blob:`, app links (behind the session's `openExternal` prompt) and form POSTs stay in place. */ -export const previewWindowOpenAction = (details: { - readonly url: string; - readonly disposition: Electron.HandlerDetails["disposition"]; - readonly postBody?: Electron.PostBody; -}): "popup" | "new-tab" | "navigate" | "deny" => { +export const previewWindowOpenAction = ( + details: { + readonly url: string; + readonly disposition: Electron.HandlerDetails["disposition"]; + readonly postBody?: Electron.PostBody; + }, + openerUrl?: string, +): "popup" | "new-tab" | "navigate" | "deny" => { const protocol = URL.parse(details.url)?.protocol; // MSAL redirects on a denied blank popup; navigating the tab would destroy that fallback. if (protocol === undefined || IN_PLACE_DENIED_PROTOCOLS.has(protocol)) return "deny"; if (!POPUP_PROTOCOLS.has(protocol)) return "navigate"; if (details.disposition === "new-window") return "popup"; - return !details.postBody && + if ( + !details.postBody && (details.disposition === "foreground-tab" || details.disposition === "background-tab") - ? "new-tab" - : "navigate"; + ) { + return openerUrl !== undefined && isSameOriginHttpUrl(details.url, openerUrl) + ? "popup" + : "new-tab"; + } + return "navigate"; }; const isPreviewRefreshShortcut = (input: Electron.Input, platform: NodeJS.Platform): boolean => @@ -1646,7 +1666,8 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function wc.ipc.on(PAGE_UNHANDLED_SHORTCUT_CHANNEL, pageUnhandledShortcut); detachPasskeys = passkeys.attachGuest(wc); wc.setWindowOpenHandler((details) => { - const action = previewWindowOpenAction(details); + const openerUrl = wc.isDestroyed() ? undefined : wc.getURL(); + const action = previewWindowOpenAction(details, openerUrl); if (action === "popup") { return { action: "allow", overrideBrowserWindowOptions: POPUP_WINDOW_OPTIONS }; } From 5f9a2218c801975867ec4d185305bac9f3efcdfb Mon Sep 17 00:00:00 2001 From: Ramavtar Yadav Date: Sun, 15 Nov 2026 20:34:48 +0530 Subject: [PATCH 2/3] fix(desktop): agents can drive native preview popups Same-origin window.open now keeps opener by allowing a native window. Expose that window over the CDP relay so Playwright adopts it as a preview tab instead of leaving it unreachable to agents. Co-authored-by: Cursor --- apps/desktop/src/preview/CdpRelay.test.ts | 51 ++++++ apps/desktop/src/preview/CdpRelay.ts | 153 ++++++++++++++++-- .../desktop/src/preview/DesktopBrowserHost.ts | 74 +++++++++ apps/desktop/src/preview/Manager.test.ts | 1 + apps/desktop/src/preview/Manager.ts | 1 + apps/server/src/preview/Manager.ts | 3 + apps/server/src/preview/ServerBrowser.ts | 26 ++- 7 files changed, 291 insertions(+), 18 deletions(-) diff --git a/apps/desktop/src/preview/CdpRelay.test.ts b/apps/desktop/src/preview/CdpRelay.test.ts index ccc2b868720b4..62b9a5a0cc064 100644 --- a/apps/desktop/src/preview/CdpRelay.test.ts +++ b/apps/desktop/src/preview/CdpRelay.test.ts @@ -399,3 +399,54 @@ describe("CDP relay reconnects", () => { expect(await connect()).toEqual(expected); }); }); + +describe("CDP relay popups", () => { + it("announces a native popup with its opener, drives it, and detaches it once it closes", async () => { + const written: Array> = []; + const relay = makeRelay(makeTarget(vi.fn()), (raw) => written.push(JSON.parse(raw))); + const popupSend = vi.fn(async (method: string) => ({ method })); + const close = vi.fn(); + const popup = relay.addPopup({ + send: popupSend, + targetId: async () => "POPUP-TARGET", + url: () => "http://localhost:4719/popup", + title: () => "Sign in", + close, + }); + relay.receive(JSON.stringify({ id: 1, method: "Target.setAutoAttach", params: {} })); + await settle(); + const announced = written.filter((message) => message["method"] === "Target.attachedToTarget"); + expect(announced.map((message) => message["params"])).toEqual([ + expect.objectContaining({ sessionId: "t3-preview-page" }), + expect.objectContaining({ + targetInfo: expect.objectContaining({ + targetId: "POPUP-TARGET", + openerId: "GUEST-TARGET", + canAccessOpener: true, + }), + }), + ]); + const sessionId = (announced[1]!["params"] as { sessionId: string }).sessionId; + + relay.receive(JSON.stringify({ id: 2, method: "DOM.enable", sessionId })); + popup.event("Page.loadEventFired", { timestamp: 1 }, ""); + relay.receive( + JSON.stringify({ id: 3, method: "Target.closeTarget", params: { targetId: "POPUP-TARGET" } }), + ); + await settle(); + expect(popupSend).toHaveBeenCalledWith("DOM.enable", {}, undefined); + expect(written).toContainEqual({ id: 2, result: { method: "DOM.enable" }, sessionId }); + expect(written).toContainEqual({ + method: "Page.loadEventFired", + params: { timestamp: 1 }, + sessionId, + }); + expect(close).toHaveBeenCalledOnce(); + + popup.remove(); + expect(written.at(-1)).toEqual({ + method: "Target.detachedFromTarget", + params: { sessionId, targetId: "POPUP-TARGET" }, + }); + }); +}); diff --git a/apps/desktop/src/preview/CdpRelay.ts b/apps/desktop/src/preview/CdpRelay.ts index 658e1cf70623d..4a8a74c8b101b 100644 --- a/apps/desktop/src/preview/CdpRelay.ts +++ b/apps/desktop/src/preview/CdpRelay.ts @@ -20,9 +20,29 @@ export interface CdpRelayTarget { readonly setDownloadDirectory: (directory: string | null) => void; } +/** A native window the page opened; it runs on its own debugger. */ +export interface CdpRelayPopupTarget { + readonly send: ( + method: string, + params: Record, + sessionId: string | undefined, + ) => Promise; + readonly targetId: () => Promise; + readonly url: () => string; + readonly title: () => string; + readonly close: () => void; +} + +type CdpRelayEvent = (method: string, params: unknown, sessionId: string | undefined) => void; + export interface CdpRelayConnection { readonly receive: (raw: string) => void; - readonly event: (method: string, params: unknown, sessionId: string | undefined) => void; + readonly event: CdpRelayEvent; + /** Announces the window as the page's popup; `remove` once it closes. */ + readonly addPopup: (target: CdpRelayPopupTarget) => { + readonly event: CdpRelayEvent; + readonly remove: () => void; + }; } interface CdpCommand { @@ -72,6 +92,14 @@ const ACKNOWLEDGED = new Set([ "Browser.cancelDownload", ]); +interface Popup { + readonly target: CdpRelayPopupTarget; + /** Set once announced to Playwright; a closed window cannot be asked for its id. */ + sessionId: string | null; + targetId: string | null; + runtimeReset?: Promise; +} + export function createCdpRelayConnection( target: CdpRelayTarget, write: (message: string) => void, @@ -101,11 +129,14 @@ export function createCdpRelayConnection( }; let attached = false; let downloadEventsEnabled = false; - /** Relay-created page sessions share one real debugger; child frame sessions retain their own ids. */ - const sessions = new Map([[PAGE_SESSION_ID, "page"]]); + /** Relay-created page sessions of one page share its debugger; child frame sessions retain their own ids. */ + const sessions = new Map([[PAGE_SESSION_ID, "page"]]); + /** Frame and worker sessions of popups; any other child session is the page's. */ + const popupChildren = new Map(); + const popups = new Set(); let sessionSequence = 0; - const newSession = (kind: "browser" | "page") => { - const sessionId = `t3-preview-${kind}-${++sessionSequence}`; + const newSession = (kind: "browser" | "page" | Popup) => { + const sessionId = `t3-preview-${typeof kind === "string" ? kind : "popup"}-${++sessionSequence}`; sessions.set(sessionId, kind); return sessionId; }; @@ -118,6 +149,38 @@ export function createCdpRelayConnection( canAccessOpener: false, browserContextId: BROWSER_CONTEXT_ID, }); + const popupInfo = async (popup: Popup) => ({ + targetId: await popup.target.targetId(), + type: "page", + title: popup.target.title(), + url: popup.target.url(), + attached: true, + canAccessOpener: true, + openerId: await target.targetId(), + browserContextId: BROWSER_CONTEXT_ID, + }); + const findPopup = async (targetId: unknown) => { + for (const popup of popups) if (popup.targetId === targetId) return popup; + return undefined; + }; + /** In order, after the page itself, so Playwright already knows each popup's opener. */ + let announcing = Promise.resolve(); + const announcePopup = (popup: Popup) => { + announcing = announcing.then(() => + popupInfo(popup).then( + (info) => { + if (!popups.has(popup) || popup.sessionId !== null) return; + popup.sessionId = newSession(popup); + popup.targetId = info.targetId; + send({ + method: "Target.attachedToTarget", + params: { sessionId: popup.sessionId, targetInfo: info, waitingForDebugger: false }, + }); + }, + () => undefined, + ), + ); + }; const browserCommand = async (command: CdpCommand): Promise => { if (ACKNOWLEDGED.has(command.method)) return {}; @@ -157,23 +220,38 @@ export function createCdpRelayConnection( case "Target.getBrowserContexts": return { browserContextIds: [] }; case "Target.getTargets": - return { targetInfos: [await targetInfo()] }; + return { + targetInfos: [ + await targetInfo(), + ...(await Promise.all( + [...popups].filter((popup) => popup.sessionId !== null).map(popupInfo), + )), + ], + }; case "Target.attachToBrowserTarget": return { sessionId: newSession("browser") }; case "Target.attachToTarget": { const targetId = command.params?.["targetId"]; - if (targetId !== (await target.targetId())) - throw new Error("Only this preview tab's page can be attached."); - return { sessionId: newSession("page") }; + if (targetId === (await target.targetId())) return { sessionId: newSession("page") }; + const popup = await findPopup(targetId); + if (!popup) throw new Error("Only this preview tab's page and its popups can be attached."); + return { sessionId: newSession(popup) }; } case "Target.detachFromTarget": { const sessionId = command.params?.["sessionId"]; if (typeof sessionId === "string" && sessionId !== PAGE_SESSION_ID) { + const kind = sessions.get(sessionId); sessions.delete(sessionId); - target.sessionDetached?.(sessionId); + if (kind === "page") target.sessionDetached?.(sessionId); } return {}; } + case "Target.closeTarget": { + const popup = await findPopup(command.params?.["targetId"]); + if (!popup) throw new Error("Only a preview tab's popup can be closed this way."); + popup.target.close(); + return { success: true }; + } case "Target.setAutoAttach": { if (attached) return {}; attached = true; @@ -192,7 +270,25 @@ export function createCdpRelayConnection( let runtimeReset: Promise | undefined; + const popupCommand = (popup: Popup, command: CdpCommand): Promise => { + const child = sessions.get(command.sessionId!) === popup ? undefined : command.sessionId; + if (command.method === "Runtime.runIfWaitingForDebugger" && child === undefined) { + return Promise.resolve({}); + } + if (command.method === "Emulation.setFocusEmulationEnabled") return Promise.resolve({}); + // Its debugger outlives a connection too, so its execution contexts need the same reset. + if (command.method === "Runtime.enable" && child === undefined) { + popup.runtimeReset ??= popup.target.send("Runtime.disable", {}, undefined).catch(() => {}); + return popup.runtimeReset.then(() => + popup.target.send(command.method, command.params ?? {}, undefined), + ); + } + return popup.target.send(command.method, command.params ?? {}, child); + }; + const pageCommand = (command: CdpCommand): Promise => { + const popup = sessions.get(command.sessionId!) ?? popupChildren.get(command.sessionId!); + if (typeof popup === "object") return popupCommand(popup, command); const child = sessions.get(command.sessionId!) === "page" ? undefined : command.sessionId; const owner = child === undefined && command.sessionId !== PAGE_SESSION_ID ? command.sessionId : undefined; @@ -236,7 +332,9 @@ export function createCdpRelayConnection( ? (value as { [ANNOUNCE]: Record })[ANNOUNCE] : undefined; send({ id: command.id, result: announce ? {} : (value ?? {}), ...route }); - if (announce) send(announce); + if (!announce) return; + send(announce); + for (const popup of popups) announcePopup(popup); }, (cause: unknown) => send({ @@ -272,5 +370,38 @@ export function createCdpRelayConnection( send({ method, params, sessionId: id }); } }, + addPopup: (popupTarget) => { + const popup: Popup = { target: popupTarget, sessionId: null, targetId: null }; + popups.add(popup); + if (attached) announcePopup(popup); + return { + event: (method, params, sessionId) => { + if (popup.sessionId === null || !popups.has(popup)) return; + const child = (params as { sessionId?: unknown } | null | undefined)?.sessionId; + if (method === "Target.attachedToTarget" && typeof child === "string") + popupChildren.set(child, popup); + else if (method === "Target.detachedFromTarget" && typeof child === "string") + popupChildren.delete(child); + // Downloads stay the page's; a popup's would need its own will-download placement. + if (method.startsWith("Page.download")) return; + if (sessionId) { + send({ method, params, sessionId }); + return; + } + for (const [id, kind] of sessions) + if (kind === popup) send({ method, params, sessionId: id }); + }, + remove: () => { + if (!popups.delete(popup)) return; + for (const [id, owner] of popupChildren) if (owner === popup) popupChildren.delete(id); + const { targetId } = popup; + for (const [id, kind] of sessions) { + if (kind !== popup) continue; + sessions.delete(id); + send({ method: "Target.detachedFromTarget", params: { sessionId: id, targetId } }); + } + }, + }; + }, }; } diff --git a/apps/desktop/src/preview/DesktopBrowserHost.ts b/apps/desktop/src/preview/DesktopBrowserHost.ts index e5f43634d204a..65cf334746f90 100644 --- a/apps/desktop/src/preview/DesktopBrowserHost.ts +++ b/apps/desktop/src/preview/DesktopBrowserHost.ts @@ -44,6 +44,15 @@ export interface DesktopBrowserTabDebugger { readonly cookiesCleared?: () => Promise; } +/** A native window the tab's page opened, driven through its own debugger. */ +interface AttachedPopup { + readonly webContents: Electron.WebContents; + readonly debugger: Electron.Debugger; + relayed: ReturnType | null; + readonly onMessage: AttachedTab["onMessage"]; + readonly onDestroyed: () => void; +} + const keyOf = ({ threadId, tabId }: DesktopBrowserTabKey) => `${threadId}\u0000${tabId}`; interface AttachedTab { @@ -86,6 +95,7 @@ interface AttachedTab { readonly onNewDocument: () => void; /** Stops waiting for the first page; set until the tab is announced. */ stopWaiting: (() => void) | null; + readonly popups: Set; } export class DesktopBrowserHost extends Context.Service< @@ -95,6 +105,8 @@ export class DesktopBrowserHost extends Context.Service< readonly handleCommandLine: (line: string) => Effect.Effect; readonly attach: (key: DesktopBrowserTabKey, debuggee: DesktopBrowserTabDebugger) => void; readonly detach: (key: DesktopBrowserTabKey) => void; + /** A page in an attached tab opened a native window; its agent can drive it. */ + readonly openedPopup: (opener: Electron.WebContents, popup: Electron.WebContents) => void; readonly loadFailed: (key: DesktopBrowserTabKey, failure: PreviewAutomationLoadError) => void; readonly setShown: (key: DesktopBrowserTabKey, shown: boolean | undefined) => void; readonly humanStartedDownload: (source: Electron.WebContents) => boolean; @@ -282,8 +294,66 @@ export const make = Effect.gen(function* () { syncPainting(tab); }; + const relayPopup = (relay: CdpRelayConnection, popup: AttachedPopup) => { + const { webContents, debugger: debuggee } = popup; + popup.relayed = relay.addPopup({ + send: (method, params, sessionId) => + sessionId === undefined + ? debuggee.sendCommand(method, params) + : debuggee.sendCommand(method, params, sessionId), + targetId: () => + debuggee + .sendCommand("Target.getTargetInfo") + .then((result: { targetInfo: { targetId: string } }) => result.targetInfo.targetId), + url: () => (webContents.isDestroyed() ? "" : webContents.getURL()), + title: () => (webContents.isDestroyed() ? "" : webContents.getTitle()), + close: () => { + if (!webContents.isDestroyed()) webContents.close(); + }, + }); + }; + + const forgetPopup = (tab: AttachedTab, popup: AttachedPopup) => { + if (!tab.popups.delete(popup)) return; + popup.relayed?.remove(); + popup.relayed = null; + popup.debugger.off("message", popup.onMessage); + if (popup.webContents.isDestroyed()) return; + popup.webContents.off("destroyed", popup.onDestroyed); + try { + if (popup.debugger.isAttached()) popup.debugger.detach(); + } catch {} + }; + + const openedPopup = (opener: Electron.WebContents, webContents: Electron.WebContents) => { + const tab = [...tabs.values()].find((candidate) => candidate.debuggee.webContents === opener); + if (!tab || webContents.isDestroyed()) return; + // Retained like the tab's own so Electron does not collect the debugger. + const debuggee = webContents.debugger; + try { + // DevTools or another client holding it leaves the window to the person. + if (debuggee.isAttached()) return; + debuggee.attach("1.3"); + } catch { + return; + } + const popup: AttachedPopup = { + webContents, + debugger: debuggee, + relayed: null, + onMessage: (_event, method, params, sessionId) => + popup.relayed?.event(method, params, sessionId), + onDestroyed: () => forgetPopup(tab, popup), + }; + tab.popups.add(popup); + debuggee.on("message", popup.onMessage); + webContents.once("destroyed", popup.onDestroyed); + if (tab.relay) relayPopup(tab.relay, popup); + }; + const dropRelay = (tab: AttachedTab) => { tab.relay = null; + for (const popup of tab.popups) popup.relayed = null; tab.screencasts.clear(); tab.agentUsed = false; dropFocusHolds(tab); @@ -449,6 +519,7 @@ export const make = Effect.gen(function* () { }, ); tab.relay = relay; + for (const popup of tab.popups) relayPopup(relay, popup); return relay; }; @@ -471,6 +542,7 @@ export const make = Effect.gen(function* () { const announced = tab.stopWaiting === null; tab.stopWaiting?.(); tab.relay = null; + for (const popup of tab.popups) forgetPopup(tab, popup); tab.debuggee.debugger.off("message", tab.onMessage); tab.debuggee.webContents.off("did-navigate", tab.onNewDocument); syncPainting(tab); @@ -515,6 +587,7 @@ export const make = Effect.gen(function* () { if (tab.screenshotTurn !== null) nextScreenshot(tab); }, stopWaiting: null, + popups: new Set(), }; tabs.set(id, tab); debuggee.debugger.on("message", tab.onMessage); @@ -643,6 +716,7 @@ export const make = Effect.gen(function* () { handleCommandLine, attach, detach, + openedPopup, loadFailed, setShown, placeDownload, diff --git a/apps/desktop/src/preview/Manager.test.ts b/apps/desktop/src/preview/Manager.test.ts index 6344452ca408d..703869333c9bb 100644 --- a/apps/desktop/src/preview/Manager.test.ts +++ b/apps/desktop/src/preview/Manager.test.ts @@ -651,6 +651,7 @@ describe("PreviewManager", () => { Layer.mock(DesktopBrowserHost.DesktopBrowserHost)({ attach: () => {}, detach: () => {}, + openedPopup: () => {}, setShown: () => {}, loadFailed: () => {}, humanStartedDownload: () => true, diff --git a/apps/desktop/src/preview/Manager.ts b/apps/desktop/src/preview/Manager.ts index 5fc469937c132..5311df1effc4a 100644 --- a/apps/desktop/src/preview/Manager.ts +++ b/apps/desktop/src/preview/Manager.ts @@ -1554,6 +1554,7 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function window.webContents.on("before-input-event", (_event, input) => { syncMenuShortcuts(window.webContents, input); }); + browserHost.openedPopup(wc, window.webContents); }; const findForwardedShortcut = (keys: Parameters[0]) => !( diff --git a/apps/server/src/preview/Manager.ts b/apps/server/src/preview/Manager.ts index 0899866f80b64..8ab52bde03112 100644 --- a/apps/server/src/preview/Manager.ts +++ b/apps/server/src/preview/Manager.ts @@ -35,6 +35,8 @@ export class PreviewManager extends Context.Service< readonly open: ( input: PreviewOpenInput & { readonly automationOwner?: string; + /** The desktop streams the tab from its first snapshot instead of hosting a webview. */ + readonly headless?: boolean; /** Runs before the `opened` event publishes, so subscribers find state keyed by the tab. */ readonly beforePublish?: (snapshot: PreviewSessionSnapshot) => void; }, @@ -199,6 +201,7 @@ export const make = Effect.gen(function* PreviewManagerMake() { ? { automationOwner: input.automationOwner } : {}), ...(input.reveal === undefined ? {} : { reveal: input.reveal }), + ...(runtime === "server" && input.headless ? { headless: true } : {}), updatedAt, }; yield* SynchronizedRef.modifyEffect(stateRef, (state) => diff --git a/apps/server/src/preview/ServerBrowser.ts b/apps/server/src/preview/ServerBrowser.ts index 6537576c89a73..c7609ef2b9ffe 100644 --- a/apps/server/src/preview/ServerBrowser.ts +++ b/apps/server/src/preview/ServerBrowser.ts @@ -548,7 +548,10 @@ const make = Effect.gen(function* () { >(); const closedPendingTabs = new Set(); - const adoptedPages = new Map(); + const adoptedPages = new Map< + string, + { readonly page: Page; readonly openerTabId: string; readonly native: boolean } + >(); const closedSessions = new Set(); let hostConnectionId: string | null = null; let viewerResizeOrder = 0; @@ -924,15 +927,19 @@ const make = Effect.gen(function* () { ): Promise => { const adopted = adoptedPages.get(tabKey(snapshot.threadId, snapshot.tabId)); adoptedPages.delete(tabKey(snapshot.threadId, snapshot.tabId)); - const desktop = + const connection = adopted === undefined && (await desktopRenders(snapshot)) ? await connectDesktop(snapshot) : null; - if (desktop) opened.push(desktop.close); + if (connection) opened.push(connection.close); + // A desktop popup window shares its opener's connection, so closing it closes only its page. + const desktop = + connection ?? + (adopted?.native ? { page: adopted.page, close: () => adopted.page.close() } : null); // Attaching over CDP emulates a light scheme; a tab on System follows the desktop's. if (desktop) await desktop.page.emulateMedia({ colorScheme: null }); // Otherwise a desktop that attaches late, or has no channel to draw it, shows its own page. - if (!desktop) { + if (!connection) { await runPromise( manager .markHeadless({ threadId: ThreadId.make(snapshot.threadId), tabId: snapshot.tabId }) @@ -1088,7 +1095,7 @@ const make = Effect.gen(function* () { if (!desktop) void recordFrameCopies(tab, frame); }); // An adopted popup's frames may have loaded before the tab listened. - if (adopted) for (const frame of page.frames()) void recordFrameCopies(tab, frame); + if (adopted && !desktop) for (const frame of page.frames()) void recordFrameCopies(tab, frame); page.on("requestfailed", (request) => { const errorText = request.failure()?.errorText ?? ""; pushBounded(tab.networkEntries, { @@ -1496,8 +1503,10 @@ const make = Effect.gen(function* () { }; const adoptPopup = async (opener: ServerTab, popup: Page) => { + // A native desktop window is the person's too; a refused adoption leaves it open. + const native = opener.desktop !== null; if (opener.closing) { - await popup.close().catch(constVoid); + if (!native) await popup.close().catch(constVoid); return; } const url = popup.url(); @@ -1514,10 +1523,13 @@ const make = Effect.gen(function* () { ...(opener.control.agentId === null ? {} : { automationOwner: opener.control.agentId, reveal: false }), + // The popup's page already exists; a desktop webview for the tab would load it again. + ...(native ? { headless: true } : {}), beforePublish: (snapshot) => adoptedPages.set(tabKey(snapshot.threadId, snapshot.tabId), { page: popup, openerTabId: opener.tabId, + native, }), }), ).then( @@ -1525,7 +1537,7 @@ const make = Effect.gen(function* () { if (opener.control.agentId === null) controller?.push({ _tag: "popup", tabId: tab.tabId }); }, async () => { - await popup.close().catch(constVoid); + if (!native) await popup.close().catch(constVoid); }, ); }; From 3c81808ad124a97770dffa17db123faea5ff7b96 Mon Sep 17 00:00:00 2001 From: Ramavtar Yadav Date: Tue, 17 Nov 2026 00:20:06 +0530 Subject: [PATCH 3/3] fix(desktop): same-origin window.open stays in T3 Browser Keep the Chromium window for opener, but hide it so HyLite is only shown as an in-app Browser tab instead of a second OS window. Co-authored-by: Cursor --- apps/desktop/src/preview/Manager.test.ts | 5 ++++ apps/desktop/src/preview/Manager.ts | 36 +++++++++++++++++++++--- 2 files changed, 37 insertions(+), 4 deletions(-) diff --git a/apps/desktop/src/preview/Manager.test.ts b/apps/desktop/src/preview/Manager.test.ts index 703869333c9bb..ea2a29a942c00 100644 --- a/apps/desktop/src/preview/Manager.test.ts +++ b/apps/desktop/src/preview/Manager.test.ts @@ -106,9 +106,14 @@ describe("previewWindowOpenAction", () => { "https://vdid.sbigeneral.in/", ), ).toBe("popup"); + expect(PreviewManager.previewPopupWindowOptions(disposition).show).toBe(false); } }); + it("still shows a scripted OAuth popup as a real window", () => { + expect(PreviewManager.previewPopupWindowOptions("new-window").show).not.toBe(false); + }); + it("still opens a cross-origin target=_blank link in a preview tab", () => { expect( PreviewManager.previewWindowOpenAction( diff --git a/apps/desktop/src/preview/Manager.ts b/apps/desktop/src/preview/Manager.ts index 5311df1effc4a..ad002118c9d19 100644 --- a/apps/desktop/src/preview/Manager.ts +++ b/apps/desktop/src/preview/Manager.ts @@ -476,14 +476,33 @@ const IN_PLACE_DENIED_PROTOCOLS = new Set([ ]); /** Popups bypass will-attach-webview hardening and would inherit the picker's contextIsolation:false. */ +const POPUP_WEB_PREFERENCES = { + contextIsolation: true, + nodeIntegration: false, + sandbox: true, +} satisfies Electron.WebPreferences; + const POPUP_WINDOW_OPTIONS = { + webPreferences: POPUP_WEB_PREFERENCES, +} satisfies Electron.BrowserWindowConstructorOptions; + +/** Same-origin tab opens stay off-screen; T3 Browser hosts the page so opener can survive. */ +const HIDDEN_POPUP_WINDOW_OPTIONS = { + show: false, + skipTaskbar: true, webPreferences: { - contextIsolation: true, - nodeIntegration: false, - sandbox: true, + ...POPUP_WEB_PREFERENCES, + backgroundThrottling: false, }, } satisfies Electron.BrowserWindowConstructorOptions; +export const previewPopupWindowOptions = ( + disposition: Electron.HandlerDetails["disposition"], +): Electron.BrowserWindowConstructorOptions => + disposition === "foreground-tab" || disposition === "background-tab" + ? HIDDEN_POPUP_WINDOW_OPTIONS + : POPUP_WINDOW_OPTIONS; + const isSameOriginHttpUrl = (left: string, right: string): boolean => { const from = URL.parse(left); const to = URL.parse(right); @@ -1554,6 +1573,12 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function window.webContents.on("before-input-event", (_event, input) => { syncMenuShortcuts(window.webContents, input); }); + // A same-origin tab open is shown in T3 Browser; keep the native window off-screen. + if (!window.isVisible()) { + window.on("show", () => { + if (!window.isDestroyed()) window.hide(); + }); + } browserHost.openedPopup(wc, window.webContents); }; const findForwardedShortcut = (keys: Parameters[0]) => @@ -1670,7 +1695,10 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function const openerUrl = wc.isDestroyed() ? undefined : wc.getURL(); const action = previewWindowOpenAction(details, openerUrl); if (action === "popup") { - return { action: "allow", overrideBrowserWindowOptions: POPUP_WINDOW_OPTIONS }; + return { + action: "allow", + overrideBrowserWindowOptions: previewPopupWindowOptions(details.disposition), + }; } if (action === "deny") return { action: "deny" }; if (action === "new-tab") {