TypeScript
feat(web): float device streams over chat (#11285)
Julius Marminge8bbe2bf660c3
diff --git a/apps/web/src/components/ChatView.logic.test.ts b/apps/web/src/components/ChatView.logic.test.tsindex 973dd574902..ae0cdc8581f 100644--- a/apps/web/src/components/ChatView.logic.test.ts+++ b/apps/web/src/components/ChatView.logic.test.ts@@ -126,7 +126,7 @@ describe("floating browser preview", () => {const ref = scopeThreadRef(EnvironmentId.make("env-1"), ThreadId.make("thread-1"));const panels = useRightPanelStore.getState();const revision = panels.getUserActionRevision(ref);- usePreviewMiniPlayerStore.getState().open(ref, "agent-tab");+ usePreviewMiniPlayerStore.getState().open(ref, { kind: "browser", tabId: "agent-tab" });panels.reconcileBrowserSurfaces(ref, ["agent-tab"]);const intent = selectThreadPreviewMiniPlayer(usePreviewMiniPlayerStore.getState().byThreadKey,@@ -135,7 +135,7 @@ describe("floating browser preview", () => {const isFloating = () =>shouldRenderPreviewMiniPlayer(selectThreadPreviewMiniPlayer(usePreviewMiniPlayerStore.getState().byThreadKey, ref)- ?.tabId ?? null,+ ?.source ?? null,selectActiveRightPanelSurface(useRightPanelStore.getState().byThreadKey, ref),);@@ -152,22 +152,61 @@ describe("floating browser preview", () => {});it("only hides the duplicate while the same browser is rendered in the panel", () => {+ const tab = { kind: "browser", tabId: "tab-1" } as const;expect(shouldRenderPreviewMiniPlayer(null, null)).toBe(false);expect(- shouldRenderPreviewMiniPlayer("tab-1", {+ shouldRenderPreviewMiniPlayer(tab, {id: "browser:one",kind: "preview",resourceId: "tab-1",}),).toBe(false);expect(- shouldRenderPreviewMiniPlayer("tab-1", {+ shouldRenderPreviewMiniPlayer(tab, {id: "browser:two",kind: "preview",resourceId: "tab-2",}),).toBe(true);- expect(shouldRenderPreviewMiniPlayer("tab-1", { id: "diff", kind: "diff" })).toBe(true);+ expect(shouldRenderPreviewMiniPlayer(tab, { id: "diff", kind: "diff" })).toBe(true);+ });++ it("only hides a floating device while that device is rendered in the panel", () => {+ const pixel = {+ kind: "device",+ hostId: "nucbox",+ deviceId: "emulator-5580",+ platform: "android",+ name: "Pixel",+ } as const;+ const target = {+ hostId: "nucbox",+ deviceId: "emulator-5580",+ platform: "android",+ name: "Pixel",+ } as const;+ expect(+ shouldRenderPreviewMiniPlayer(pixel, {+ id: "device:nucbox:emulator-5580",+ kind: "device",+ target,+ }),+ ).toBe(false);+ expect(+ shouldRenderPreviewMiniPlayer(pixel, {+ id: "device:nucbox:emulator-5554",+ kind: "device",+ target: { ...target, deviceId: "emulator-5554" },+ }),+ ).toBe(true);+ expect(shouldRenderPreviewMiniPlayer(pixel, { id: "device", kind: "device" })).toBe(true);+ expect(+ shouldRenderPreviewMiniPlayer(pixel, {+ id: "browser:one",+ kind: "preview",+ resourceId: "emulator-5580",+ }),+ ).toBe(true);});});diff --git a/apps/web/src/components/ChatView.logic.ts b/apps/web/src/components/ChatView.logic.tsindex 772a0f3cf2f..b6bb98b4c50 100644--- a/apps/web/src/components/ChatView.logic.ts+++ b/apps/web/src/components/ChatView.logic.ts@@ -50,6 +50,7 @@ import {import type { DraftThreadEnvMode } from "../composerDraftStore";import type { ComposerSubmissionIntent } from "../composer-logic";import type { TimelineEntry } from "../session-logic";+import type { PreviewMiniPlayerSource } from "../previewMiniPlayerStore";import type { DesktopPreviewOverlay } from "../previewStateStore";import type { RightPanelSurface } from "../rightPanelStore";import {@@ -88,16 +89,22 @@ export function agentControlledBrowserCloseConfirmation(].join("\n");}+/** The floating player hides only while the same source is rendered in the panel. */export function shouldRenderPreviewMiniPlayer(- miniPlayerTabId: string | null,+ source: PreviewMiniPlayerSource | null,renderedRightPanelSurface: RightPanelSurface | null,): boolean {- return (- miniPlayerTabId !== null &&- !(+ if (source === null) return false;+ if (source.kind === "browser") {+ return !(renderedRightPanelSurface?.kind === "preview" &&- renderedRightPanelSurface.resourceId === miniPlayerTabId- )+ renderedRightPanelSurface.resourceId === source.tabId+ );+ }+ return !(+ renderedRightPanelSurface?.kind === "device" &&+ renderedRightPanelSurface.target?.hostId === source.hostId &&+ renderedRightPanelSurface.target.deviceId === source.deviceId);}diff --git a/apps/web/src/components/ChatView.tsx b/apps/web/src/components/ChatView.tsxindex fc529b02a73..0e786ae54af 100644--- a/apps/web/src/components/ChatView.tsx+++ b/apps/web/src/components/ChatView.tsx@@ -195,6 +195,8 @@ import {useSidebarPendingFileDropStore,} from "../sidebarPendingFileDropStore";import {+ browserMiniPlayerSource,+ previewMiniPlayerSourceKey,selectThreadPreviewMiniPlayer,usePreviewMiniPlayerStore,} from "../previewMiniPlayerStore";@@ -566,6 +568,8 @@ const PreviewPanel = lazy(() =>import("./preview/PreviewPanel").then((module) => ({ default: module.PreviewPanel })),);const DiffPanel = lazy(() => import("./DiffPanel"));+const selectAutoShowFloatingPreview = (settings: { browserAutoShowFloatingPreview: boolean }) =>+ settings.browserAutoShowFloatingPreview;const DevicePanel = lazy(() =>import("./device/DevicePanel").then((module) => ({ default: module.DevicePanel })),);@@ -1958,7 +1962,7 @@ export default function ChatView(props: ChatViewProps) {const renderedRightPanelSurface = rightPanelPresence.value?.activeSurface ?? null;const renderedRightPanelSurfaces = rightPanelPresence.value?.surfaces ?? [];const previewMiniPlayerVisible = shouldRenderPreviewMiniPlayer(- activePreviewMiniPlayer?.tabId ?? null,+ activePreviewMiniPlayer?.source ?? null,renderedRightPanelSurface,);const canMaximizeRightPanel = rightPanelOpen && !shouldUseRightPanelSheet;@@ -1974,8 +1978,10 @@ export default function ChatView(props: ChatViewProps) {}, [activePreviewState.sessions, activeThreadRef]);useEffect(() => {- if (!activeThreadRef || !activePreviewMiniPlayer) return;- const miniTabStillExists = Boolean(activePreviewState.sessions[activePreviewMiniPlayer.tabId]);+ if (!activeThreadRef || activePreviewMiniPlayer?.source.kind !== "browser") return;+ const miniTabStillExists = Boolean(+ activePreviewState.sessions[activePreviewMiniPlayer.source.tabId],+ );if (!miniTabStillExists) {usePreviewMiniPlayerStore.getState().close(activeThreadRef);}@@ -4215,9 +4221,13 @@ export default function ChatView(props: ChatViewProps) {}useRightPanelStore.getState().open(activeThreadRef, "device");}, [activeThreadRef, deviceState.onboardingCompleted, deviceState.hostStatus]);- // Reconcile new server sessions into separate tabs, including sessions opened- // by an agent or another client. The first snapshot is a baseline: persisted- // tabs restore themselves, and existing sessions must not resurrect closed tabs.+ // A device the agent opens floats over chat like an agent-driven browser,+ // or becomes a panel tab when floating previews are off. Sessions opened by+ // another client arrive the same way; sheet layouts get neither. The first+ // snapshot is a baseline: persisted tabs restore themselves, and existing+ // sessions must not resurrect closed tabs. A session whose device summary+ // has not arrived yet stays out of the baseline so a later snapshot opens it.+ const autoShowFloatingPreview = useClientSettings(selectAutoShowFloatingPreview);const previousDeviceSessions = useRef(new Map<string, Set<string>>());useEffect(() => {if (!activeThreadRef || !deviceStateLoaded) return;@@ -4226,11 +4236,30 @@ export default function ChatView(props: ChatViewProps) {(session) => session.threadId === activeThreadRef.threadId,);const key = (session: (typeof sessions)[number]) => `${session.hostId}:${session.deviceId}`;+ const deviceFor = (session: (typeof sessions)[number]) =>+ deviceState.devices.find(+ (entry) => entry.hostId === session.hostId && entry.id === session.deviceId,+ );const previous = previousDeviceSessions.current.get(threadKey);- previousDeviceSessions.current.set(threadKey, new Set(sessions.map(key)));+ previousDeviceSessions.current.set(+ threadKey,+ new Set(sessions.filter((session) => deviceFor(session) !== undefined).map(key)),+ );if (!previous || shouldUseRightPanelSheet) return;for (const session of sessions) {- if (previous?.has(key(session))) continue;+ if (previous.has(key(session))) continue;+ const device = deviceFor(session);+ if (!device) continue;+ const target = {+ hostId: session.hostId,+ deviceId: session.deviceId,+ platform: device.platform,+ name: device.name,+ };+ if (autoShowFloatingPreview) {+ usePreviewMiniPlayerStore.getState().open(activeThreadRef, { kind: "device", ...target });+ continue;+ }const existing = useRightPanelStore.getState().byThreadKey[scopedThreadKey(activeThreadRef)]?.surfaces.some(@@ -4240,28 +4269,30 @@ export default function ChatView(props: ChatViewProps) {surface.target.deviceId === session.deviceId,);if (existing) continue;- const device = deviceState.devices.find(- (entry) => entry.hostId === session.hostId && entry.id === session.deviceId,- );- if (!device) continue;- useRightPanelStore.getState().openDevice(- activeThreadRef,- {- hostId: session.hostId,- deviceId: session.deviceId,- platform: device.platform,- name: device.name,- },- true,- );+ useRightPanelStore.getState().openDevice(activeThreadRef, target, true);}}, [activeThreadRef,+ autoShowFloatingPreview,deviceStateLoaded,shouldUseRightPanelSheet,deviceState.sessions,deviceState.devices,]);+ // A floating device follows its session: once the agent or another client+ // closes the device there is nothing left to stream.+ useEffect(() => {+ if (!activeThreadRef || !deviceStateLoaded) return;+ const source = activePreviewMiniPlayer?.source;+ if (source?.kind !== "device") return;+ const sessionStillExists = deviceState.sessions.some(+ (session) =>+ session.threadId === activeThreadRef.threadId &&+ session.hostId === source.hostId &&+ session.deviceId === source.deviceId,+ );+ if (!sessionStillExists) usePreviewMiniPlayerStore.getState().close(activeThreadRef);+ }, [activePreviewMiniPlayer, activeThreadRef, deviceState.sessions, deviceStateLoaded]);const openFileSurface = useCallback((relativePath: string) => {if (!activeThreadRef || !activeProject) return;@@ -4421,10 +4452,15 @@ export default function ChatView(props: ChatViewProps) {]);const closePreviewPanel = useCallback(() => {if (activeThreadRef) {+ // Closing the panel on a live browser or device floats it instead of dropping it.if (activeRightPanelSurface?.kind === "preview" && activeRightPanelSurface.resourceId) {usePreviewMiniPlayerStore.getState()- .open(activeThreadRef, activeRightPanelSurface.resourceId);+ .open(activeThreadRef, browserMiniPlayerSource(activeRightPanelSurface.resourceId));+ } else if (activeRightPanelSurface?.kind === "device" && activeRightPanelSurface.target) {+ usePreviewMiniPlayerStore+ .getState()+ .open(activeThreadRef, { kind: "device", ...activeRightPanelSurface.target });}setMaximizedRightPanelThreadKey(null);useRightPanelStore.getState().close(activeThreadRef);@@ -8834,9 +8870,9 @@ export default function ChatView(props: ChatViewProps) {{activeThreadRef && activePreviewMiniPlayer && previewMiniPlayerVisible ? (<ThreadPreviewMiniPlayer- key={`${activeThreadKey}:${activePreviewMiniPlayer.tabId}`}+ key={`${activeThreadKey}:${previewMiniPlayerSourceKey(activePreviewMiniPlayer.source)}`}threadRef={activeThreadRef}- tabId={activePreviewMiniPlayer.tabId}+ miniPlayer={activePreviewMiniPlayer}bottomInset={isDraftHeroState ? 0 : composerOverlayHeight}/>) : null}diff --git a/apps/web/src/components/device/DevicePanel.tsx b/apps/web/src/components/device/DevicePanel.tsxindex 5b312f7fc4f..950a202a7b9 100644--- a/apps/web/src/components/device/DevicePanel.tsx+++ b/apps/web/src/components/device/DevicePanel.tsx@@ -7,6 +7,7 @@ import type {import {ChevronLeft,Home,+ PictureInPicture2,Power,RotateCcw,SlidersHorizontal,@@ -16,6 +17,7 @@ import {} from "lucide-react";import { useEffect, useMemo, useState } from "react";+import { usePreviewMiniPlayerStore } from "~/previewMiniPlayerStore";import { useRightPanelStore, type RightPanelSurface } from "~/rightPanelStore";import { Button } from "~/components/ui/button";import { DiscoveryList, DiscoveryListRow } from "~/components/ui/discovery-list";@@ -116,6 +118,19 @@ export function DevicePanel(props: {}};+ // Floating the device closes the panel, like the browser's floating preview.+ const floatActive = () => {+ if (!activeDevice) return;+ usePreviewMiniPlayerStore.getState().open(props.threadRef, {+ kind: "device",+ hostId: activeDevice.hostId,+ deviceId: activeDevice.id,+ platform: activeDevice.platform,+ name: activeDevice.name,+ });+ useRightPanelStore.getState().close(props.threadRef);+ };+const closeActive = (powerOff: boolean) => {if (!powerOff) {useRightPanelStore.getState().closeSurface(props.threadRef, props.surface.id);@@ -218,6 +233,9 @@ export function DevicePanel(props: {><SlidersHorizontal /></Toggle>+ <DeviceButton label="Float device over chat" onClick={floatActive}>+ <PictureInPicture2 />+ </DeviceButton><DeviceButton label="Power off" onClick={() => closeActive(true)}><Power /></DeviceButton>diff --git a/apps/web/src/components/preview/PreviewAutomationHosts.tsx b/apps/web/src/components/preview/PreviewAutomationHosts.tsxindex d1fc1282173..a793e8a2c8c 100644--- a/apps/web/src/components/preview/PreviewAutomationHosts.tsx+++ b/apps/web/src/components/preview/PreviewAutomationHosts.tsx@@ -29,7 +29,11 @@ import {reconcilePreviewServerSessions,updatePreviewServerSnapshot,} from "~/previewStateStore";-import { selectThreadPreviewMiniPlayer, usePreviewMiniPlayerStore } from "~/previewMiniPlayerStore";+import {+ browserMiniPlayerSource,+ selectThreadPreviewMiniPlayerTabId,+ usePreviewMiniPlayerStore,+} from "~/previewMiniPlayerStore";import { resolveBrowserNavigationTarget } from "~/browser/browserTargetResolver";import {readActiveBrowserRecordingTargets,@@ -378,7 +382,9 @@ function PreviewAutomationHost(props: { readonly environmentId: EnvironmentId })?.has(runtimeTabId) ?? false,})) {- usePreviewMiniPlayerStore.getState().open(threadRef, readyTabId);+ usePreviewMiniPlayerStore+ .getState()+ .open(threadRef, browserMiniPlayerSource(readyTabId));}}browserActivity.release ??= acquireBrowserSurfaceActivity(runtimeTabId);@@ -493,11 +499,11 @@ function PreviewAutomationHost(props: { readonly environmentId: EnvironmentId })new Set([activeRuntimeTabId]),);}- const miniPlayer = selectThreadPreviewMiniPlayer(+ const miniPlayerTabId = selectThreadPreviewMiniPlayerTabId(usePreviewMiniPlayerStore.getState().byThreadKey,threadRef,);- if (miniPlayer?.tabId === activeTabId) {+ if (miniPlayerTabId === activeTabId) {usePreviewMiniPlayerStore.getState().close(threadRef);}} else if (shouldPresentPreview) {@@ -507,7 +513,9 @@ function PreviewAutomationHost(props: { readonly environmentId: EnvironmentId })}}if (shouldPresentPreview) {- usePreviewMiniPlayerStore.getState().open(threadRef, activeTabId);+ usePreviewMiniPlayerStore+ .getState()+ .open(threadRef, browserMiniPlayerSource(activeTabId));}if (activeSnapshot && previewAutomationOpenNeedsOverlay(input, activeSnapshot)) {await requireReadyTab();diff --git a/apps/web/src/components/preview/PreviewView.test.tsx b/apps/web/src/components/preview/PreviewView.test.tsxindex 2a146834012..ea28a93235e 100644--- a/apps/web/src/components/preview/PreviewView.test.tsx+++ b/apps/web/src/components/preview/PreviewView.test.tsx@@ -171,7 +171,7 @@ vi.mock("~/previewMiniPlayerStore", () => {byThreadKey: mocks.miniPlayerTabId? {"environment-1:thread-1": {- tabId: mocks.miniPlayerTabId,+ source: { kind: "browser", tabId: mocks.miniPlayerTabId },position: null,},}@@ -185,9 +185,10 @@ vi.mock("~/previewMiniPlayerStore", () => {},);return {- selectThreadPreviewMiniPlayer: (- byThreadKey: Record<string, { tabId: string; position: null }>,- ) => byThreadKey["environment-1:thread-1"] ?? null,+ browserMiniPlayerSource: (tabId: string) => ({ kind: "browser", tabId }),+ selectThreadPreviewMiniPlayerTabId: (+ byThreadKey: Record<string, { source: { tabId: string }; position: null }>,+ ) => byThreadKey["environment-1:thread-1"]?.source.tabId ?? null,usePreviewMiniPlayerStore,};});@@ -485,7 +486,10 @@ describe("PreviewView navigation", () => {renderToStaticMarkup(<PreviewView {...props} />);expect(mocks.pictureInPicturePressed).toBe(false);mocks.togglePictureInPicture?.();- expect(mocks.openMiniPlayer).toHaveBeenCalledWith(props.threadRef, "tab-1");+ expect(mocks.openMiniPlayer).toHaveBeenCalledWith(props.threadRef, {+ kind: "browser",+ tabId: "tab-1",+ });expect(mocks.closeRightPanel).toHaveBeenCalledWith(props.threadRef);mocks.miniPlayerTabId = "tab-1";diff --git a/apps/web/src/components/preview/PreviewView.tsx b/apps/web/src/components/preview/PreviewView.tsxindex e6ad2758bc4..6086e049ab1 100644--- a/apps/web/src/components/preview/PreviewView.tsx+++ b/apps/web/src/components/preview/PreviewView.tsx@@ -34,7 +34,11 @@ import { resolveDiscoveredServerUrl } from "~/browser/browserTargetResolver";import { useEnvironmentHttpBaseUrl } from "~/state/environments";import { previewEnvironment } from "~/state/preview";import { useAtomCommand } from "~/state/use-atom-command";-import { selectThreadPreviewMiniPlayer, usePreviewMiniPlayerStore } from "~/previewMiniPlayerStore";+import {+ browserMiniPlayerSource,+ selectThreadPreviewMiniPlayerTabId,+ usePreviewMiniPlayerStore,+} from "~/previewMiniPlayerStore";import { useRightPanelStore } from "~/rightPanelStore";import { previewBridge } from "./previewBridge";@@ -114,8 +118,8 @@ export function PreviewView({threadRef,BROWSER_HISTORY_MAX_ENTRIES_PER_PROJECT,);- const miniPlayer = usePreviewMiniPlayerStore((state) =>- selectThreadPreviewMiniPlayer(state.byThreadKey, threadRef),+ const miniPlayerTabId = usePreviewMiniPlayerStore((state) =>+ selectThreadPreviewMiniPlayerTabId(state.byThreadKey, threadRef),);const addPreviewAnnotation = useComposerDraftStore((store) => store.addPreviewAnnotation);const addImage = useComposerDraftStore((store) => store.addImage);@@ -311,13 +315,13 @@ export function PreviewView({const handlePictureInPicture = useCallback(() => {if (!tabId) return;- if (miniPlayer?.tabId === tabId) {+ if (miniPlayerTabId === tabId) {usePreviewMiniPlayerStore.getState().close(threadRef);return;}- usePreviewMiniPlayerStore.getState().open(threadRef, tabId);+ usePreviewMiniPlayerStore.getState().open(threadRef, browserMiniPlayerSource(tabId));useRightPanelStore.getState().close(threadRef);- }, [miniPlayer?.tabId, tabId, threadRef]);+ }, [miniPlayerTabId, tabId, threadRef]);const handleNativePictureInPicture = useCallback(() => {if (!previewBridge || !runtimeTabId) return;@@ -722,7 +726,7 @@ export function PreviewView({captureDisabled={!desktopOverlay || isUnreachable}recording={recordingRuntimeTabId !== null}onPictureInPicture={previewBridge && tabId ? handlePictureInPicture : undefined}- pictureInPicture={miniPlayer?.tabId === tabId}+ pictureInPicture={miniPlayerTabId === tabId}pictureInPictureDisabled={!desktopOverlay?.hasWebContents || isUnreachable}onPickElement={previewBridge && tabId ? handlePickElement : undefined}pickActive={pickActive}diff --git a/apps/web/src/components/preview/ThreadPreviewMiniPlayer.tsx b/apps/web/src/components/preview/ThreadPreviewMiniPlayer.tsxindex 4384019abba..432e41cb4ab 100644--- a/apps/web/src/components/preview/ThreadPreviewMiniPlayer.tsx+++ b/apps/web/src/components/preview/ThreadPreviewMiniPlayer.tsx@@ -2,7 +2,14 @@import { FILL_PREVIEW_VIEWPORT, type ScopedThreadRef } from "@t3tools/contracts";import { PanelRightIcon, PictureInPicture2, XIcon } from "lucide-react";-import { type PointerEvent as ReactPointerEvent, useLayoutEffect, useRef, useState } from "react";+import {+ type PointerEvent as ReactPointerEvent,+ type ReactNode,+ useCallback,+ useLayoutEffect,+ useRef,+ useState,+} from "react";import { BrowserSurfaceSlot } from "~/browser/BrowserSurfaceSlot";import { useBrowserSurfaceStore } from "~/browser/browserSurfaceStore";@@ -15,17 +22,25 @@ import { cn } from "~/lib/utils";import { useThreadPreviewState } from "~/previewStateStore";import {type PreviewMiniPlayerSize,- selectThreadPreviewMiniPlayer,+ type PreviewMiniPlayerSource,+ type PreviewMiniPlayerState,+ previewMiniPlayerSourceKey,usePreviewMiniPlayerStore,} from "~/previewMiniPlayerStore";import { useRightPanelStore } from "~/rightPanelStore";+import { useDeviceState } from "~/state/device";+import { DeviceStreamView } from "../device/DeviceStreamView";+import type { DeviceScreenSize } from "../device/deviceStream";import { previewBridge } from "./previewBridge";import {clampPreviewMiniPlayerPosition,+ PREVIEW_MINI_PLAYER_CORNER_RADIUS,PREVIEW_MINI_PLAYER_WEBVIEW_Z_INDEX,type PreviewMiniPlayerFrame,resizePreviewMiniPlayer,+ resolveDeviceMiniPlayerCornerRadius,+ resolveDeviceMiniPlayerSourceSize,resolvePreviewMiniPlayerFrame,resolvePreviewMiniPlayerSourceSize,} from "./previewMiniPlayerLayout";@@ -40,11 +55,11 @@ interface PointerGesture {interface Props {readonly threadRef: ScopedThreadRef;- readonly tabId: string;+ readonly miniPlayer: PreviewMiniPlayerState;readonly bottomInset: number;}-const PREVIEW_MINI_PLAYER_CORNER_RADIUS = 12;+const frameCornerRadius = () => PREVIEW_MINI_PLAYER_CORNER_RADIUS;// Invisible grab zones straddling each edge; the cursor is the only affordance.const RESIZE_HANDLES: ReadonlyArray<{@@ -61,17 +76,34 @@ const RESIZE_HANDLES: ReadonlyArray<{{ direction: "southeast", className: "-bottom-2 -right-2 size-4 cursor-nwse-resize" },];-/**- * Floats the thread's browser surface over chat. Native clipping and the DOM- * frame use the same radius so their separately composited edges stay aligned.- */-export function ThreadPreviewMiniPlayer({ threadRef, tabId, bottomInset }: Props) {- const containerRef = useRef<HTMLDivElement | null>(null);- const gestureRef = useRef<PointerGesture | null>(null);- const [container, setContainer] = useState<PreviewMiniPlayerSize | null>(null);- const miniPlayer = usePreviewMiniPlayerStore((state) =>- selectThreadPreviewMiniPlayer(state.byThreadKey, threadRef),+/** Floats the thread's browser tab or device stream over chat. */+export function ThreadPreviewMiniPlayer({ threadRef, miniPlayer, bottomInset }: Props) {+ const { source } = miniPlayer;+ return source.kind === "browser" ? (+ <BrowserMiniPlayer+ key={source.tabId}+ threadRef={threadRef}+ tabId={source.tabId}+ miniPlayer={miniPlayer}+ bottomInset={bottomInset}+ />+ ) : (+ <DeviceMiniPlayer+ key={previewMiniPlayerSourceKey(source)}+ threadRef={threadRef}+ source={source}+ miniPlayer={miniPlayer}+ bottomInset={bottomInset}+ />);+}++function BrowserMiniPlayer({+ threadRef,+ tabId,+ miniPlayer,+ bottomInset,+}: Props & { readonly tabId: string }) {const previewState = useThreadPreviewState(threadRef);const snapshot = previewState.sessions[tabId] ?? null;const runtimeTabId = previewRuntimeTabId(threadRef, previewState.serverEpoch, tabId);@@ -79,25 +111,11 @@ export function ThreadPreviewMiniPlayer({ threadRef, tabId, bottomInset }: Propsconst fittedSourceContent = useBrowserSurfaceStore((state) => state.byTabId[runtimeTabId]?.fittedSourceContent ?? null,);- const source = resolvePreviewMiniPlayerSourceSize(+ const sourceSize = resolvePreviewMiniPlayerSourceSize(snapshot?.viewport ?? FILL_PREVIEW_VIEWPORT,fittedSourceContent,desktopOverlay?.zoomFactor ?? 1,);- const frame =- container && miniPlayer?.tabId === tabId- ? resolvePreviewMiniPlayerFrame({- width: miniPlayer.width,- position: miniPlayer.position,- source,- container,- bottomInset,- })- : null;-- const close = () => {- usePreviewMiniPlayerStore.getState().close(threadRef);- };const openInPanel = () => {usePreviewMiniPlayerStore.getState().close(threadRef);@@ -118,6 +136,176 @@ export function ThreadPreviewMiniPlayer({ threadRef, tabId, bottomInset }: Props});};+ if (!snapshot) return null;++ return (+ <MiniPlayerShell+ threadRef={threadRef}+ miniPlayer={miniPlayer}+ sourceSize={sourceSize}+ bottomInset={bottomInset}+ label="Floating browser preview"+ onOpenInPanel={openInPanel}+ pillActions={+ <Tooltip>+ <TooltipTrigger+ render={+ <Button+ variant={desktopOverlay?.pictureInPicture ? "secondary" : "ghost"}+ size="icon-xs"+ aria-label={+ desktopOverlay?.pictureInPicture+ ? "Close popped-out preview"+ : "Pop preview into separate window"+ }+ disabled={!desktopOverlay?.hasWebContents}+ onPointerDown={(event) => event.stopPropagation()}+ onClick={toggleNativePictureInPicture}+ />+ }+ >+ <PictureInPicture2 />+ </TooltipTrigger>+ <TooltipPopup side="top">+ {desktopOverlay?.pictureInPicture+ ? "Close separate window"+ : "Pop into separate window"}+ </TooltipPopup>+ </Tooltip>+ }+ >+ {(frame) => (+ <>+ <BrowserSurfaceSlot+ tabId={runtimeTabId}+ visible={Boolean(desktopOverlay?.hasWebContents)}+ cornerRadius={PREVIEW_MINI_PLAYER_CORNER_RADIUS}+ zIndex={PREVIEW_MINI_PLAYER_WEBVIEW_Z_INDEX}+ fitSourceContent+ layoutVersion={`${frame.x}:${frame.y}`}+ className="absolute inset-0"+ />+ {!desktopOverlay?.hasWebContents ? (+ <div className="pointer-events-none absolute inset-0 z-[49] flex items-center justify-center rounded-[inherit] bg-muted text-xs text-muted-foreground">+ Reconnecting preview…+ </div>+ ) : null}+ </>+ )}+ </MiniPlayerShell>+ );+}++function DeviceMiniPlayer({+ threadRef,+ source,+ miniPlayer,+ bottomInset,+}: Props & { readonly source: Extract<PreviewMiniPlayerSource, { kind: "device" }> }) {+ const { state: deviceState } = useDeviceState(threadRef.environmentId);+ const [screen, setScreen] = useState<DeviceScreenSize | null>(null);+ const sourceSize = resolveDeviceMiniPlayerSourceSize(source.platform, screen);+ const device = deviceState.devices.find(+ (entry) => entry.hostId === source.hostId && entry.id === source.deviceId,+ );+ const hostLabel =+ deviceState.hosts.find((host) => host.id === source.hostId)?.label ?? "Device host";+ const cornerRadius = useCallback(+ (player: PreviewMiniPlayerSize) => resolveDeviceMiniPlayerCornerRadius(source.platform, player),+ [source.platform],+ );++ const openInPanel = () => {+ usePreviewMiniPlayerStore.getState().close(threadRef);+ useRightPanelStore.getState().openDevice(threadRef, {+ hostId: source.hostId,+ deviceId: source.deviceId,+ platform: source.platform,+ name: source.name,+ });+ };++ return (+ <MiniPlayerShell+ threadRef={threadRef}+ miniPlayer={miniPlayer}+ sourceSize={sourceSize}+ bottomInset={bottomInset}+ label="Floating device preview"+ onOpenInPanel={openInPanel}+ cornerRadius={cornerRadius}+ >+ {() => (+ // The stream is DOM, so it takes the band the browser's native webview would.+ <div+ className="pointer-events-auto absolute inset-0 overflow-hidden rounded-[inherit]"+ style={{ zIndex: PREVIEW_MINI_PLAYER_WEBVIEW_Z_INDEX }}+ >+ <DeviceStreamView+ environmentId={threadRef.environmentId}+ platform={source.platform}+ deviceId={source.deviceId}+ hostId={source.hostId}+ deviceName={device?.name ?? source.name}+ deviceDescription={`${hostLabel} · ${device?.version ?? source.platform}`}+ visible+ onScreen={setScreen}+ />+ </div>+ )}+ </MiniPlayerShell>+ );+}++/**+ * The frame, drag/resize gestures, and hover pill shared by every floating+ * source. Native clipping and the DOM frame use the same radius so their+ * separately composited edges stay aligned.+ */+function MiniPlayerShell({+ threadRef,+ miniPlayer,+ sourceSize,+ bottomInset,+ label,+ onOpenInPanel,+ pillActions,+ cornerRadius = frameCornerRadius,+ children,+}: {+ readonly threadRef: ScopedThreadRef;+ readonly miniPlayer: PreviewMiniPlayerState;+ readonly sourceSize: PreviewMiniPlayerSize;+ readonly bottomInset: number;+ readonly label: string;+ readonly onOpenInPanel: () => void;+ readonly pillActions?: ReactNode;+ /** The clip radius for a given frame; the pill stays inside the curve. */+ readonly cornerRadius?: (frame: PreviewMiniPlayerSize) => number;+ readonly children: (frame: PreviewMiniPlayerFrame) => ReactNode;+}) {+ const containerRef = useRef<HTMLDivElement | null>(null);+ const gestureRef = useRef<PointerGesture | null>(null);+ const [container, setContainer] = useState<PreviewMiniPlayerSize | null>(null);+ const sourceKey = previewMiniPlayerSourceKey(miniPlayer.source);+ const frame = container+ ? resolvePreviewMiniPlayerFrame({+ width: miniPlayer.width,+ position: miniPlayer.position,+ source: sourceSize,+ container,+ bottomInset,+ })+ : null;++ const radius = frame ? cornerRadius(frame) : PREVIEW_MINI_PLAYER_CORNER_RADIUS;+ // Inside a wide curve the default 8px inset would land on the clipped-away corner.+ const pillInset = Math.max(8, Math.round(radius * 0.55));++ const close = () => {+ usePreviewMiniPlayerStore.getState().close(threadRef);+ };+useLayoutEffect(() => {const element = containerRef.current;if (!element) return;@@ -160,7 +348,7 @@ export function ThreadPreviewMiniPlayer({ threadRef, tabId, bottomInset }: Propsif (gesture.direction === null) {store.move(threadRef,- tabId,+ sourceKey,clampPreviewMiniPlayerPosition({ x: gesture.frame.x + delta.x, y: gesture.frame.y + delta.y },container,@@ -174,12 +362,12 @@ export function ThreadPreviewMiniPlayer({ threadRef, tabId, bottomInset }: Propsstart: gesture.frame,direction: gesture.direction,delta,- source,+ source: sourceSize,container,bottomInset,});- store.resize(threadRef, tabId, next.width);- store.move(threadRef, tabId, { x: next.x, y: next.y });+ store.resize(threadRef, sourceKey, next.width);+ store.move(threadRef, sourceKey, { x: next.x, y: next.y });};const endGesture = (event: ReactPointerEvent<HTMLElement>) => {@@ -190,24 +378,25 @@ export function ThreadPreviewMiniPlayer({ threadRef, tabId, bottomInset }: Props}};- if (!snapshot || miniPlayer?.tabId !== tabId) return null;-return (<div ref={containerRef} className="pointer-events-none absolute inset-0">{frame ? (<section- aria-label="Floating browser preview"- data-preview-mini-player={tabId}+ aria-label={label}+ data-preview-mini-player={sourceKey}className="pointer-events-none absolute select-none"style={{left: frame.x,top: frame.y,width: frame.width,height: frame.height,- borderRadius: PREVIEW_MINI_PLAYER_CORNER_RADIUS,+ borderRadius: radius,}}>- <div className="group pointer-events-auto absolute right-2 top-2 z-[49] size-3">+ <div+ className="group pointer-events-auto absolute z-[49] size-3"+ style={{ right: pillInset, top: pillInset }}+ ><divaria-hidden="true"className="absolute right-0 top-0 size-2 rounded-full bg-foreground/25 shadow-sm ring-1 ring-background/70 transition-opacity group-hover:opacity-0 group-focus-within:opacity-0"@@ -227,7 +416,7 @@ export function ThreadPreviewMiniPlayer({ threadRef, tabId, bottomInset }: Propssize="icon-xs"aria-label="Open preview in right panel"onPointerDown={(event) => event.stopPropagation()}- onClick={openInPanel}+ onClick={onOpenInPanel}/>}>@@ -235,31 +424,7 @@ export function ThreadPreviewMiniPlayer({ threadRef, tabId, bottomInset }: Props</TooltipTrigger><TooltipPopup side="top">Open in right panel</TooltipPopup></Tooltip>- <Tooltip>- <TooltipTrigger- render={- <Button- variant={desktopOverlay?.pictureInPicture ? "secondary" : "ghost"}- size="icon-xs"- aria-label={- desktopOverlay?.pictureInPicture- ? "Close popped-out preview"- : "Pop preview into separate window"- }- disabled={!desktopOverlay?.hasWebContents}- onPointerDown={(event) => event.stopPropagation()}- onClick={toggleNativePictureInPicture}- />- }- >- <PictureInPicture2 />- </TooltipTrigger>- <TooltipPopup side="top">- {desktopOverlay?.pictureInPicture- ? "Close separate window"- : "Pop into separate window"}- </TooltipPopup>- </Tooltip>+ {pillActions}<Tooltip><TooltipTriggerrender={@@ -280,21 +445,8 @@ export function ThreadPreviewMiniPlayer({ threadRef, tabId, bottomInset }: Props</div><div className="absolute inset-0 z-[47] rounded-[inherit] bg-muted shadow-2xl/35" />- <BrowserSurfaceSlot- tabId={runtimeTabId}- visible={Boolean(desktopOverlay?.hasWebContents)}- cornerRadius={PREVIEW_MINI_PLAYER_CORNER_RADIUS}- zIndex={PREVIEW_MINI_PLAYER_WEBVIEW_Z_INDEX}- fitSourceContent- layoutVersion={`${frame.x}:${frame.y}`}- className="absolute inset-0"- />+ {children(frame)}<div className="pointer-events-none absolute inset-0 z-[49] rounded-[inherit] ring-1 ring-inset ring-border/80" />- {!desktopOverlay?.hasWebContents ? (- <div className="pointer-events-none absolute inset-0 z-[49] flex items-center justify-center rounded-[inherit] bg-muted text-xs text-muted-foreground">- Reconnecting preview…- </div>- ) : null}{RESIZE_HANDLES.map(({ direction, className }) => (<divkey={direction}diff --git a/apps/web/src/components/preview/previewMiniPlayerLayout.test.ts b/apps/web/src/components/preview/previewMiniPlayerLayout.test.tsindex 20094ad1a5f..ad330ddcd22 100644--- a/apps/web/src/components/preview/previewMiniPlayerLayout.test.ts+++ b/apps/web/src/components/preview/previewMiniPlayerLayout.test.ts@@ -5,6 +5,8 @@ import {clampPreviewMiniPlayerPosition,PREVIEW_MINI_PLAYER_EDGE_GAP,resizePreviewMiniPlayer,+ resolveDeviceMiniPlayerCornerRadius,+ resolveDeviceMiniPlayerSourceSize,resolvePreviewMiniPlayerFrame,resolvePreviewMiniPlayerSourceSize,} from "./previewMiniPlayerLayout";@@ -30,6 +32,50 @@ describe("resolvePreviewMiniPlayerSourceSize", () => {});});+describe("resolveDeviceMiniPlayerSourceSize", () => {+ it("stands in with the platform's phone shape until the stream reports a size", () => {+ const ios = resolveDeviceMiniPlayerSourceSize("ios", null);+ expect(ios.width / ios.height).toBeCloseTo(9 / 19.5);+ const android = resolveDeviceMiniPlayerSourceSize("android", null);+ expect(android.width / android.height).toBeCloseTo(9 / 20);+ });++ it("turns a rotated screen into a landscape box", () => {+ const screen = { width: 1_179, height: 2_556, orientation: "landscape_left" } as const;+ expect(resolveDeviceMiniPlayerSourceSize("ios", screen)).toEqual({+ width: 2_556,+ height: 1_179,+ });+ expect(+ resolveDeviceMiniPlayerSourceSize("android", { ...screen, orientation: "portrait" }),+ ).toEqual({ width: 1_179, height: 2_556 });+ });++ it("floats a phone at the minimum width rather than the default box", () => {+ expect(+ resolvePreviewMiniPlayerFrame({+ width: null,+ position: null,+ source: resolveDeviceMiniPlayerSourceSize("ios", null),+ container,+ }),+ ).toMatchObject({ width: 240, height: 520 });+ });+});++describe("resolveDeviceMiniPlayerCornerRadius", () => {+ it("rounds an Android player like a phone, scaled with its short side", () => {+ expect(resolveDeviceMiniPlayerCornerRadius("android", { width: 240, height: 520 })).toBe(34);+ expect(resolveDeviceMiniPlayerCornerRadius("android", { width: 520, height: 240 })).toBe(34);+ expect(resolveDeviceMiniPlayerCornerRadius("android", { width: 60, height: 130 })).toBe(12);+ });++ it("keeps the frame radius for iOS, whose stream has square corners", () => {+ expect(resolveDeviceMiniPlayerCornerRadius("ios", { width: 240, height: 520 })).toBe(12);+ expect(resolveDeviceMiniPlayerCornerRadius("ios", { width: 720, height: 1_000 })).toBe(12);+ });+});+describe("resolvePreviewMiniPlayerFrame", () => {it("opens at the source aspect ratio in the top-right corner", () => {expect(diff --git a/apps/web/src/components/preview/previewMiniPlayerLayout.ts b/apps/web/src/components/preview/previewMiniPlayerLayout.tsindex 372ed71c6b0..6f9dc41725d 100644--- a/apps/web/src/components/preview/previewMiniPlayerLayout.ts+++ b/apps/web/src/components/preview/previewMiniPlayerLayout.ts@@ -1,4 +1,4 @@-import type { PreviewViewportSetting } from "@t3tools/contracts";+import type { DevicePlatform, PreviewViewportSetting } from "@t3tools/contracts";import type { BrowserSurfaceContentPresentation } from "~/browser/browserSurfaceStore";import {@@ -7,7 +7,10 @@ import {} from "~/browser/browserViewportLayout";import type { PreviewMiniPlayerPosition, PreviewMiniPlayerSize } from "~/previewMiniPlayerStore";+import type { DeviceScreenSize } from "../device/deviceStream";+export const PREVIEW_MINI_PLAYER_EDGE_GAP = 12;+export const PREVIEW_MINI_PLAYER_CORNER_RADIUS = 12;// The mini-player shell straddles this webview at 47 and 49; dialogs begin at 50.export const PREVIEW_MINI_PLAYER_WEBVIEW_Z_INDEX = 48;// A fresh player is the largest box at the source aspect ratio that fits here.@@ -34,6 +37,46 @@ export function resolvePreviewMiniPlayerSourceSize(};}+/**+ * The device screen as the user sees it, so a rotated phone floats as a+ * landscape box. Before the stream reports its size the platform's usual phone+ * shape stands in, matching the stream view's own placeholder aspect; the+ * nominal width only keeps the source cap above any sensible player width.+ */+export function resolveDeviceMiniPlayerSourceSize(+ platform: DevicePlatform,+ screen: DeviceScreenSize | null,+): PreviewMiniPlayerSize {+ if (!screen) {+ const width = 1_000;+ return { width, height: width / (platform === "ios" ? 9 / 19.5 : 9 / 20) };+ }+ const landscape =+ screen.orientation === "landscape_left" || screen.orientation === "landscape_right";+ const long = Math.max(screen.width, screen.height);+ const short = Math.min(screen.width, screen.height);+ return landscape ? { width: long, height: short } : { width: short, height: long };+}++/**+ * The Android emulator composites the skin's rounded corners into its+ * framebuffer as black wedges (measured at ~13% of the short side on a+ * Pixel 9), so its player clips at a matching phone-like radius; the sliver+ * lost under the curve is status-bar padding. iOS simulators stream an+ * edge-to-edge rectangle and keep the frame radius, which matters for iPads+ * whose real corners are far tighter than a phone's.+ */+export function resolveDeviceMiniPlayerCornerRadius(+ platform: DevicePlatform,+ player: PreviewMiniPlayerSize,+): number {+ if (platform !== "android") return PREVIEW_MINI_PLAYER_CORNER_RADIUS;+ return Math.max(+ PREVIEW_MINI_PLAYER_CORNER_RADIUS,+ Math.round(Math.min(player.width, player.height) * 0.14),+ );+}+const availableArea = (container: PreviewMiniPlayerSize,bottomInset: number,diff --git a/apps/web/src/components/settings/IntegrationsSettings.tsx b/apps/web/src/components/settings/IntegrationsSettings.tsxindex 188c3045fbc..4197a828e2f 100644--- a/apps/web/src/components/settings/IntegrationsSettings.tsx+++ b/apps/web/src/components/settings/IntegrationsSettings.tsx@@ -718,7 +718,7 @@ function BrowserAutoShowFloatingPreviewSetting({ disabled }: { readonly disabledreturn (<SettingsRow{...searchableSetting("browser-auto-show-floating-preview")}- description="Show the floating preview when an agent opens a browser unless the agent says otherwise."+ description="Show the floating preview when an agent opens a browser or device unless the agent says otherwise."resetAction={!disabled && autoShow !== DEFAULT_BROWSER_AUTO_SHOW_FLOATING_PREVIEW ? (<SettingResetButtondiff --git a/apps/web/src/components/settings/settingsSearch.ts b/apps/web/src/components/settings/settingsSearch.tsindex 605023c2326..aa5b95642b9 100644--- a/apps/web/src/components/settings/settingsSearch.ts+++ b/apps/web/src/components/settings/settingsSearch.ts@@ -519,7 +519,7 @@ export const SETTINGS_SEARCH_ITEMS = [id: "browser-auto-show-floating-preview",title: "Auto-show floating preview",to: "/settings/integrations",- searchTerms: ["agent opens browser pop into view hide"],+ searchTerms: ["agent opens browser device simulator pop into view hide"],},{id: "automatic-pull",diff --git a/apps/web/src/previewMiniPlayerStore.test.ts b/apps/web/src/previewMiniPlayerStore.test.tsindex 32c84f38294..e4eb40c8b08 100644--- a/apps/web/src/previewMiniPlayerStore.test.ts+++ b/apps/web/src/previewMiniPlayerStore.test.ts@@ -2,10 +2,25 @@ import { scopeThreadRef } from "@t3tools/client-runtime/environment";import { type EnvironmentId, ThreadId } from "@t3tools/contracts";import { beforeEach, describe, expect, it } from "vite-plus/test";-import { selectThreadPreviewMiniPlayer, usePreviewMiniPlayerStore } from "./previewMiniPlayerStore";+import {+ browserMiniPlayerSource,+ type PreviewMiniPlayerSource,+ selectThreadPreviewMiniPlayer,+ selectThreadPreviewMiniPlayerTabId,+ usePreviewMiniPlayerStore,+} from "./previewMiniPlayerStore";const refA = scopeThreadRef("env-1" as EnvironmentId, ThreadId.make("thread-A"));const refB = scopeThreadRef("env-1" as EnvironmentId, ThreadId.make("thread-B"));+const tabA = browserMiniPlayerSource("tab-a");+const tabB = browserMiniPlayerSource("tab-b");+const pixel: PreviewMiniPlayerSource = {+ kind: "device",+ hostId: "nucbox",+ deviceId: "emulator-5580",+ platform: "android",+ name: "Pixel",+};beforeEach(() => {usePreviewMiniPlayerStore.setState({ byThreadKey: {} });@@ -13,52 +28,71 @@ beforeEach(() => {describe("previewMiniPlayerStore", () => {it("keeps floating previews scoped to their thread", () => {- usePreviewMiniPlayerStore.getState().open(refA, "tab-a");- usePreviewMiniPlayerStore.getState().open(refB, "tab-b");+ usePreviewMiniPlayerStore.getState().open(refA, tabA);+ usePreviewMiniPlayerStore.getState().open(refB, tabB);expect(selectThreadPreviewMiniPlayer(usePreviewMiniPlayerStore.getState().byThreadKey, refA),- ).toMatchObject({ tabId: "tab-a" });+ ).toMatchObject({ source: tabA });expect(selectThreadPreviewMiniPlayer(usePreviewMiniPlayerStore.getState().byThreadKey, refB),- ).toMatchObject({ tabId: "tab-b" });+ ).toMatchObject({ source: tabB });});it("preserves position when switching the floating tab within one thread", () => {- usePreviewMiniPlayerStore.getState().open(refA, "tab-a");- usePreviewMiniPlayerStore.getState().move(refA, "tab-a", { x: 24, y: 48 });- usePreviewMiniPlayerStore.getState().open(refA, "tab-b");+ usePreviewMiniPlayerStore.getState().open(refA, tabA);+ usePreviewMiniPlayerStore.getState().move(refA, "browser:tab-a", { x: 24, y: 48 });+ usePreviewMiniPlayerStore.getState().open(refA, tabB);expect(selectThreadPreviewMiniPlayer(usePreviewMiniPlayerStore.getState().byThreadKey, refA),).toEqual({- tabId: "tab-b",+ source: tabB,position: { x: 24, y: 48 },width: null,});});it("ignores stale drag updates after the floating tab changes", () => {- usePreviewMiniPlayerStore.getState().open(refA, "tab-a");- usePreviewMiniPlayerStore.getState().open(refA, "tab-b");- usePreviewMiniPlayerStore.getState().move(refA, "tab-a", { x: 100, y: 100 });+ usePreviewMiniPlayerStore.getState().open(refA, tabA);+ usePreviewMiniPlayerStore.getState().open(refA, tabB);+ usePreviewMiniPlayerStore.getState().move(refA, "browser:tab-a", { x: 100, y: 100 });expect(selectThreadPreviewMiniPlayer(usePreviewMiniPlayerStore.getState().byThreadKey, refA),).toEqual({- tabId: "tab-b",+ source: tabB,position: null,width: null,});});it("preserves a thread-bound width while switching tabs", () => {- usePreviewMiniPlayerStore.getState().open(refA, "tab-a");- usePreviewMiniPlayerStore.getState().resize(refA, "tab-a", 480);- usePreviewMiniPlayerStore.getState().open(refA, "tab-b");+ usePreviewMiniPlayerStore.getState().open(refA, tabA);+ usePreviewMiniPlayerStore.getState().resize(refA, "browser:tab-a", 480);+ usePreviewMiniPlayerStore.getState().open(refA, tabB);expect(selectThreadPreviewMiniPlayer(usePreviewMiniPlayerStore.getState().byThreadKey, refA),- ).toMatchObject({ tabId: "tab-b", width: 480 });+ ).toMatchObject({ source: tabB, width: 480 });+ });++ it("floats one source per thread, so a device replaces the browser tab", () => {+ usePreviewMiniPlayerStore.getState().open(refA, tabA);+ usePreviewMiniPlayerStore.getState().open(refA, pixel);+ const floating = selectThreadPreviewMiniPlayer(+ usePreviewMiniPlayerStore.getState().byThreadKey,+ refA,+ );++ expect(floating).toMatchObject({ source: pixel });+ expect(+ selectThreadPreviewMiniPlayerTabId(usePreviewMiniPlayerStore.getState().byThreadKey, refA),+ ).toBeNull();+ // The same device under a new label is still the same floating source.+ usePreviewMiniPlayerStore.getState().open(refA, { ...pixel, name: "Renamed" });+ expect(+ selectThreadPreviewMiniPlayer(usePreviewMiniPlayerStore.getState().byThreadKey, refA),+ ).toBe(floating);});});diff --git a/apps/web/src/previewMiniPlayerStore.ts b/apps/web/src/previewMiniPlayerStore.tsindex aed9376af15..b3e3c3b0505 100644--- a/apps/web/src/previewMiniPlayerStore.ts+++ b/apps/web/src/previewMiniPlayerStore.ts@@ -1,5 +1,5 @@import { scopedThreadKey } from "@t3tools/client-runtime/environment";-import type { ScopedThreadRef } from "@t3tools/contracts";+import type { DevicePlatform, ScopedThreadRef } from "@t3tools/contracts";import { create } from "zustand";export interface PreviewMiniPlayerPosition {@@ -12,34 +12,66 @@ export interface PreviewMiniPlayerSize {readonly height: number;}+/** What the floating player mirrors: a browser tab or a device stream. */+export type PreviewMiniPlayerSource =+ | { readonly kind: "browser"; readonly tabId: string }+ | {+ readonly kind: "device";+ readonly hostId: string;+ readonly deviceId: string;+ readonly platform: DevicePlatform;+ readonly name: string;+ };+export interface PreviewMiniPlayerState {- readonly tabId: string;+ readonly source: PreviewMiniPlayerSource;readonly position: PreviewMiniPlayerPosition | null;- /** Height always follows the previewed viewport's aspect ratio. */+ /** Height always follows the mirrored source's aspect ratio. */readonly width: number | null;}interface PreviewMiniPlayerStoreState {readonly byThreadKey: Record<string, PreviewMiniPlayerState>;- readonly open: (ref: ScopedThreadRef, tabId: string) => void;+ readonly open: (ref: ScopedThreadRef, source: PreviewMiniPlayerSource) => void;readonly close: (ref: ScopedThreadRef) => void;- readonly move: (ref: ScopedThreadRef, tabId: string, position: PreviewMiniPlayerPosition) => void;- readonly resize: (ref: ScopedThreadRef, tabId: string, width: number) => void;+ /** `sourceKey` guards against a drag that outlives the source it started on. */+ readonly move: (+ ref: ScopedThreadRef,+ sourceKey: string,+ position: PreviewMiniPlayerPosition,+ ) => void;+ readonly resize: (ref: ScopedThreadRef, sourceKey: string, width: number) => void;readonly removeThread: (ref: ScopedThreadRef) => void;}+export function previewMiniPlayerSourceKey(source: PreviewMiniPlayerSource): string {+ return source.kind === "browser"+ ? `browser:${source.tabId}`+ : `device:${encodeURIComponent(source.hostId)}:${encodeURIComponent(source.deviceId)}`;+}++export const browserMiniPlayerSource = (tabId: string): PreviewMiniPlayerSource => ({+ kind: "browser",+ tabId,+});+export const usePreviewMiniPlayerStore = create<PreviewMiniPlayerStoreState>()((set) => ({byThreadKey: {},- open: (ref, tabId) =>+ open: (ref, source) =>set((state) => {const threadKey = scopedThreadKey(ref);const current = state.byThreadKey[threadKey];- if (current?.tabId === tabId) return state;+ if (+ current &&+ previewMiniPlayerSourceKey(current.source) === previewMiniPlayerSourceKey(source)+ ) {+ return state;+ }return {byThreadKey: {...state.byThreadKey,[threadKey]: {- tabId,+ source,position: current?.position ?? null,width: current?.width ?? null,},@@ -53,11 +85,11 @@ export const usePreviewMiniPlayerStore = create<PreviewMiniPlayerStoreState>()((const { [threadKey]: _closed, ...byThreadKey } = state.byThreadKey;return { byThreadKey };}),- move: (ref, tabId, position) =>+ move: (ref, sourceKey, position) =>set((state) => {const threadKey = scopedThreadKey(ref);const current = state.byThreadKey[threadKey];- if (!current || current.tabId !== tabId) return state;+ if (!current || previewMiniPlayerSourceKey(current.source) !== sourceKey) return state;if (current.position?.x === position.x && current.position.y === position.y) return state;return {byThreadKey: {@@ -66,11 +98,17 @@ export const usePreviewMiniPlayerStore = create<PreviewMiniPlayerStoreState>()((},};}),- resize: (ref, tabId, width) =>+ resize: (ref, sourceKey, width) =>set((state) => {const threadKey = scopedThreadKey(ref);const current = state.byThreadKey[threadKey];- if (!current || current.tabId !== tabId || current.width === width) return state;+ if (+ !current ||+ previewMiniPlayerSourceKey(current.source) !== sourceKey ||+ current.width === width+ ) {+ return state;+ }return {byThreadKey: {...state.byThreadKey,@@ -94,3 +132,12 @@ export function selectThreadPreviewMiniPlayer(if (!ref) return null;return byThreadKey[scopedThreadKey(ref)] ?? null;}++/** The floating browser tab, or null when nothing floats or a device does. */+export function selectThreadPreviewMiniPlayerTabId(+ byThreadKey: Record<string, PreviewMiniPlayerState>,+ ref: ScopedThreadRef | null | undefined,+): string | null {+ const source = selectThreadPreviewMiniPlayer(byThreadKey, ref)?.source;+ return source?.kind === "browser" ? source.tabId : null;+}diff --git a/docs/user/devices.md b/docs/user/devices.mdindex 7d1b91792ae..2dbe0e26007 100644--- a/docs/user/devices.md+++ b/docs/user/devices.md@@ -18,6 +18,10 @@ device to boot it. The panel shows when you or an agent starts a device.Each device opens in its own tab. Use **+ → Device** to open another, anddouble-click a tab name or choose **Rename** from its context menu to rename it.Only the visible tab streams video; switching tabs keeps both devices running.+Choose **Float device over chat** in the toolbar to keep watching and tapping the+device in a small window while the right panel shows something else; drag the+window by its handle, resize it from any edge, and use **Open in right panel**+to bring it back.Turn off the device hub in **Settings → Integrations → Devices** to stop thehelper processes; simulators and emulators keep running until you power themoff.@@ -48,8 +52,11 @@ back from the device after a change.## Agents and devices-When an agent opens a device, the panel opens in web and desktop clients connected-to the thread. Mobile clients show device activity in the thread timeline. Agents drive the device through the `agent-device` command line. T3+When an agent opens a device, it floats over the chat in web and desktop clients+connected to the thread, the same way an agent-driven browser does. Turn off+**Auto-show floating preview** in **Settings → Integrations → Browser** to open a+right-panel tab instead. Mobile clients show device activity in the thread+timeline. Agents drive the device through the `agent-device` command line. T3Code installs and starts it only after **Agent device access** is enabled. iOStaps build a small test runner on first use, which takes a couple of minutesonce per server. Restart an existing agent session after granting access so it