Open History to see the last commit
1import type { DeviceServiceState, ScopedThreadRef } from "@t3tools/contracts";
2import { scopedThreadKey } from "@t3tools/client-runtime/environment";
3import { useEffect, useRef } from "react";
4import { useClientSettings } from "../../hooks/useSettings";
5import {
6 browserMiniPlayerSource,
7 usePreviewMiniPlayerStore,
8 type PreviewMiniPlayerState,
9} from "../../previewMiniPlayerStore";
10import type { ThreadPreviewState } from "../../previewStateStore";
11import { useRightPanelStore, type RightPanelSurface } from "../../rightPanelStore";
12
13const selectAutoShowFloatingPreview = (settings: { browserAutoShowFloatingPreview: boolean }) =>
14 settings.browserAutoShowFloatingPreview;
15
16/**
17 * Shows browsers and devices an agent or another client opened for the thread,
18 * and closes a floating device once its session ends.
19 */
20export function useAgentOpenedPreviews(input: {
21 readonly threadRef: ScopedThreadRef | null;
22 readonly deviceState: DeviceServiceState;
23 readonly deviceStateLoaded: boolean;
24 readonly previewState: ThreadPreviewState;
25 // Whether the environment hosts browser tabs for this client.
26 readonly serverBrowserAvailable: boolean;
27 readonly panelSurfaces: ReadonlyArray<RightPanelSurface>;
28 readonly miniPlayerSource: PreviewMiniPlayerState["source"] | null;
29 // Sheet layouts show neither floating previews nor auto-opened device tabs.
30 readonly sheetLayout: boolean;
31}) {
32 const {
33 threadRef,
34 deviceState,
35 deviceStateLoaded,
36 previewState,
37 serverBrowserAvailable,
38 panelSurfaces,
39 miniPlayerSource,
40 sheetLayout,
41 } = input;
42 const autoShowFloatingPreview = useClientSettings(selectAutoShowFloatingPreview);
43 // A device the agent opens floats over chat like an agent-driven browser,
44 // or becomes a panel tab when floating previews are off. Sessions opened by
45 // another client arrive the same way; sheet layouts get neither. The first
46 // snapshot is a baseline: persisted tabs restore themselves, and existing
47 // sessions must not resurrect closed tabs. A session whose device summary
48 // has not arrived yet stays out of the baseline so a later snapshot opens it.
49 const previousDeviceSessions = useRef(new Map<string, Set<string>>());
50 useEffect(() => {
51 if (!threadRef || !deviceStateLoaded) return;
52 const threadKey = `${threadRef.environmentId}:${threadRef.threadId}`;
53 const sessions = deviceState.sessions.filter(
54 (session) => session.threadId === threadRef.threadId,
55 );
56 const key = (session: (typeof sessions)[number]) => `${session.hostId}:${session.deviceId}`;
57 const deviceFor = (session: (typeof sessions)[number]) =>
58 deviceState.devices.find(
59 (entry) => entry.hostId === session.hostId && entry.id === session.deviceId,
60 );
61 const previous = previousDeviceSessions.current.get(threadKey);
62 previousDeviceSessions.current.set(
63 threadKey,
64 new Set(sessions.filter((session) => deviceFor(session) !== undefined).map(key)),
65 );
66 if (!previous || sheetLayout) return;
67 for (const session of sessions) {
68 if (previous.has(key(session))) continue;
69 const device = deviceFor(session);
70 if (!device) continue;
71 const target = {
72 hostId: session.hostId,
73 deviceId: session.deviceId,
74 platform: device.platform,
75 name: device.name,
76 };
77 if (autoShowFloatingPreview) {
78 usePreviewMiniPlayerStore.getState().open(threadRef, { kind: "device", ...target });
79 continue;
80 }
81 const existing = useRightPanelStore
82 .getState()
83 .byThreadKey[scopedThreadKey(threadRef)]?.surfaces.some(
84 (surface) =>
85 surface.kind === "device" &&
86 surface.target?.hostId === session.hostId &&
87 surface.target.deviceId === session.deviceId,
88 );
89 if (existing) continue;
90 useRightPanelStore.getState().openDevice(threadRef, target, true);
91 }
92 }, [
93 threadRef,
94 autoShowFloatingPreview,
95 deviceStateLoaded,
96 sheetLayout,
97 deviceState.sessions,
98 deviceState.devices,
99 ]);
100 // Baseline loaded tabs so reloads never reopen previews the user dismissed.
101 const previousServerPreviewTabs = useRef(new Map<string, Map<string, string | undefined>>());
102 useEffect(() => {
103 if (!threadRef || !serverBrowserAvailable || !previewState.listLoaded) return;
104 const threadKey = scopedThreadKey(threadRef);
105 const serverSessions = Object.values(previewState.sessions).filter(
106 (session) => session.runtime === "server",
107 );
108 const previous = previousServerPreviewTabs.current.get(threadKey);
109 previousServerPreviewTabs.current.set(
110 threadKey,
111 new Map(serverSessions.map((session) => [session.tabId, session.revealRequest?.id])),
112 );
113 if (!previous) return;
114 for (const session of serverSessions) {
115 const requested = session.revealRequest;
116 const fresh = requested
117 ? previous.get(session.tabId) !== requested.id
118 : !previous.has(session.tabId);
119 if (!fresh || session.reveal !== true) continue;
120 if (!autoShowFloatingPreview && requested?.force !== true) continue;
121 const surface = panelSurfaces.find(
122 (surface) => surface.kind === "preview" && surface.resourceId === session.tabId,
123 );
124 if (surface && requested?.force === true) {
125 useRightPanelStore.getState().activateSurface(threadRef, surface.id);
126 } else if (!surface) {
127 usePreviewMiniPlayerStore
128 .getState()
129 .open(threadRef, browserMiniPlayerSource(session.tabId));
130 }
131 }
132 }, [
133 serverBrowserAvailable,
134 previewState.listLoaded,
135 previewState.sessions,
136 threadRef,
137 autoShowFloatingPreview,
138 panelSurfaces,
139 ]);
140 // A floating device follows its session: once the agent or another client
141 // closes the device there is nothing left to stream.
142 useEffect(() => {
143 if (!threadRef || !deviceStateLoaded) return;
144 const source = miniPlayerSource;
145 if (source?.kind !== "device") return;
146 const sessionStillExists = deviceState.sessions.some(
147 (session) =>
148 session.threadId === threadRef.threadId &&
149 session.hostId === source.hostId &&
150 session.deviceId === source.deviceId,
151 );
152 if (!sessionStillExists) usePreviewMiniPlayerStore.getState().close(threadRef);
153 }, [miniPlayerSource, threadRef, deviceState.sessions, deviceStateLoaded]);
154}