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

agentOpenedPreviews.ts

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