Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

agentOpenedPreviews.ts

333 lines12.7 KB

1import {
2 parseScopedThreadKey,
3 scopedThreadKey,
4 scopeThreadRef,
5} from "@t3tools/client-runtime/environment";
6import type {
7 DeviceServiceState,
8 EnvironmentId,
9 PreviewSessionSnapshot,
10 ScopedThreadRef,
11 ThreadId,
12} from "@t3tools/contracts";
13import { AsyncResult } from "effect/reactivity";
14​
15import { getClientSettings } from "../../hooks/useSettings";
16import {
17 browserMiniPlayerSource,
18 type PreviewMiniPlayerSource,
19 previewMiniPlayerSourceKey,
20 usePreviewMiniPlayerStore,
21} from "../../previewMiniPlayerStore";
22import {
23 previewNavStatus,
24 previewStateAtom,
25 previewThreadRefsAtom,
26 type ThreadPreviewState,
27} from "../../previewStateStore";
28import {
29 type RightPanelSurface,
30 selectActiveRightPanelSurface,
31 useRightPanelStore,
32} from "../../rightPanelStore";
33import { RIGHT_PANEL_INLINE_LAYOUT_MEDIA_QUERY } from "../../rightPanelLayout";
34import { appAtomRegistry } from "../../rpc/atomRegistry";
35import { deviceEnvironment } from "../../state/device";
36import { readEnvironmentSupportsServerBrowser } from "../../state/entities";
37import { environmentSummaries } from "../../state/presentation";
38​
39/**
40 * Shows browsers an agent or another client revealed for a thread: floating
41 * over chat, or focusing an existing panel tab when the reveal is forced.
42 */
43export function revealServerTabs(
44 threadRef: ScopedThreadRef,
45 sessions: ReadonlyArray<PreviewSessionSnapshot>,
46 options: { readonly autoShowFloatingPreview: boolean },
47): void {
48 if (!readEnvironmentSupportsServerBrowser(threadRef.environmentId)) return;
49 for (const session of sessions) {
50 const force = session.revealRequest?.force === true;
51 if (!options.autoShowFloatingPreview && !force) continue;
52 const surface = useRightPanelStore
53 .getState()
54 .byThreadKey[scopedThreadKey(threadRef)]?.surfaces.find(
55 (surface) => surface.kind === "preview" && surface.resourceId === session.tabId,
56 );
57 if (surface && force) {
58 useRightPanelStore.getState().revealSurface(threadRef, surface.id);
59 } else if (!surface) {
60 usePreviewMiniPlayerStore.getState().open(threadRef, browserMiniPlayerSource(session.tabId));
61 }
62 }
64​
65/**
66 * Keeps a thread's browser panel tabs and floating browser in step with its
67 * preview sessions. Server-hosted sessions are only complete once the first
68 * list has loaded; before that, a missing session is not a closed one.
69 */
70export function followPreviewSessions(threadRef: ScopedThreadRef, state: ThreadPreviewState): void {
71 if (readEnvironmentSupportsServerBrowser(threadRef.environmentId) && !state.listLoaded) return;
72 const sessions = Object.values(state.sessions);
73 useRightPanelStore.getState().reconcileBrowserSurfaces(
74 threadRef,
75 sessions.map((session) => session.tabId),
76 new Set(
77 sessions
78 .filter((session) => session.runtime === "server" && session.reveal === false)
79 .map((session) => session.tabId),
80 ),
81 );
82 const miniPlayer = usePreviewMiniPlayerStore.getState();
83 const source = miniPlayer.byThreadKey[scopedThreadKey(threadRef)]?.source;
84 if (source?.kind === "browser" && !state.sessions[source.tabId]) miniPlayer.close(threadRef);
86​
87/**
88 * Server tabs that are new, or carry a new reveal request, since `previous`.
89 * Nothing is fresh until the first list has loaded: that list is the baseline,
90 * so a reload never reopens previews the user dismissed. A tab this client was
91 * closing comes back without a reveal if the close fails.
92 */
93function freshlyRevealedServerTabs(
94 previous: ThreadPreviewState,
95 next: ThreadPreviewState,
96): ReadonlyArray<PreviewSessionSnapshot> {
97 if (!previous.listLoaded || previous.sessions === next.sessions) return [];
98 return Object.values(next.sessions).filter((session) => {
99 if (session.runtime !== "server" || session.reveal !== true) return false;
100 if (previous.suppressedTabIds.has(session.tabId)) return false;
101 const before = previous.sessions[session.tabId];
102 const requested = session.revealRequest;
103 return requested ? before?.revealRequest?.id !== requested.id : before === undefined;
104 });
106​
107function followThread(threadKey: string, threadRef: ScopedThreadRef): () => void {
108 const atom = previewStateAtom(threadKey);
109 let previous = appAtomRegistry.get(atom);
110 return appAtomRegistry.subscribe(atom, (next) => {
111 const before = previous;
112 previous = next;
113 // Reveals run first so a revealed tab floats before it gains a panel tab.
114 const revealed = freshlyRevealedServerTabs(before, next);
115 if (revealed.length > 0) {
116 revealServerTabs(threadRef, revealed, {
117 autoShowFloatingPreview: getClientSettings().browserAutoShowFloatingPreview,
118 });
119 }
120 if (before.sessions !== next.sessions || before.listLoaded !== next.listLoaded) {
121 followPreviewSessions(threadRef, next);
122 }
123 });
125​
126// `openedAt` tells a session apart from one that ended and reopened on the same device while
127// this client was disconnected.
128const sessionKey = (session: DeviceServiceState["sessions"][number]) =>
129 `${session.threadId}:${session.hostId}:${session.deviceId}:${session.openedAt}`;
130​
131/**
132 * Per environment: the device sessions seen in the last snapshot. The first
133 * snapshot is a baseline, so persisted tabs restore themselves and existing
134 * sessions never resurrect tabs the user closed. Baselines outlive a
135 * disconnect, so a device an agent opened during the gap still shows.
136 */
137const deviceSessionBaselines = new Map<EnvironmentId, ReadonlySet<string>>();
138​
139function hasLiveSession(
140 state: DeviceServiceState,
141 threadId: ThreadId,
142 target: { readonly hostId: string; readonly deviceId: string },
143): boolean {
144 return state.sessions.some(
145 (session) =>
146 session.threadId === threadId &&
147 session.hostId === target.hostId &&
148 session.deviceId === target.deviceId,
149 );
151​
152/**
153 * A device the agent opens floats over its thread's chat, or becomes a panel tab
154 * when floating previews are off; sheet layouts get neither. A session without a
155 * device summary yet stays out of the baseline so a later snapshot opens it.
156 * Floating devices whose session ended close here.
157 */
158export function applyDeviceSnapshot(
159 environmentId: EnvironmentId,
160 state: DeviceServiceState,
161 options: { readonly sheetLayout: boolean; readonly autoShowFloatingPreview: boolean },
162): void {
163 const deviceFor = (session: DeviceServiceState["sessions"][number]) =>
164 state.devices.find((entry) => entry.hostId === session.hostId && entry.id === session.deviceId);
165​
166 const miniPlayer = usePreviewMiniPlayerStore.getState();
167 for (const [threadKey, entry] of Object.entries(miniPlayer.byThreadKey)) {
168 if (entry.source.kind !== "device") continue;
169 const ref = parseScopedThreadKey(threadKey);
170 if (ref?.environmentId === environmentId && !hasLiveSession(state, ref.threadId, entry.source))
171 miniPlayer.close(ref);
172 }
173​
174 const previous = deviceSessionBaselines.get(environmentId);
175 deviceSessionBaselines.set(
176 environmentId,
177 new Set(state.sessions.filter((session) => deviceFor(session) !== undefined).map(sessionKey)),
178 );
179 if (!previous || options.sheetLayout) return;
180 for (const session of state.sessions) {
181 if (previous.has(sessionKey(session))) continue;
182 const device = deviceFor(session);
183 if (!device) continue;
184 const threadRef = scopeThreadRef(environmentId, session.threadId);
185 const target = {
186 hostId: session.hostId,
187 deviceId: session.deviceId,
188 platform: device.platform,
189 name: device.name,
190 };
191 if (options.autoShowFloatingPreview) {
192 usePreviewMiniPlayerStore.getState().open(threadRef, { kind: "device", ...target });
193 continue;
194 }
195 const existing = useRightPanelStore
196 .getState()
197 .byThreadKey[scopedThreadKey(threadRef)]?.surfaces.some(
198 (surface) =>
199 surface.kind === "device" &&
200 surface.target?.hostId === session.hostId &&
201 surface.target.deviceId === session.deviceId,
202 );
203 if (existing) continue;
204 useRightPanelStore.getState().openDevice(threadRef, target, true);
205 }
207​
208/**
209 * Floats a device panel tab over chat. A tab whose device session already
210 * ended has nothing to stream, so it only closes the panel. Before the first
211 * device snapshot the tab floats, and that snapshot closes it if needed.
212 */
213export function floatDeviceSurface(
214 threadRef: ScopedThreadRef,
215 source: Extract<PreviewMiniPlayerSource, { kind: "device" }>,
216 state: DeviceServiceState | null,
217): void {
218 if (state !== null && !hasLiveSession(state, threadRef.threadId, source)) return;
219 usePreviewMiniPlayerStore.getState().open(threadRef, source);
221​
222/** Floats a browser panel tab over chat, unless it never navigated. */
223export function floatBrowserSurface(
224 threadRef: ScopedThreadRef,
225 tabId: string,
226 state: ThreadPreviewState,
227): void {
228 const snapshot = state.sessions[tabId] ?? null;
229 if (previewNavStatus(snapshot, state.desktopByTabId[tabId] ?? null)._tag === "Idle") return;
230 usePreviewMiniPlayerStore.getState().open(threadRef, browserMiniPlayerSource(tabId));
232​
233/** The floating source a panel tab would become: its browser or device, if it has one. */
234export function panelSurfaceMiniPlayerSource(
235 surface: RightPanelSurface | null,
236): PreviewMiniPlayerSource | null {
237 if (surface?.kind === "preview" && surface.resourceId) {
238 return browserMiniPlayerSource(surface.resourceId);
239 }
240 if (surface?.kind === "device" && surface.target) return { kind: "device", ...surface.target };
241 return null;
243​
244/** Ends the float of a browser or device once the open panel shows it again. */
245export function dockFloatingPreviewInPanel(threadRef: ScopedThreadRef): void {
246 const miniPlayer = usePreviewMiniPlayerStore.getState();
247 const floating = miniPlayer.byThreadKey[scopedThreadKey(threadRef)]?.source;
248 if (!floating) return;
249 const docked = panelSurfaceMiniPlayerSource(
250 selectActiveRightPanelSurface(useRightPanelStore.getState().byThreadKey, threadRef),
251 );
252 if (docked && previewMiniPlayerSourceKey(docked) === previewMiniPlayerSourceKey(floating)) {
253 miniPlayer.close(threadRef);
254 }
256​
257/** Floats a panel's browser or device as the panel closes, when Auto-show floating preview is on. */
258export function floatPanelSurfaceOnClose(
259 threadRef: ScopedThreadRef,
260 source: PreviewMiniPlayerSource,
261 options: {
262 readonly autoShowFloatingPreview: boolean;
263 readonly previewState: ThreadPreviewState;
264 readonly deviceState: DeviceServiceState | null;
265 },
266): void {
267 if (!options.autoShowFloatingPreview) return;
268 if (source.kind === "browser") {
269 floatBrowserSurface(threadRef, source.tabId, options.previewState);
270 } else {
271 floatDeviceSurface(threadRef, source, options.deviceState);
272 }
274​
275export function resetDeviceSessionBaselinesForTests(): void {
276 deviceSessionBaselines.clear();
278​
279function watchEnvironmentDevices(environmentId: EnvironmentId): () => void {
280 return appAtomRegistry.subscribe(
281 deviceEnvironment.state({ environmentId, input: {} }),
282 (result) => {
283 const state = AsyncResult.getOrElse(result, () => null);
284 if (state === null) return;
285 applyDeviceSnapshot(environmentId, state, {
286 sheetLayout: window.matchMedia(RIGHT_PANEL_INLINE_LAYOUT_MEDIA_QUERY).matches,
287 autoShowFloatingPreview: getClientSettings().browserAutoShowFloatingPreview,
288 });
289 },
290 { immediate: true },
291 );
293​
294/**
295 * Follows every thread's browser previews and every connected environment's
296 * device sessions for the life of the page, not just the open thread's: an
297 * agent in a background thread can open either.
298 */
299export function startAgentOpenedPreviews(): () => void {
300 const followed = new Map<string, () => void>();
301 const followNewThreads = (refs: ReadonlyMap<string, ScopedThreadRef>) => {
302 for (const [threadKey, threadRef] of refs) {
303 if (!followed.has(threadKey)) followed.set(threadKey, followThread(threadKey, threadRef));
304 }
305 };
306 const stopIndex = appAtomRegistry.subscribe(previewThreadRefsAtom, followNewThreads, {
307 immediate: true,
308 });
309 const watchedEnvironments = new Map<EnvironmentId, () => void>();
310 const watchConnectedEnvironments = (environmentIds: ReadonlyArray<EnvironmentId>) => {
311 for (const [environmentId, stop] of watchedEnvironments) {
312 if (environmentIds.includes(environmentId)) continue;
313 stop();
314 watchedEnvironments.delete(environmentId);
315 }
316 for (const environmentId of environmentIds) {
317 if (!watchedEnvironments.has(environmentId)) {
318 watchedEnvironments.set(environmentId, watchEnvironmentDevices(environmentId));
319 }
320 }
321 };
322 const stopEnvironments = appAtomRegistry.subscribe(
323 environmentSummaries.connectedEnvironmentIdsAtom,
324 watchConnectedEnvironments,
325 { immediate: true },
326 );
327 return () => {
328 stopIndex();
329 stopEnvironments();
330 for (const stop of followed.values()) stop();
331 for (const stop of watchedEnvironments.values()) stop();
332 };