diff --git a/apps/desktop/src/preview/DesktopBrowserHost.ts b/apps/desktop/src/preview/DesktopBrowserHost.ts index 1444e7e9d8a2e..9c432f68bc68f 100644 --- a/apps/desktop/src/preview/DesktopBrowserHost.ts +++ b/apps/desktop/src/preview/DesktopBrowserHost.ts @@ -4,6 +4,7 @@ import { DesktopBrowserCommand, DesktopBrowserEvent, type DesktopBrowserEvent as DesktopBrowserEventType, + type DesktopPopupBlockReason, } from "@t3tools/contracts"; import * as Context from "effect/Context"; import * as NodePath from "node:path"; @@ -32,6 +33,10 @@ export interface DesktopBrowserTabKey { readonly tabId: string; } +export type DesktopPopupCommand = + | { readonly type: "adopt"; readonly key: DesktopBrowserTabKey; readonly popupId: string } + | { readonly type: "close"; readonly key: DesktopBrowserTabKey }; + export interface DesktopBrowserTabDebugger { readonly webContents: Electron.WebContents; readonly debugger: Electron.Debugger; @@ -103,6 +108,16 @@ export class DesktopBrowserHost extends Context.Service< readonly key: DesktopBrowserTabKey; readonly active: boolean; }>; + /** Asks the server to adopt a popup window that `opener`'s page opened. */ + readonly popupOpened: (opener: DesktopBrowserTabKey, popupId: string, url: string) => void; + readonly popupBlocked: ( + opener: DesktopBrowserTabKey, + url: string, + reason: DesktopPopupBlockReason, + ) => void; + /** A popup the server asked for is gone, so its tab will never attach. */ + readonly popupGone: (key: DesktopBrowserTabKey) => void; + readonly popupCommands: Stream.Stream; } >()("@t3tools/desktop/preview/DesktopBrowserHost") {} @@ -118,6 +133,7 @@ export const make = Effect.gen(function* () { readonly key: DesktopBrowserTabKey; readonly active: boolean; }>(); + const popupCommands = yield* PubSub.unbounded(); const runFork = Effect.runForkWith(yield* Effect.context()); const tabs = new Map(); /** Threads whose agent turn runs, by the server's account. */ @@ -496,6 +512,16 @@ export const make = Effect.gen(function* () { else endAgentTurn(command.value.threadId); return; } + // A popup's key attaches only once its window is adopted. + if (command.value.type === "adoptPopup" || command.value.type === "closePopup") { + const key = { threadId: command.value.threadId, tabId: command.value.tabId }; + const popupCommand: DesktopPopupCommand = + command.value.type === "adoptPopup" + ? { type: "adopt", key, popupId: command.value.popupId } + : { type: "close", key }; + runFork(PubSub.publish(popupCommands, popupCommand)); + return; + } const tab = tabs.get(keyOf(command.value)); if (!tab) return; if (command.value.type === "pointer") { @@ -536,9 +562,20 @@ export const make = Effect.gen(function* () { ); }); + // Event URLs travel on every line of the channel; a data: URL can be megabytes. + const eventUrl = (url: string) => url.slice(0, 2048); + return DesktopBrowserHost.of({ pointers: Stream.fromPubSub(pointers), painting: Stream.fromPubSub(painting), + popupCommands: Stream.fromPubSub(popupCommands), + popupOpened: (opener, popupId, url) => + emit({ type: "popup", ...opener, popupId, url: eventUrl(url) }), + popupBlocked: (opener, url, reason) => + emit({ type: "popupBlocked", ...opener, url: eventUrl(url), reason }), + popupGone: (key) => { + if (!tabs.has(keyOf(key))) emit({ type: "detached", ...key }); + }, // Subscribes before announcing, so no attach falls between the two. events: Stream.unwrap( Effect.gen(function* () { diff --git a/apps/desktop/src/preview/Manager.test.ts b/apps/desktop/src/preview/Manager.test.ts index 26a6386a9abd2..5168bf4891414 100644 --- a/apps/desktop/src/preview/Manager.test.ts +++ b/apps/desktop/src/preview/Manager.test.ts @@ -130,15 +130,54 @@ describe("previewWindowOpenAction", () => { } }); - it("denies a blank window instead of blanking the opener", () => { - for (const url of ["about:blank", ""]) { - for (const disposition of ["new-window", "foreground-tab"] as const) { - expect(PreviewManager.previewWindowOpenAction(details({ url, disposition }))).toBe("deny"); - } + it("opens a blank window as a popup, so a page can point it at sign-in through the handle", () => { + for (const disposition of ["new-window", "foreground-tab", "background-tab"] as const) { + expect( + PreviewManager.previewWindowOpenAction(details({ url: "about:blank", disposition })), + ).toBe("popup"); } }); }); +describe("popupWindowBounds", () => { + const display = { x: 1800, y: 25, width: 2560, height: 1415 }; + + it("centres the size the page asked for over the T3 window, not where the page placed it", () => { + expect( + PreviewManager.popupWindowBounds({ + host: { x: 2010, y: 266, width: 1100, height: 780 }, + workArea: display, + // Firebase's signInWithPopup features, positioned for the whole screen. + features: "location=yes,resizable=yes,toolbar=no,width=500,height=600,top=405,left=2310,", + }), + ).toEqual({ x: 2310, y: 356, width: 500, height: 600 }); + expect( + PreviewManager.popupWindowBounds({ + host: { x: 2010, y: 266, width: 1100, height: 780 }, + workArea: display, + features: "", + }), + ).toEqual({ x: 2160, y: 356, width: 800, height: 600 }); + }); + + it("keeps the popup on the T3 window's display", () => { + expect( + PreviewManager.popupWindowBounds({ + host: { x: 1800, y: 25, width: 400, height: 300 }, + workArea: display, + features: "width=500,height=660", + }), + ).toEqual({ x: 1800, y: 25, width: 500, height: 660 }); + expect( + PreviewManager.popupWindowBounds({ + host: { x: 0, y: 25, width: 1440, height: 875 }, + workArea: { x: 0, y: 25, width: 1440, height: 875 }, + features: "width=3000,height=2000", + }), + ).toEqual({ x: 0, y: 25, width: 1440, height: 875 }); + }); +}); + const { browserWindowConstructor, clipboardItemConstructor, diff --git a/apps/desktop/src/preview/Manager.ts b/apps/desktop/src/preview/Manager.ts index 8c0904199921d..e9fda61a4d94f 100644 --- a/apps/desktop/src/preview/Manager.ts +++ b/apps/desktop/src/preview/Manager.ts @@ -32,6 +32,7 @@ import { type Session, clipboard, nativeImage, + screen, shell, webContents, } from "electron"; @@ -409,6 +410,14 @@ interface PickSession { readonly cancel: Effect.Effect; } +/** The window can be created before or after the server names its tab; it attaches once both exist. */ +interface PopupWindow { + window: BrowserWindow | null; + webContentsId: number | null; + key: DesktopBrowserHost.DesktopBrowserTabKey | null; + attached: boolean; +} + const decodeAnnotationVoiceEvent = Schema.decodeUnknownOption( DesktopPreviewAnnotationVoiceEventSchema, ); @@ -434,7 +443,7 @@ type PointerEventListener = (event: DesktopPreviewPointerEvent) => Effect.Effect type OpenLinkListener = (event: DesktopPreviewOpenLinkEvent) => Effect.Effect; -// about:blank inherits relaxed guest preferences; external editor schemes must reach the OS handler. +// External editor schemes must reach the OS handler. const POPUP_PROTOCOLS = new Set(["http:", "https:"]); // Main-process loadURL bypasses Chromium's renderer-side restrictions on local and inline URLs. @@ -467,8 +476,9 @@ export const previewWindowOpenAction = (details: { readonly disposition: Electron.HandlerDetails["disposition"]; readonly postBody?: Electron.PostBody; }): "popup" | "new-tab" | "navigate" | "deny" => { + // Sign-in SDKs open a blank popup inside the click, then set its location; null reads as blocked. + if (details.url === "about:blank" && !details.postBody) return "popup"; 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"; @@ -478,6 +488,32 @@ export const previewWindowOpenAction = (details: { : "navigate"; }; +/** Electron's size for a `window.open` that names none. */ +const DEFAULT_POPUP_SIZE = { width: 800, height: 600 }; + +/** Centres a popup over the window that hosts its opener, inside that window's display. */ +export const popupWindowBounds = (input: { + readonly host: Electron.Rectangle; + readonly workArea: Electron.Rectangle; + readonly features: string; +}): Electron.Rectangle => { + const feature = (name: "width" | "height") => { + const value = new RegExp(`(?:^|,)\\s*${name}\\s*=\\s*(\\d+)`, "i").exec(input.features)?.[1]; + return value === undefined ? DEFAULT_POPUP_SIZE[name] : Number(value); + }; + const { host, workArea } = input; + const width = Math.min(feature("width"), workArea.width); + const height = Math.min(feature("height"), workArea.height); + const centre = (start: number, span: number, size: number, min: number, room: number) => + Math.round(Math.min(Math.max(start + (span - size) / 2, min), min + room - size)); + return { + x: centre(host.x, host.width, width, workArea.x, workArea.width), + y: centre(host.y, host.height, height, workArea.y, workArea.height), + width, + height, + }; +}; + const isPreviewRefreshShortcut = (input: Electron.Input, platform: NodeJS.Platform): boolean => input.type === "keyDown" && input.key.toLowerCase() === "r" && @@ -581,6 +617,10 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function { readonly semaphore: Semaphore.Semaphore; users: number } >(); const tabLifecycleGenerations = new Map(); + /** Popup windows of server-driven tabs, by the id the server echoes back to adopt one. */ + const popupWindows = new Map(); + let popupSequence = 0; + const runSync = Effect.runSyncWith(context); const attempt = (errorContext: PreviewOperationContext, evaluate: () => A) => Effect.try({ @@ -1016,9 +1056,91 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function browserHost.detach(tab.serverTab); } } + for (const popup of popupWindows.values()) { + if (popup.attached && popup.key && popup.webContentsId === control.webContentsId) { + popup.attached = false; + browserHost.detach(popup.key); + } + } yield* Scope.close(control.scope, Exit.void).pipe(Effect.ignore); }); + const attachPopupWindow = Effect.fn("PreviewManager.attachPopupWindow")( + function* (popup: PopupWindow) { + const { window, key } = popup; + if (!window || !key || popup.attached || window.isDestroyed()) return; + const control = yield* ensureControlSession(window.webContents); + if (window.isDestroyed()) return; + popup.attached = true; + browserHost.attach(key, { webContents: window.webContents, debugger: control.debugger }); + }, + (effect, popup) => + effect.pipe( + Effect.catch((error) => + Effect.logWarning("Could not drive a preview popup window.", { error }).pipe( + Effect.andThen(Effect.sync(() => popup.key && browserHost.popupGone(popup.key))), + ), + ), + ), + ); + + const adoptPopupWindow = Effect.fn("PreviewManager.adoptPopupWindow")(function* ( + key: DesktopBrowserHost.DesktopBrowserTabKey, + popupId: string, + ) { + const popup = popupWindows.get(popupId); + if (!popup) { + browserHost.popupGone(key); + return; + } + popup.key = key; + yield* attachPopupWindow(popup); + }); + + const closePopupWindow = (key: DesktopBrowserHost.DesktopBrowserTabKey) => { + for (const popup of popupWindows.values()) { + if (popup.key?.threadId !== key.threadId || popup.key.tabId !== key.tabId) continue; + if (popup.window && !popup.window.isDestroyed()) popup.window.close(); + } + }; + + const popupHostWindow = (guest: Electron.WebContents) => { + const host = guest.hostWebContents; + const window = + (host && !host.isDestroyed() ? BrowserWindow.fromWebContents(host) : null) ?? + currentMainWindow; + return window && !window.isDestroyed() ? window : undefined; + }; + + /** Runs as Electron creates the window, so it is placed and hardened before it first shows. */ + const createPopupWindow = ( + options: Electron.BrowserWindowConstructorOptions, + popupId: string | undefined, + ) => { + const window = new BrowserWindow(options); + const contents = window.webContents; + const popup = popupId === undefined ? undefined : popupWindows.get(popupId); + contents.setIgnoreMenuShortcuts(true); + // Without a handler, Electron allows every window a popup opens; denying bounds the chain. + contents.setWindowOpenHandler((details) => { + if (popup?.attached && popup.key) browserHost.popupBlocked(popup.key, details.url, "nested"); + return { action: "deny" }; + }); + if (popup && popupId !== undefined) { + popup.window = window; + popup.webContentsId = contents.id; + window.once("closed", () => { + popupWindows.delete(popupId); + if (popup.key && popup.attached) browserHost.detach(popup.key); + else if (popup.key) browserHost.popupGone(popup.key); + popup.attached = false; + if (popup.webContentsId !== null) runFork(detachControlSession(popup.webContentsId)); + }); + if (popup.key) runFork(attachPopupWindow(popup)); + } + return { window, contents }; + }; + const ensureControlSession = Effect.fn("PreviewManager.ensureControlSession")(function* ( wc: Electron.WebContents, ) { @@ -1450,13 +1572,43 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function !isPreviewEditingShortcut(input, hostPlatform) || !holdsKeyboardFocus(contents), ); }; - // Popups inherit Electron's unrestricted window handler; block nested popups to bound the chain. - const windowCreated = (window: Electron.BrowserWindow): void => { - window.webContents.setIgnoreMenuShortcuts(true); - window.webContents.setWindowOpenHandler(() => ({ action: "deny" })); - window.webContents.on("before-input-event", (_event, input) => { - syncMenuShortcuts(window.webContents, input); - }); + const serverTabOf = () => runSync(SynchronizedRef.get(tabsRef)).get(tabId)?.serverTab; + // The page's own position is for its screen; centred over T3, the user sees what the agent drives. + const openPopup = (details: Electron.HandlerDetails): Electron.WindowOpenHandlerResponse => { + const opener = serverTabOf(); + const popupId = opener === undefined ? undefined : `popup-${++popupSequence}`; + if (opener !== undefined && popupId !== undefined) { + popupWindows.set(popupId, { + window: null, + webContentsId: null, + key: null, + attached: false, + }); + browserHost.popupOpened(opener, popupId, details.url); + } + const host = popupHostWindow(wc); + const hostBounds = host?.getBounds(); + return { + action: "allow", + overrideBrowserWindowOptions: { + ...POPUP_WINDOW_OPTIONS, + ...(host && hostBounds + ? { + parent: host, + ...popupWindowBounds({ + host: hostBounds, + workArea: screen.getDisplayMatching(hostBounds).workArea, + features: details.features, + }), + } + : {}), + }, + createWindow: (options) => { + const { contents } = createPopupWindow(options, popupId); + contents.on("before-input-event", (_event, input) => syncMenuShortcuts(contents, input)); + return contents; + }, + }; }; const beforeInput = (event: Electron.Event, input: Electron.Input): void => { syncMenuShortcuts(wc, input); @@ -1526,7 +1678,6 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function wc.off("dom-ready", restoreRecordingCursor); wc.off("did-fail-load", failed as never); wc.off("audio-state-changed", audioStateChanged); - wc.off("did-create-window", windowCreated); wc.off("before-input-event", beforeInput); wc.ipc.off(HUMAN_INPUT_CHANNEL, humanInput); wc.ipc.off(RECORDING_INPUT_CHANNEL, recordingInput); @@ -1553,10 +1704,12 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function detachPasskeys = passkeys.attachGuest(wc); wc.setWindowOpenHandler((details) => { const action = previewWindowOpenAction(details); - if (action === "popup") { - return { action: "allow", overrideBrowserWindowOptions: POPUP_WINDOW_OPTIONS }; + if (action === "popup") return openPopup(details); + if (action === "deny") { + const opener = serverTabOf(); + if (opener) browserHost.popupBlocked(opener, details.url, "scheme"); + return { action: "deny" }; } - if (action === "deny") return { action: "deny" }; if (action === "new-tab") { runFork( emitOpenLink({ @@ -1574,7 +1727,6 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function ); return { action: "deny" }; }); - wc.on("did-create-window", windowCreated); wc.on("before-input-event", beforeInput); }); yield* Ref.update(attachedRef, (attached) => @@ -3312,6 +3464,14 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function [ browserHost.pointers.pipe(Stream.runForEach(emitAgentPointer), listen), browserHost.painting.pipe(Stream.runForEach(updateServerTabCapturing), listen), + browserHost.popupCommands.pipe( + Stream.runForEach((command) => + command.type === "adopt" + ? adoptPopupWindow(command.key, command.popupId) + : Effect.sync(() => closePopupWindow(command.key)), + ), + listen, + ), ], { discard: true }, ); diff --git a/apps/server/src/mcp/McpDevHarness.ts b/apps/server/src/mcp/McpDevHarness.ts index 67b7971236933..506cc7e68d99f 100644 --- a/apps/server/src/mcp/McpDevHarness.ts +++ b/apps/server/src/mcp/McpDevHarness.ts @@ -18,6 +18,9 @@ import type * as McpInvocationContext from "./McpInvocationContext.ts"; /** The provider instance id the harness acts as; the agent cursor labels it "Dev harness". */ const DEV_HARNESS_ID = "dev-harness"; +/** Preview tools act as a real thread, so the harness names one it started. */ +const DEV_HARNESS_THREAD_HEADER = "x-t3-dev-harness-thread"; + const LOOPBACK_ADDRESSES = new Set(["127.0.0.1", "::1"]); const FORWARDING_HEADERS = ["forwarded", "x-forwarded-for", "x-real-ip"]; @@ -25,25 +28,27 @@ const devHarnessScope = ( environmentId: EnvironmentId, sessionId: string, issuedAt: number, + threadId: string, ): McpInvocationContext.McpThreadInvocationScope => ({ environmentId, requestNamespace: `${DEV_HARNESS_ID}:${sessionId}`, thread: { - threadId: ThreadId.make(DEV_HARNESS_ID), + threadId: ThreadId.make(threadId), providerSessionId: sessionId, providerInstanceId: ProviderInstanceId.make(DEV_HARNESS_ID), + devHarness: true, }, client: undefined, // Computer use is reached through the orchestration capability. - capabilities: new Set(["orchestration"]), + capabilities: new Set(["orchestration", "preview"]), issuedAt, }); /** - * Dev servers only: lets `scripts/computer-use-dev.ts` call `/mcp` with an admin environment - * token, so an agent outside the app drives computer use through the backend holding the macOS - * grants. Loopback only: a proxy such as `tailscale serve` adds forwarding headers and is refused. - * Each environment session is its own caller, so its snapshot receipts carry over. + * Dev servers only: lets `scripts/computer-use-dev.ts` drive computer use and preview tabs over + * `/mcp` with an admin environment token. Loopback only: a proxy such as `tailscale serve` adds + * forwarding headers and is refused. Each environment session is its own caller, so its + * snapshot receipts carry over. */ export const makeResolve = Effect.gen(function* () { // Optional so upstream's transport tests, which build the middleware without them, need no harness wiring. @@ -76,6 +81,11 @@ export const makeResolve = Effect.gen(function* () { .authenticateHttpRequest(request) .pipe(Effect.orElseSucceed(() => undefined)); if (!session?.scopes.includes(AuthAccessWriteScope)) return undefined; - return devHarnessScope(environmentId, session.sessionId, yield* Clock.currentTimeMillis); + return devHarnessScope( + environmentId, + session.sessionId, + yield* Clock.currentTimeMillis, + request.headers[DEV_HARNESS_THREAD_HEADER] || DEV_HARNESS_ID, + ); }); }); diff --git a/apps/server/src/mcp/McpInvocationContext.ts b/apps/server/src/mcp/McpInvocationContext.ts index 842d18ad9c8bc..61e78aba36c87 100644 --- a/apps/server/src/mcp/McpInvocationContext.ts +++ b/apps/server/src/mcp/McpInvocationContext.ts @@ -29,6 +29,8 @@ export interface McpThreadCaller { readonly providerInstanceId: ProviderInstanceId; /** A delegated child task; its parent owns the work it hands back. */ readonly subagent?: boolean; + /** `McpDevHarness` on a dev server: acts as the thread from outside any run. */ + readonly devHarness?: boolean; } export interface McpClientCaller { diff --git a/apps/server/src/mcp/threadAccess.ts b/apps/server/src/mcp/threadAccess.ts index 4bf90f0182fc4..2fc32973f7443 100644 --- a/apps/server/src/mcp/threadAccess.ts +++ b/apps/server/src/mcp/threadAccess.ts @@ -139,7 +139,7 @@ export const isLiveCallerShell = ( /** Thread callers need a live run or its background subagent in an unarchived thread. OAuth clients rely on their session and ceiling. */ export function assertLiveCaller({ caller, scope }: Caller) { - if (caller === undefined) return Effect.void; + if (caller === undefined || scope.thread?.devHarness === true) return Effect.void; return isLiveCallerShell(caller, scope.thread?.providerInstanceId) ? Effect.void : Effect.fail( diff --git a/apps/server/src/mcp/toolkits/preview/tools.ts b/apps/server/src/mcp/toolkits/preview/tools.ts index a32c8613d819b..4b148c397dd19 100644 --- a/apps/server/src/mcp/toolkits/preview/tools.ts +++ b/apps/server/src/mcp/toolkits/preview/tools.ts @@ -10,6 +10,7 @@ import { PreviewAutomationEvaluateInput, PreviewAutomationNavigateInput, PreviewAutomationOpenInput, + PreviewAutomationPopups, PreviewAutomationRecordingArtifact, PreviewAutomationRecordingStatus, PreviewAutomationResizeInput, @@ -44,7 +45,9 @@ const PreviewToolFailure = Schema.Union([PreviewAutomationError, OrchestratorMcp const presentationFields = { toolIcon: Schema.optional(ToolActivityIcon) }; -const PreviewActionResult = Schema.Struct(presentationFields); +const popupFields = { popups: PreviewAutomationPopups }; + +const PreviewActionResult = Schema.Struct({ ...presentationFields, ...popupFields }); const browserTool = (tool: T): T => tool.annotate(Tool.OpenWorld, true).annotate(Tool.Destructive, true) as T; @@ -194,7 +197,11 @@ const PreviewActTool = browserTool( "Act on the chosen tab. Target with `locator='aria-ref='` from `preview_snapshot`; `x` and `y` go together. `timeoutMs` defaults to 15000. click: `button`, `clickCount` 1 to 3. type: literal `text`, `clear=true` replaces it. hover: shows menus or tooltips. select: `values` in one native . press: one `key`, such as 'Enter', with `modifiers`, to the focused element; click a field first to focus it. scroll: the tab, or one container with a locator; positive `deltaY` scrolls down, positive `deltaX` right.", parameters: PreviewAutomationActInput, success: Schema.Union([ - Schema.Struct({ ...PreviewAutomationSelectResult.fields, ...presentationFields }), + Schema.Struct({ + ...PreviewAutomationSelectResult.fields, + ...presentationFields, + ...popupFields, + }), PreviewActionResult, ]), failure: PreviewToolFailure, diff --git a/apps/server/src/preview/DesktopBrowserChannel.test.ts b/apps/server/src/preview/DesktopBrowserChannel.test.ts index ab5464cc4f6f7..5114bbc695812 100644 --- a/apps/server/src/preview/DesktopBrowserChannel.test.ts +++ b/apps/server/src/preview/DesktopBrowserChannel.test.ts @@ -2,6 +2,7 @@ import * as NodeServices from "@effect/platform-node/NodeServices"; import * as NodeStream from "@effect/platform-node/NodeStream"; import { expect, it } from "@effect/vitest"; import * as Effect from "effect/Effect"; +import * as Fiber from "effect/Fiber"; import * as Layer from "effect/Layer"; import * as Queue from "effect/Queue"; import * as Stream from "effect/Stream"; @@ -17,16 +18,41 @@ vi.mock("node:net", () => ({ }, })); -it.effect("protects unknown desktop visibility until an explicit hidden report arrives", () => +/** Runs `test` against a channel whose desktop events are the lines `send` writes. */ +const withChannel = ( + test: ( + channel: DesktopBrowserChannel.DesktopBrowserChannel["Service"], + send: (event: object) => Effect.Effect, + ) => Effect.Effect, +) => Effect.gen(function* () { const input = yield* Queue.unbounded(); vi.mocked(NodeStream.fromReadable).mockReturnValue(Stream.fromQueue(input)); const config = yield* ServerConfig.ServerConfig; - yield* Effect.gen(function* () { - const channel = yield* DesktopBrowserChannel.DesktopBrowserChannel; + const send = (event: object) => + Queue.offer(input, new TextEncoder().encode(`${JSON.stringify(event)}\n`)); + return yield* DesktopBrowserChannel.DesktopBrowserChannel.pipe( + Effect.flatMap((channel) => test(channel, send)), + Effect.provide( + DesktopBrowserChannel.layer.pipe( + Layer.provide( + ServerConfig.layer({ ...config, desktopBrowserFd: 41, desktopBrowserControlFd: 42 }), + ), + ), + ), + ); + }).pipe( + Effect.provide( + ServerConfig.layerTest(process.cwd(), { prefix: "desktop-browser-channel-" }).pipe( + Layer.provide(NodeServices.layer), + ), + ), + ); + +it.effect("protects unknown desktop visibility until an explicit hidden report arrives", () => + withChannel((channel, send) => + Effect.gen(function* () { const key = { threadId: "thread-1", tabId: "tab-1" }; - const send = (event: object) => - Queue.offer(input, new TextEncoder().encode(`${JSON.stringify(event)}\n`)); expect(channel.isShown(key)).toBe(true); yield* send({ type: "attached", ...key }); @@ -48,20 +74,20 @@ it.effect("protects unknown desktop visibility until an explicit hidden report a yield* send({ type: "attached", threadId: key.threadId, tabId: "sentinel-3" }); yield* channel.awaitAttached({ threadId: key.threadId, tabId: "sentinel-3" }, "5 seconds"); expect(channel.isShown(key)).toBe(true); - }).pipe( - Effect.provide( - DesktopBrowserChannel.layer.pipe( - Layer.provide( - ServerConfig.layer({ ...config, desktopBrowserFd: 41, desktopBrowserControlFd: 42 }), - ), - ), - ), - ); - }).pipe( - Effect.provide( - ServerConfig.layerTest(process.cwd(), { prefix: "desktop-browser-channel-" }).pipe( - Layer.provide(NodeServices.layer), - ), - ), + }), + ), +); + +it.effect("a popup window that closes before its tab attaches ends the wait for it", () => + withChannel((channel, send) => + Effect.gen(function* () { + const key = { threadId: "thread-1", tabId: "popup-tab" }; + // The test clock never reaches the timeout, so only the detach can end this wait. + const waiting = yield* channel + .awaitAttached(key, "1 minute") + .pipe(Effect.forkChild({ startImmediately: true })); + yield* send({ type: "detached", ...key }); + expect(yield* Fiber.join(waiting)).toBe(false); + }), ), ); diff --git a/apps/server/src/preview/DesktopBrowserChannel.ts b/apps/server/src/preview/DesktopBrowserChannel.ts index 65129274206da..cb3fc235489d8 100644 --- a/apps/server/src/preview/DesktopBrowserChannel.ts +++ b/apps/server/src/preview/DesktopBrowserChannel.ts @@ -6,6 +6,7 @@ import { DesktopBrowserCommand, DesktopBrowserEvent, type DesktopBrowserCommand as DesktopBrowserCommandType, + type DesktopPopupBlockReason, } from "@t3tools/contracts"; import * as Context from "effect/Context"; import * as Duration from "effect/Duration"; @@ -33,6 +34,14 @@ export interface DesktopTabKey { readonly tabId: string; } +export type DesktopPopupEvent = + | { readonly opener: DesktopTabKey; readonly url: string; readonly popupId: string } + | { + readonly opener: DesktopTabKey; + readonly url: string; + readonly blocked: DesktopPopupBlockReason; + }; + const keyOf = ({ threadId, tabId }: DesktopTabKey) => `${threadId}\u0000${tabId}`; export class DesktopBrowserChannel extends Context.Service< @@ -53,6 +62,11 @@ export class DesktopBrowserChannel extends Context.Service< ) => Effect.Effect; /** Never fails. A failed write means a broken channel; the next backend starts with no turns. */ readonly turn: (threadId: string, active: boolean) => Effect.Effect; + /** Windows a desktop tab's page opened, or asked for and was refused. */ + readonly popups: Stream.Stream; + /** The desktop attaches popup `popupId` as tab `key`, which then reports `attached`. */ + readonly adoptPopup: (key: DesktopTabKey, popupId: string) => Effect.Effect; + readonly closePopup: (key: DesktopTabKey) => Effect.Effect; } >()("t3/preview/DesktopBrowserChannel") {} @@ -88,8 +102,16 @@ const make = Effect.gen(function* () { return Effect.void; }), isShown: () => false, + popups: Stream.empty, + adoptPopup: Effect.fn("DesktopBrowserChannel.adoptPopup")(function () { + return Effect.void; + }), + closePopup: Effect.fn("DesktopBrowserChannel.closePopup")(function () { + return Effect.void; + }), }); } + const popups = yield* PubSub.unbounded(); const command = (message: DesktopBrowserCommandType) => writeLock.withPermits(1)( @@ -137,6 +159,14 @@ const make = Effect.gen(function* () { case "shown": shownTabs.set(id, event.shown); return Effect.void; + case "popup": + return PubSub.publish(popups, { + opener: key, + url: event.url, + popupId: event.popupId, + }); + case "popupBlocked": + return PubSub.publish(popups, { opener: key, url: event.url, blocked: event.reason }); } }), Effect.catchCause((cause) => Effect.logWarning("desktop browser channel stopped", { cause })), @@ -210,10 +240,11 @@ const make = Effect.gen(function* () { Effect.gen(function* () { const subscription = yield* PubSub.subscribe(changes); if (attachedTabs.has(keyOf(key))) return true; + // A detach before any attach is a popup window that closed before it was adopted. return yield* Stream.fromSubscription(subscription).pipe( - Stream.filter((change) => change.attached && keyOf(change.key) === keyOf(key)), + Stream.filter((change) => keyOf(change.key) === keyOf(key)), Stream.runHead, - Effect.map(Option.isSome), + Effect.map((change) => Option.isSome(change) && change.value.attached), Effect.timeoutOption(timeout), Effect.map((result) => Option.getOrElse(result, () => false)), ); @@ -239,6 +270,13 @@ const make = Effect.gen(function* () { pointer: Effect.fn("DesktopBrowserChannel.pointer")(function (key, pointer) { return command({ type: "pointer", ...key, ...pointer }); }), + popups: Stream.fromPubSub(popups), + adoptPopup: Effect.fn("DesktopBrowserChannel.adoptPopup")(function (key, popupId) { + return command({ type: "adoptPopup", ...key, popupId }); + }), + closePopup: Effect.fn("DesktopBrowserChannel.closePopup")(function (key) { + return command({ type: "closePopup", ...key }); + }), }); }); diff --git a/apps/server/src/preview/Manager.ts b/apps/server/src/preview/Manager.ts index f5db1d2fefc1e..0691863c1fbaa 100644 --- a/apps/server/src/preview/Manager.ts +++ b/apps/server/src/preview/Manager.ts @@ -35,6 +35,7 @@ export class PreviewManager extends Context.Service< readonly open: ( input: PreviewOpenInput & { readonly automationOwner?: string; + readonly openerTabId?: string; /** Runs before the `opened` event publishes, so subscribers find state keyed by the tab. */ readonly beforePublish?: (snapshot: PreviewSessionSnapshot) => void; }, @@ -193,6 +194,7 @@ export const make = Effect.gen(function* PreviewManagerMake() { ? { automationOwner: input.automationOwner } : {}), ...(input.reveal === undefined ? {} : { reveal: input.reveal }), + ...(input.openerTabId === undefined ? {} : { openerTabId: input.openerTabId }), updatedAt, }; yield* SynchronizedRef.modifyEffect(stateRef, (state) => diff --git a/apps/server/src/preview/ServerBrowser.test.ts b/apps/server/src/preview/ServerBrowser.test.ts index 898f2de7df77d..6aa6d8ce4ea45 100644 --- a/apps/server/src/preview/ServerBrowser.test.ts +++ b/apps/server/src/preview/ServerBrowser.test.ts @@ -219,6 +219,7 @@ function makeContext(onClose?: (context: BrowserContext) => void, initialUrl = " interactiveElements: [], })), ariaSnapshot: vi.fn(async () => '- button "delete" [ref=e1]'), + keyboard: { press: vi.fn(async (_key: string) => {}) }, locator: vi.fn(() => { throw new Error("Unexpected locator action"); }), @@ -324,6 +325,8 @@ const desktopRenders = (tabId: string) => { const shownDesktopTabs = new Set(); const releasedDesktopTabs: Array = []; const desktopTurns = new NodeEvents.EventEmitter(); +/** `popup` events from the desktop; `adopt` and `close` commands back to it. */ +const desktopPopups = new NodeEvents.EventEmitter(); const desktopConnections: Array<{ endpoint: string; context: ReturnType }> = []; const testThread = { threadId: ThreadId.make("browser-test-thread"), @@ -391,6 +394,24 @@ const dependencies = Layer.mergeAll( ), pointer: () => Effect.void, turn: (threadId, active) => Effect.sync(() => desktopTurns.emit("turn", threadId, active)), + popups: Stream.callback((queue) => + Effect.acquireRelease( + Effect.sync(() => { + const onPopup = (event: DesktopChannel.DesktopPopupEvent) => + Queue.offerUnsafe(queue, event); + desktopPopups.on("popup", onPopup); + return onPopup; + }), + (onPopup) => Effect.sync(() => desktopPopups.off("popup", onPopup)), + ), + ), + // The desktop attaches the adopted window, so the popup's tab renders on the desktop. + adoptPopup: (key, popupId) => + Effect.sync(() => { + desktopTabs.add(key.tabId); + desktopPopups.emit("adopt", { tabId: key.tabId, popupId }); + }), + closePopup: (key) => Effect.sync(() => desktopPopups.emit("close", key.tabId)), }), PreviewAgentActivity.layer, ).pipe( @@ -700,6 +721,116 @@ it.effect("a tab the desktop does not draw is marked headless, so the desktop st ).pipe(Effect.provide(layer)), ); +it.live("a desktop tab's popup window becomes a tab, named by the action that opened it", () => + Effect.scoped( + Effect.gen(function* () { + const { broker } = yield* ready; + const manager = yield* Manager.PreviewManager; + desktopRendersNext = true; + const opened = yield* broker.invoke({ + scope, + operation: "open", + input: { reuseExistingTab: false, show: false }, + }); + const openerTabId = PreviewTabId.make(opened.tabId!); + const opener = { threadId: scope.thread.threadId, tabId: openerTabId }; + const adoptions: Array<{ tabId: string; popupId: string }> = []; + const adopted = (popupId: string) => + new Promise((resolve) => { + const onAdopt = (adoption: { tabId: string; popupId: string }) => { + adoptions.push(adoption); + if (adoption.popupId !== popupId) return; + desktopPopups.off("adopt", onAdopt); + resolve(adoption.tabId); + }; + desktopPopups.on("adopt", onAdopt); + }); + const signIn = adopted("popup-1"); + desktopConnections[0]!.context.page.keyboard.press.mockImplementationOnce(async () => { + desktopPopups.emit("popup", { opener, url: "data:text/html,

hi

", blocked: "scheme" }); + desktopPopups.emit("popup", { opener, url: "https://idp.example/sso", popupId: "popup-1" }); + // The desktop announces a window before the input that opened it settles. + await signIn; + }); + + const pressed = yield* broker.invoke<{ popups?: ReadonlyArray }>({ + scope, + tabId: openerTabId, + operation: "press", + input: { key: "Enter" }, + }); + const popupTabId = yield* Effect.promise(() => signIn); + + expect(pressed.popups).toEqual([ + { url: "data:text/html,…", openerTabId, error: expect.stringContaining("got null") }, + { url: "https://idp.example/sso", openerTabId, tabId: popupTabId }, + ]); + expect(adoptions).toEqual([{ tabId: popupTabId, popupId: "popup-1" }]); + const listed = (yield* manager.list({ threadId: scope.thread.threadId })).sessions; + const openerSession = listed.find((session) => session.tabId === openerTabId); + expect(listed.find((session) => session.tabId === popupTabId)).toMatchObject({ + openerTabId, + reveal: false, + automationOwner: openerSession?.automationOwner, + }); + expect(listed.find((session) => session.tabId === popupTabId)).not.toHaveProperty("headless"); + const status = yield* broker.invoke({ + scope, + tabId: openerTabId, + operation: "status", + input: {}, + }); + expect(status.tabs).toContainEqual( + expect.objectContaining({ tabId: popupTabId, openerTabId }), + ); + // The popup's tab runs through its own window's debugger. + yield* broker.invoke({ scope, tabId: popupTabId, operation: "snapshot", input: {} }); + expect(desktopConnections.map(({ endpoint }) => endpoint)).toContain( + `ws://desktop/${popupTabId}`, + ); + const snapshot = yield* broker.invoke({ + scope, + tabId: openerTabId, + operation: "snapshot", + input: {}, + }); + expect(snapshot.consoleEntries).toContainEqual( + expect.objectContaining({ level: "warning", source: "t3" }), + ); + + // The page calls window.close() after signing in: its tab ends and the opener stays. + const events = yield* manager.subscribeEvents; + desktopDetaches.emit("detach", { threadId: scope.thread.threadId, tabId: popupTabId }); + let event = yield* PubSub.take(events); + while (event.type !== "closed" || event.tabId !== popupTabId) { + event = yield* PubSub.take(events); + } + const remaining = yield* broker.invoke({ + scope, + tabId: openerTabId, + operation: "status", + input: {}, + }); + expect(remaining.tabs?.map((tab) => tab.tabId)).toContain(openerTabId); + expect(remaining.tabs?.map((tab) => tab.tabId)).not.toContain(popupTabId); + + // Closing a popup's tab closes its window. + const second = adopted("popup-2"); + desktopPopups.emit("popup", { opener, url: "https://idp.example/sso", popupId: "popup-2" }); + const secondTabId = yield* Effect.promise(() => second); + const closed = Promise.withResolvers(); + desktopPopups.once("close", closed.resolve); + yield* broker.invoke({ + scope, + tabId: PreviewTabId.make(secondTabId), + operation: "close", + input: {}, + }); + expect(yield* Effect.promise(() => closed.promise)).toBe(secondTabId); + }), + ).pipe(Effect.provide(layer)), +); + it.effect("a desktop page that loaded before the server attached reports its loaded title", () => Effect.scoped( Effect.gen(function* () { diff --git a/apps/server/src/preview/ServerBrowser.ts b/apps/server/src/preview/ServerBrowser.ts index 3d816d414d6bb..aa34776ff950a 100644 --- a/apps/server/src/preview/ServerBrowser.ts +++ b/apps/server/src/preview/ServerBrowser.ts @@ -10,6 +10,7 @@ import { INCOGNITO_BROWSER_PROFILE_ID, resolveBrowserProfiles, type BrowserProfile, + type DesktopPopupBlockReason, type PreviewReportProfilesInput, PREVIEW_AUTOMATION_SERVER_OPERATIONS, PreviewViewportSetting as PreviewViewportSettingSchema, @@ -24,6 +25,7 @@ import { type PreviewAutomationNavigateInput, type PreviewAutomationNetworkEntry, type PreviewAutomationOpenInput, + type PreviewAutomationPopup, type PreviewAutomationPressInput, type PreviewAutomationRequest, type PreviewAutomationResizeInput, @@ -99,6 +101,29 @@ const SCREENCAST_MOTION_WINDOW_MS = 300; const SCREENCAST_MOTION_QUALITY = 50; const HOST_RECONNECT_DELAY = "1 second"; const DESKTOP_ATTACH_TIMEOUT = "10 seconds"; +const POPUP_REPORT_LIMIT = 8; +const POPUP_BLOCK_REASONS = { + scheme: "T3 opens popups only for web pages and about:blank, so the page got null.", + nested: "A popup cannot open another window, so the page got null.", +} as const; +/** + * Results that name the windows a tab's page opened: actions, and the reads that follow one, + * since sign-in SDKs often call `window.open` after an await, once the click has returned. + */ +const POPUP_REPORTING_OPERATIONS: ReadonlySet = new Set([ + "click", + "hover", + "select", + "drag", + "upload", + "type", + "press", + "scroll", + "observe", + "snapshot", + "waitFor", +]); +const POPUP_URL_CHARS = 500; const VIEWER_OUTPUT_LIMIT = 64; const RECORDING_SCREENCAST = { format: "jpeg", quality: 90, everyNthFrame: 1 } as const; const decodeViewportSetting = Schema.decodeUnknownSync(PreviewViewportSettingSchema); @@ -312,6 +337,10 @@ interface ServerTab { readonly desktop: { readonly close: () => Promise } | null; readonly profileId: string | undefined; readonly openerTabId: string | undefined; + /** A desktop popup's own window draws it, and nothing reconnects it, so it ends with its tab. */ + readonly desktopPopup: boolean; + /** Windows this tab's page opened that no result has named yet. */ + readonly popupReports: Array; readonly downloads: Array; fileChooser: { @@ -346,6 +375,12 @@ interface ServerTab { capturing: number; } +interface PopupReport { + readonly url: string; + /** Settles once the popup is a tab or has failed to become one. */ + readonly settled: Promise; +} + interface ServerDownload { readonly id: string; readonly fileName: string; @@ -497,7 +532,9 @@ const make = Effect.gen(function* () { >(); const closedPendingTabs = new Set(); - const adoptedPages = new Map(); + const adoptedPages = new Map(); + /** Opened for a desktop popup window, which must attach rather than fall back to headless. */ + const desktopPopupTabs = new Set(); const closedSessions = new Set(); let hostConnectionId: string | null = null; let viewerResizeOrder = 0; @@ -744,12 +781,16 @@ const make = Effect.gen(function* () { const sessionOpen = (tab: ServerTab) => !closedSessions.has(tabKey(tab.threadId, tab.tabId)); - const dropTab = (tab: ServerTab, closeSession: boolean) => { + const dropTab = (tab: ServerTab, closeSessionRequested: boolean) => { const key = tabKey(tab.threadId, tab.tabId); if (tabs.get(key) !== tab) return; tabs.delete(key); tab.closing = true; clearAbortedNavigation(tab); + const closeSession = closeSessionRequested || tab.desktopPopup; + if (tab.desktopPopup) { + runFork(desktopChannel.closePopup({ threadId: tab.threadId, tabId: tab.tabId })); + } // A desktop page outlives the connection unless its session closed with it. const end = tab.desktop && !closeSession && sessionOpen(tab) ? "reconnect" : "gone"; for (const viewer of tab.viewers) viewer.push({ _tag: end }); @@ -812,13 +853,17 @@ const make = Effect.gen(function* () { snapshot: PreviewSessionSnapshot, opened: Array<() => Promise>, ): Promise => { - const adopted = adoptedPages.get(tabKey(snapshot.threadId, snapshot.tabId)); - adoptedPages.delete(tabKey(snapshot.threadId, snapshot.tabId)); + const key = tabKey(snapshot.threadId, snapshot.tabId); + const adopted = adoptedPages.get(key); + adoptedPages.delete(key); + const desktopPopup = desktopPopupTabs.delete(key); const desktop = adopted === undefined && (await desktopRenders(snapshot)) ? await connectDesktop(snapshot) : null; if (desktop) opened.push(desktop.close); + // A headless copy would load the page without its opener. + if (desktopPopup && !desktop) throw new Error("The popup window closed before it opened."); // Otherwise a desktop that attaches late shows its own page, and the agent drives another. if (!desktop && desktopChannel.available) { await runPromise( @@ -833,16 +878,16 @@ const make = Effect.gen(function* () { ((snapshot.automationOwner !== undefined && snapshot.profileId === undefined) || snapshot.profileId === INCOGNITO_BROWSER_PROFILE_ID); const context = - adopted?.page.context() ?? + adopted?.context() ?? desktop?.page.context() ?? (await contexts.contextFor( snapshot.profileId ?? "default", isolatedContext ? tabKey(snapshot.threadId, snapshot.tabId) : undefined, )); if (isolatedContext) opened.push(() => context.close()); - if (adopted?.page.isClosed()) throw new Error("The popup closed before it opened."); + if (adopted?.isClosed()) throw new Error("The popup closed before it opened."); if (!desktop) await prepareContext(context); - const page = adopted?.page ?? desktop?.page ?? (await context.newPage()); + const page = adopted ?? desktop?.page ?? (await context.newPage()); if (!desktop) opened.push(() => page.close()); const cdp = await context.newCDPSession(page); await installPdfDocumentNavigation(cdp); @@ -879,7 +924,9 @@ const make = Effect.gen(function* () { isolatedContext, desktop: desktop === null ? null : { close: desktop.close }, profileId: snapshot.profileId, - openerTabId: adopted?.openerTabId, + openerTabId: snapshot.openerTabId, + desktopPopup: desktop !== null && snapshot.openerTabId !== undefined, + popupReports: [], downloads: [], fileChooser: null, dialog: null, @@ -1014,7 +1061,6 @@ const make = Effect.gen(function* () { // Popups become tabs and keep `window.opener`, so sign-in popups can report back. page.on("popup", (popup) => void adoptPopup(tab, popup)); // Playwright cannot reload a crashed page, so it must leave the tab list. - const key = tabKey(tab.threadId, tab.tabId); if (closedPendingTabs.delete(key)) { await control.close().catch(constVoid); throw new ServerBrowserTabNotFoundError({ threadId: tab.threadId, tabId: tab.tabId }); @@ -1338,6 +1384,69 @@ const make = Effect.gen(function* () { return copies.flat().find((text) => text.length > 0); }; + /** The next result for the opener names the popup: its tab, or why it is not one. */ + const reportPopup = (opener: ServerTab, url: string, opening: Promise) => { + const reported = { url: ServerBrowserPage.withoutDataPayload(url).slice(0, POPUP_URL_CHARS) }; + pushBounded( + opener.popupReports, + { + ...reported, + settled: opening.then( + (tab) => ({ ...reported, openerTabId: opener.tabId, tabId: tab.tabId }), + (cause: unknown) => ({ + ...reported, + openerTabId: opener.tabId, + error: `The popup could not become a tab: ${ServerBrowserPage.toOperationError(cause).message}`, + }), + ), + }, + POPUP_REPORT_LIMIT, + ); + }; + + const reportBlockedPopup = (opener: ServerTab, url: string, reason: DesktopPopupBlockReason) => { + const error = POPUP_BLOCK_REASONS[reason]; + const shownUrl = ServerBrowserPage.withoutDataPayload(url).slice(0, POPUP_URL_CHARS); + pushBounded(opener.consoleEntries, { + level: "warning", + text: `T3 blocked window.open(${JSON.stringify(shownUrl)}). ${error}`, + timestamp: new Date().toISOString(), + source: "t3", + }); + const blocked = { url: shownUrl, openerTabId: opener.tabId, error }; + pushBounded( + opener.popupReports, + { url: shownUrl, settled: Promise.resolve(blocked) }, + POPUP_REPORT_LIMIT, + ); + }; + + /** The desktop keeps the window, with its opener, and drives it as a new tab once attached. */ + const adoptDesktopPopup = async (opener: ServerTab, popupId: string, url: string) => { + const opening = runPromise( + openTab( + { + threadId: opener.threadId, + ...(/^https?:/i.test(url) ? { url } : {}), + runtime: "server", + ...(opener.profileId === undefined ? {} : { profileId: opener.profileId }), + ...(opener.control.agentId === null ? {} : { automationOwner: opener.control.agentId }), + // Its own window shows it; switching the panel to a stream of it would only repeat it. + reveal: false, + openerTabId: opener.tabId, + beforePublish: (snapshot) => { + const key = { threadId: snapshot.threadId, tabId: snapshot.tabId }; + desktopPopupTabs.add(tabKey(key.threadId, key.tabId)); + runFork(desktopChannel.adoptPopup(key, popupId)); + }, + }, + { reclaimIdleSlot: true }, + ), + ); + reportPopup(opener, url, opening); + await opening.catch(constVoid); + }; + const adoptPopup = async (opener: ServerTab, popup: Page) => { if (opener.closing) { await popup.close().catch(constVoid); @@ -1348,7 +1457,7 @@ const make = Effect.gen(function* () { const controller = [...opener.viewers].find( (viewer) => viewer.id === opener.control.controller, ); - await runPromise( + const opening = runPromise( openTab( { threadId: opener.threadId, @@ -1358,16 +1467,16 @@ const make = Effect.gen(function* () { ...(opener.control.agentId === null ? {} : { automationOwner: opener.control.agentId, reveal: false }), + openerTabId: opener.tabId, beforePublish: (snapshot) => - adoptedPages.set(tabKey(snapshot.threadId, snapshot.tabId), { - page: popup, - openerTabId: opener.tabId, - }), + adoptedPages.set(tabKey(snapshot.threadId, snapshot.tabId), popup), }, // An agent's popup is an open it asked for, so it may reclaim an idle slot too. { reclaimIdleSlot: true }, ), - ).then( + ); + reportPopup(opener, url, opening); + await opening.then( (tab) => { if (opener.control.agentId === null) controller?.push({ _tag: "popup", tabId: tab.tabId }); }, @@ -2184,7 +2293,7 @@ const make = Effect.gen(function* () { return executeTabOperation(tab, request); }); } - return tab.control.agent( + const result = await tab.control.agent( agentSessionId, async () => { if (tab.dialog) @@ -2206,6 +2315,33 @@ const make = Effect.gen(function* () { }, deadlineMs, ); + return POPUP_REPORTING_OPERATIONS.has(request.operation) + ? withPopupReports(tab, result, deadlineMs) + : result; + }; + + /** Outside the opener's queue: a popup's tab sets up on its own connection. */ + const withPopupReports = async (tab: ServerTab, result: unknown, deadlineMs: number) => { + const reports = tab.popupReports.splice(0); + if (reports.length === 0) return result; + let timer: ReturnType | undefined; + // Leaves the broker time to deliver the reply before its own timeout. + const late = new Promise((resolve) => { + timer = setTimeout(resolve, Math.max(0, deadlineMs - performance.now() - 500)); + }); + const popups = await Promise.all( + reports.map((report) => + Promise.race([ + report.settled, + late.then((): PreviewAutomationPopup => ({ + url: report.url, + openerTabId: tab.tabId, + error: "It was still opening; its tab will show in preview_status tabs.", + })), + ]), + ), + ).finally(() => clearTimeout(timer)); + return { ...(typeof result === "object" && result !== null ? result : {}), popups }; }; const executeTabOperation = async (tab: ServerTab, request: PreviewAutomationRequest) => { @@ -2793,6 +2929,20 @@ const make = Effect.gen(function* () { ), Effect.forkScoped, ); + // With no tab for its opener, a popup stays a plain window that only the user can use. + yield* desktopChannel.popups.pipe( + Stream.runForEach((event) => + Effect.promise(async () => { + const key = tabKey(event.opener.threadId, event.opener.tabId); + const opener = + tabs.get(key) ?? (await pendingTabs.get(key)?.promise?.catch(constVoid)) ?? undefined; + if (!opener || opener.closing) return; + if ("blocked" in event) reportBlockedPopup(opener, event.url, event.blocked); + else void adoptDesktopPopup(opener, event.popupId, event.url); + }), + ), + Effect.forkScoped, + ); // The desktop keeps the tabs an agent uses focused until its turn ends, not just per command. yield* Stream.fromSubscription(agentTurns).pipe( Stream.runForEach((change) => desktopChannel.turn(change.threadId, change.active)), diff --git a/apps/web/src/browser/previewRuntime.test.ts b/apps/web/src/browser/previewRuntime.test.ts new file mode 100644 index 0000000000000..c152ec7b4f76a --- /dev/null +++ b/apps/web/src/browser/previewRuntime.test.ts @@ -0,0 +1,17 @@ +import { EnvironmentId } from "@t3tools/contracts"; +import { describe, expect, it, vi } from "vite-plus/test"; + +vi.mock(import("~/env"), async (original) => ({ ...(await original()), isElectron: true })); + +import { rendersServerTabNatively } from "./previewRuntime"; + +describe("rendersServerTabNatively", () => { + const primary = EnvironmentId.make("primary"); + + it("leaves a desktop popup to the window its page opened, which alone keeps the opener", () => { + expect(rendersServerTabNatively(primary, primary, { runtime: "server" })).toBe(true); + expect( + rendersServerTabNatively(primary, primary, { runtime: "server", openerTabId: "tab_1" }), + ).toBe(false); + }); +}); diff --git a/apps/web/src/browser/previewRuntime.ts b/apps/web/src/browser/previewRuntime.ts index 7ca4a8a8f6995..c4318fa0d1343 100644 --- a/apps/web/src/browser/previewRuntime.ts +++ b/apps/web/src/browser/previewRuntime.ts @@ -44,12 +44,14 @@ export function usePreviewAvailable(environmentId: EnvironmentId | null): boolea export function rendersServerTabNatively( environmentId: EnvironmentId, primaryEnvironmentId: EnvironmentId | null, - snapshot: Pick | null | undefined, + snapshot: Pick | null | undefined, ): boolean { return ( isElectron && snapshot?.runtime === "server" && !snapshot.headless && + // A popup keeps its opener only in the window the page opened; a webview would be a second page. + snapshot.openerTabId === undefined && primaryEnvironmentId !== null && environmentId === primaryEnvironmentId ); @@ -57,7 +59,7 @@ export function rendersServerTabNatively( export function useRendersServerTabNatively( environmentId: EnvironmentId, - snapshot: Pick | null | undefined, + snapshot: Pick | null | undefined, ): boolean { return rendersServerTabNatively(environmentId, useAtomValue(primaryEnvironmentIdAtom), snapshot); } diff --git a/docs/operations/development.md b/docs/operations/development.md index 89a84515f1db0..f5f783f2fd293 100644 --- a/docs/operations/development.md +++ b/docs/operations/development.md @@ -267,11 +267,14 @@ node scripts/computer-use-dev.ts bakeoff # 11 tasks on a back node scripts/computer-use-dev.ts snapshot Calculator node scripts/computer-use-dev.ts action '{"steps":[{"ref":12,"action":"click"}]}' node scripts/computer-use-dev.ts snapshot TextEdit --image /tmp/textedit.png +node scripts/computer-use-dev.ts preview --thread preview_open '{"url":"https://example.com"}' ``` It reads the server origin from the main checkout's `.t3` (override with `--home`), issues a day-long admin session for itself, and keeps the token in the system temp directory. -`action` defaults to the latest snapshot the harness took. Only development servers accept +`action` defaults to the latest snapshot the harness took. `preview` calls one `preview_*` or +`t3_preview_*` tool as the dev database thread `--thread` names, with no run in progress, and +the dev desktop app draws those tabs like any thread's. Only development servers accept the harness, and only over direct loopback requests. Computer access must be enabled in the app's settings, with the target app allowed. A `vp run dev:server` started from a T3 Code terminal also has the grants, since macOS credits them to the app that started the shell; pass diff --git a/packages/contracts/src/desktopBrowser.ts b/packages/contracts/src/desktopBrowser.ts index 52fb66885adfe..985c07b929448 100644 --- a/packages/contracts/src/desktopBrowser.ts +++ b/packages/contracts/src/desktopBrowser.ts @@ -7,6 +7,10 @@ const TabKey = { tabId: TrimmedNonEmptyString, }; +/** `scheme`: a URL no hardened window can load. `nested`: a popup's own popup. */ +export const DesktopPopupBlockReason = Schema.Literals(["scheme", "nested"]); +export type DesktopPopupBlockReason = typeof DesktopPopupBlockReason.Type; + export const DesktopBrowserEvent = Schema.Union([ Schema.Struct({ type: Schema.Literal("attached"), ...TabKey }), /** Its `` went away: closed, crashed, swapped, or devtools took the debugger. */ @@ -14,6 +18,20 @@ export const DesktopBrowserEvent = Schema.Union([ Schema.Struct({ type: Schema.Literal("cdp"), ...TabKey, message: Schema.String }), /** Its `` started or stopped being on screen in a desktop window. */ Schema.Struct({ type: Schema.Literal("shown"), ...TabKey, shown: Schema.Boolean }), + /** Its page opened a popup window; the window keeps its opener and waits for `adoptPopup`. */ + Schema.Struct({ + type: Schema.Literal("popup"), + ...TabKey, + popupId: TrimmedNonEmptyString, + url: Schema.String, + }), + /** Its page asked for a window the desktop refused, so `window.open` returned null. */ + Schema.Struct({ + type: Schema.Literal("popupBlocked"), + ...TabKey, + url: Schema.String, + reason: DesktopPopupBlockReason, + }), ]); export type DesktopBrowserEvent = typeof DesktopBrowserEvent.Type; @@ -33,5 +51,9 @@ export const DesktopBrowserCommand = Schema.Union([ threadId: TrimmedNonEmptyString, active: Schema.Boolean, }), + /** Attach the waiting popup window as this tab. */ + Schema.Struct({ type: Schema.Literal("adoptPopup"), ...TabKey, popupId: TrimmedNonEmptyString }), + /** This popup tab's session ended; close its window. */ + Schema.Struct({ type: Schema.Literal("closePopup"), ...TabKey }), ]); export type DesktopBrowserCommand = typeof DesktopBrowserCommand.Type; diff --git a/packages/contracts/src/preview.ts b/packages/contracts/src/preview.ts index 1790a4797db29..1aacf1801482e 100644 --- a/packages/contracts/src/preview.ts +++ b/packages/contracts/src/preview.ts @@ -162,6 +162,8 @@ export const PreviewSessionSnapshot = Schema.Struct({ runtime: Schema.optional(PreviewRuntime), /** The server runs this tab in headless Chromium, so the desktop streams it like other clients. */ headless: Schema.optional(Schema.Boolean), + /** A popup that tab's page opened. A desktop popup has its own window, so clients stream it. */ + openerTabId: Schema.optional(PreviewTabId), automationOwner: Schema.optional(Schema.String), reveal: Schema.optional(Schema.Boolean), revealRequest: Schema.optional(Schema.Struct({ id: Schema.String, force: Schema.Boolean })), diff --git a/packages/contracts/src/previewAutomation.ts b/packages/contracts/src/previewAutomation.ts index 2dc695341196f..6913f15c3cdeb 100644 --- a/packages/contracts/src/previewAutomation.ts +++ b/packages/contracts/src/previewAutomation.ts @@ -86,6 +86,22 @@ export const PreviewAutomationObserveInput = Schema.Struct({ }); export type PreviewAutomationObserveInput = typeof PreviewAutomationObserveInput.Type; +export const PreviewAutomationPopup = Schema.Struct({ + url: Schema.String, + openerTabId: PreviewTabId, + tabId: Schema.optional(PreviewTabId), + error: Schema.optional(Schema.String), +}); +export type PreviewAutomationPopup = typeof PreviewAutomationPopup.Type; + +/** Windows the tab's page opened since an earlier result last named one. */ +export const PreviewAutomationPopups = Schema.optional( + Schema.Array(PreviewAutomationPopup), +).annotate({ + description: + "Windows the page opened. Act on one by its tabId; `error` says why one is not a tab.", +}); + const ObservationFields = { revision: Schema.String, refPrefix: Schema.String, @@ -94,6 +110,7 @@ const ObservationFields = { loading: Schema.Boolean, readiness: Schema.Literals(["dom_quiet", "budget_exhausted"]), truncated: Schema.Boolean, + popups: PreviewAutomationPopups, }; export const PreviewAutomationObservation = Schema.Union([ Schema.Struct({ ...ObservationFields, mode: Schema.Literal("full"), tree: Schema.String }), @@ -606,6 +623,7 @@ export const PreviewAutomationSnapshot = Schema.Struct({ fullScreenshot: Schema.optional( Schema.Struct({ data: Schema.String, width: Schema.Int, height: Schema.Int }), ), + popups: PreviewAutomationPopups, }); export type PreviewAutomationSnapshot = typeof PreviewAutomationSnapshot.Type; diff --git a/scripts/computer-use-dev.ts b/scripts/computer-use-dev.ts index 19936a8924621..e9af00e010d3c 100644 --- a/scripts/computer-use-dev.ts +++ b/scripts/computer-use-dev.ts @@ -126,6 +126,7 @@ const run = Effect.fn("computerUseDev.run")(function* (program: string, args: st const makeHarness = Effect.fn("computerUseDev.makeHarness")(function* ( homeFlag: Option.Option, + threadId?: string, ) { const fs = yield* FileSystem.FileSystem; const path = yield* Path.Path; @@ -191,6 +192,7 @@ const makeHarness = Effect.fn("computerUseDev.makeHarness")(function* ( authorization: `Bearer ${token}`, accept: "application/json, text/event-stream", ...(sessionId ? { "mcp-session-id": sessionId, "mcp-protocol-version": "2025-06-18" } : {}), + ...(threadId ? { "x-t3-dev-harness-thread": threadId } : {}), }), HttpClientRequest.bodyJson(body), Effect.flatMap(httpClient.execute), @@ -367,6 +369,32 @@ const action = Command.make( }), ); +const preview = Command.make( + "preview", + { + home, + image, + thread: Flag.String("thread").pipe( + Flag.withDescription( + "Thread the tool acts as, such as one from `t3 thread start --provider devReplay`.", + ), + ), + tool: Argument.String("tool").pipe( + Argument.withDescription("A preview tool, such as preview_open or t3_preview_list."), + ), + input: Argument.String("input").pipe( + Argument.withDescription("The tool's input as JSON. Defaults to {}."), + Argument.optional, + ), + }, + Effect.fn(function* ({ home, image, thread, tool, input }) { + if (!/^(?:t3_)?preview_\w+$/.test(tool)) return yield* fail(`${tool} is not a preview tool.`); + const harness = yield* makeHarness(home, thread); + const args = Option.isSome(input) ? yield* decodeJson(input.value) : {}; + yield* report(yield* harness.call(tool, args), image); + }), +); + const CALCULATOR_BUTTONS = [ ["All Clear", "Clear", "AC", "C"], ["7"], @@ -817,8 +845,10 @@ const bakeoff = Command.make( ); const main = Command.make("computer-use-dev").pipe( - Command.withDescription("Call the running dev app's computer-use tools as the Dev harness."), - Command.withSubcommands([status, open, snapshot, action, smoke, bakeoff]), + Command.withDescription( + "Call the running dev app's computer-use and preview tools as the Dev harness.", + ), + Command.withSubcommands([status, open, snapshot, action, preview, smoke, bakeoff]), ); if (import.meta.main) {