Open History to see the last commit
1/**
2 * In-memory PreviewManager implementation.
3 *
4 * Sessions are keyed by `(threadId, tabId)`; a single thread can host
5 * multiple tabs (browser-style). `open` always creates a new tab — tab
6 * lifecycle is owned by the renderer.
7 *
8 * Events are published via Effect's `PubSub`, so subscriber failures are
9 * isolated from the publishing call (a closed WS subscriber queue cannot
10 * fail an in-progress `navigate()`).
11 */
12import {
13 type PreviewCloseInput,
14 type PreviewEvent,
15 type PreviewError,
16 PreviewInvalidUrlError,
17 type PreviewListInput,
18 type PreviewListResult,
19 type PreviewNavigateInput,
20 type PreviewOpenInput,
21 type PreviewRefreshInput,
22 type PreviewReportStatusInput,
23 type PreviewResizeInput,
24 FILL_PREVIEW_VIEWPORT,
25 PreviewSessionLookupError,
26 type PreviewSessionSnapshot,
27 type PreviewViewportSetting,
28} from "@t3tools/contracts";
29import {
30 isPreviewUrlNormalizationError,
31 newPreviewTabId,
32 normalizePreviewUrl,
33} from "@t3tools/shared/preview";
34import * as NodeCrypto from "node:crypto";
35import * as Context from "effect/Context";
36import * as DateTime from "effect/DateTime";
37import * as Effect from "effect/Effect";
38import * as Layer from "effect/Layer";
39import * as PubSub from "effect/PubSub";
40import * as Scope from "effect/Scope";
41import * as Stream from "effect/Stream";
42import * as SynchronizedRef from "effect/SynchronizedRef";
43
44export class PreviewManager extends Context.Service<
45 PreviewManager,
46 {
47 readonly open: (input: PreviewOpenInput) => Effect.Effect<PreviewSessionSnapshot, PreviewError>;
48 readonly navigate: (
49 input: PreviewNavigateInput,
50 ) => Effect.Effect<PreviewSessionSnapshot, PreviewError>;
51 readonly reportStatus: (input: PreviewReportStatusInput) => Effect.Effect<void, PreviewError>;
52 readonly resize: (
53 input: PreviewResizeInput,
54 ) => Effect.Effect<PreviewSessionSnapshot, PreviewError>;
55 readonly refresh: (input: PreviewRefreshInput) => Effect.Effect<void, PreviewError>;
56 readonly close: (input: PreviewCloseInput) => Effect.Effect<void, PreviewError>;
57 readonly list: (input: PreviewListInput) => Effect.Effect<PreviewListResult>;
58 readonly events: Stream.Stream<PreviewEvent>;
59 readonly subscribeEvents: Effect.Effect<PubSub.Subscription<PreviewEvent>, never, Scope.Scope>;
60 }
61>()("t3/preview/Manager/PreviewManager") {}
62
63interface PreviewSessionState {
64 readonly threadId: string;
65 readonly tabId: string;
66 readonly snapshot: PreviewSessionSnapshot;
67}
68
69interface ManagerState {
70 /** All sessions across every thread, keyed by `${threadId}\u0000${tabId}`. */
71 readonly sessions: ReadonlyMap<string, PreviewSessionState>;
72 /** Global monotonic revision establishing list/event ordering. */
73 readonly revision: number;
74}
75
76const initialState: ManagerState = { sessions: new Map(), revision: 0 };
77
78type PreviewEventDraft = PreviewEvent extends infer Event
79 ? Event extends { readonly revision: number }
80 ? Omit<Event, "revision" | "serverEpoch">
81 : never
82 : never;
83
84const compositeKey = (threadId: string, tabId: string): string => `${threadId}\u0000${tabId}`;
85
86const sessionsForThread = (
87 state: ManagerState,
88 threadId: string,
89): ReadonlyArray<PreviewSessionState> => {
90 const out: PreviewSessionState[] = [];
91 for (const session of state.sessions.values()) {
92 if (session.threadId === threadId) out.push(session);
93 }
94 return out;
95};
96
97const normalizeUrl = (rawUrl: string): Effect.Effect<string, PreviewInvalidUrlError> =>
98 Effect.try({
99 try: () => normalizePreviewUrl(rawUrl),
100 catch: (cause) => {
101 if (isPreviewUrlNormalizationError(cause)) {
102 return new PreviewInvalidUrlError({
103 inputLength: cause.inputLength,
104 reason: cause.reason,
105 protocol: cause.protocol,
106 cause,
107 });
108 }
109
110 return new PreviewInvalidUrlError({
111 inputLength: rawUrl.length,
112 reason: "unexpected",
113 cause,
114 });
115 },
116 });
117
118const currentIsoTimestamp = DateTime.now.pipe(Effect.map(DateTime.formatIso));
119
120const buildLoadingSnapshot = (input: {
121 readonly threadId: string;
122 readonly tabId: string;
123 readonly url: string;
124 readonly title: string;
125 readonly viewport: PreviewViewportSetting;
126 readonly updatedAt: string;
127}): PreviewSessionSnapshot => ({
128 threadId: input.threadId,
129 tabId: input.tabId,
130 navStatus: { _tag: "Loading", url: input.url, title: input.title },
131 canGoBack: false,
132 canGoForward: false,
133 viewport: input.viewport,
134 updatedAt: input.updatedAt,
135});
136
137const buildIdleSnapshot = (input: {
138 readonly threadId: string;
139 readonly tabId: string;
140 readonly viewport: PreviewViewportSetting;
141 readonly updatedAt: string;
142}): PreviewSessionSnapshot => ({
143 threadId: input.threadId,
144 tabId: input.tabId,
145 navStatus: { _tag: "Idle" },
146 canGoBack: false,
147 canGoForward: false,
148 viewport: input.viewport,
149 updatedAt: input.updatedAt,
150});
151
152export const make = Effect.gen(function* PreviewManagerMake() {
153 const serverEpoch = NodeCrypto.randomUUID();
154 const stateRef = yield* SynchronizedRef.make<ManagerState>(initialState);
155 // Unbounded PubSub is fine here — events are tiny and we don't want to
156 // block publishers if a subscriber is slow. WS clients backpressure on
157 // their own queues downstream.
158 const eventsPubSub = yield* PubSub.unbounded<PreviewEvent>();
159 const events: Stream.Stream<PreviewEvent> = Stream.fromPubSub(eventsPubSub);
160
161 /**
162 * Atomic read-modify-write over the session for `(threadId, tabId)`. The
163 * mutator runs under the SynchronizedRef so concurrent writers cannot
164 * interleave. Lookup failures travel through the modify result so both
165 * branches yield the same `[A, S]` shape `modifyEffect` requires.
166 *
167 * The event is published INSIDE the lock so observers see events in the
168 * same order as the underlying state transitions. Publishing an unbounded
169 * PubSub is non-blocking, so this is cheap.
170 */
171 const mutateExistingSession = <R, E>(
172 threadId: string,
173 tabId: string,
174 mutator: (
175 session: PreviewSessionState,
176 ) => Effect.Effect<{ next: PreviewSessionState; emit: PreviewEventDraft | null; result: R }, E>,
177 ): Effect.Effect<R, E | PreviewSessionLookupError> => {
178 type ModifyResult =
179 | { kind: "fail"; error: PreviewSessionLookupError }
180 | { kind: "ok"; result: R };
181
182 return SynchronizedRef.modifyEffect(stateRef, (state) => {
183 const session = state.sessions.get(compositeKey(threadId, tabId));
184 if (!session) {
185 return Effect.succeed([
186 { kind: "fail", error: new PreviewSessionLookupError({ threadId, tabId }) },
187 state,
188 ] as readonly [ModifyResult, ManagerState]);
189 }
190 return mutator(session).pipe(
191 Effect.flatMap(
192 Effect.fn("PreviewManager.commitMutation")(function* ({ next, emit, result }) {
193 const revision = emit ? state.revision + 1 : state.revision;
194 if (emit) {
195 yield* PubSub.publish(eventsPubSub, {
196 ...emit,
197 revision,
198 serverEpoch,
199 } as PreviewEvent);
200 }
201 const sessions = new Map(state.sessions);
202 sessions.set(compositeKey(threadId, tabId), next);
203 return [{ kind: "ok", result } as ModifyResult, { sessions, revision }] as readonly [
204 ModifyResult,
205 ManagerState,
206 ];
207 }),
208 ),
209 );
210 }).pipe(
211 Effect.flatMap((modify) =>
212 modify.kind === "fail" ? Effect.fail(modify.error) : Effect.succeed(modify.result),
213 ),
214 );
215 };
216
217 const open: PreviewManager["Service"]["open"] = Effect.fn("PreviewManager.open")(
218 function* (input) {
219 const tabId = newPreviewTabId();
220 const updatedAt = yield* currentIsoTimestamp;
221 // Clients with a configured default send the viewport up front so the
222 // session is born at the right size; older clients omit it and keep the
223 // historical fill-panel behaviour.
224 const viewport = input.viewport ?? FILL_PREVIEW_VIEWPORT;
225 const snapshot = input.url
226 ? buildLoadingSnapshot({
227 threadId: input.threadId,
228 tabId,
229 url: yield* normalizeUrl(input.url),
230 title: "",
231 viewport,
232 updatedAt,
233 })
234 : buildIdleSnapshot({ threadId: input.threadId, tabId, viewport, updatedAt });
235 yield* SynchronizedRef.modifyEffect(stateRef, (state) =>
236 Effect.gen(function* () {
237 const revision = state.revision + 1;
238 const sessions = new Map(state.sessions);
239 sessions.set(compositeKey(input.threadId, tabId), {
240 threadId: input.threadId,
241 tabId,
242 snapshot,
243 });
244 yield* PubSub.publish(eventsPubSub, {
245 type: "opened",
246 threadId: input.threadId,
247 tabId,
248 createdAt: snapshot.updatedAt,
249 serverEpoch,
250 revision,
251 snapshot,
252 });
253 return [snapshot, { sessions, revision }] as const;
254 }),
255 );
256 return snapshot;
257 },
258 );
259
260 const navigate: PreviewManager["Service"]["navigate"] = Effect.fn("PreviewManager.navigate")(
261 function* (input) {
262 const url = yield* normalizeUrl(input.url);
263 return yield* mutateExistingSession(
264 input.threadId,
265 input.tabId,
266 Effect.fn("PreviewManager.navigateSession")(function* (session) {
267 const updatedAt = yield* currentIsoTimestamp;
268 const previousTitle =
269 session.snapshot.navStatus._tag === "Idle" ? "" : session.snapshot.navStatus.title;
270 const resolvedTitle = input.resolvedTitle ?? previousTitle;
271 const snapshot: PreviewSessionSnapshot = {
272 threadId: session.threadId,
273 tabId: session.tabId,
274 navStatus: { _tag: "Success", url, title: resolvedTitle },
275 canGoBack: session.snapshot.canGoBack,
276 canGoForward: session.snapshot.canGoForward,
277 viewport: session.snapshot.viewport ?? FILL_PREVIEW_VIEWPORT,
278 updatedAt,
279 };
280 return {
281 next: { ...session, snapshot },
282 emit: {
283 type: "navigated",
284 threadId: session.threadId,
285 tabId: session.tabId,
286 createdAt: snapshot.updatedAt,
287 snapshot,
288 },
289 result: snapshot,
290 };
291 }),
292 );
293 },
294 );
295
296 const reportStatus: PreviewManager["Service"]["reportStatus"] = Effect.fn(
297 "PreviewManager.reportStatus",
298 )(function* (input) {
299 yield* mutateExistingSession(
300 input.threadId,
301 input.tabId,
302 Effect.fn("PreviewManager.reportSessionStatus")(function* (session) {
303 const updatedAt = yield* currentIsoTimestamp;
304 const snapshot: PreviewSessionSnapshot = {
305 threadId: session.threadId,
306 tabId: session.tabId,
307 navStatus: input.navStatus,
308 canGoBack: input.canGoBack,
309 canGoForward: input.canGoForward,
310 viewport: session.snapshot.viewport ?? FILL_PREVIEW_VIEWPORT,
311 updatedAt,
312 };
313 const emit: PreviewEventDraft =
314 input.navStatus._tag === "LoadFailed"
315 ? {
316 type: "failed",
317 threadId: session.threadId,
318 tabId: session.tabId,
319 createdAt: snapshot.updatedAt,
320 url: input.navStatus.url,
321 title: input.navStatus.title,
322 code: input.navStatus.code,
323 description: input.navStatus.description,
324 }
325 : {
326 type: "navigated",
327 threadId: session.threadId,
328 tabId: session.tabId,
329 createdAt: snapshot.updatedAt,
330 snapshot,
331 };
332 return {
333 next: { ...session, snapshot },
334 emit,
335 result: undefined as void,
336 };
337 }),
338 );
339 });
340
341 const resize: PreviewManager["Service"]["resize"] = Effect.fn("PreviewManager.resize")(
342 function* (input) {
343 return yield* mutateExistingSession(
344 input.threadId,
345 input.tabId,
346 Effect.fn("PreviewManager.resizeSession")(function* (session) {
347 const updatedAt = yield* currentIsoTimestamp;
348 const snapshot: PreviewSessionSnapshot = {
349 ...session.snapshot,
350 viewport: input.viewport,
351 updatedAt,
352 };
353 return {
354 next: { ...session, snapshot },
355 emit: {
356 type: "resized",
357 threadId: session.threadId,
358 tabId: session.tabId,
359 createdAt: snapshot.updatedAt,
360 snapshot,
361 },
362 result: snapshot,
363 };
364 }),
365 );
366 },
367 );
368
369 const refresh: PreviewManager["Service"]["refresh"] = Effect.fn("PreviewManager.refresh")(
370 function* (input) {
371 // Verify the session exists; the desktop bridge handles the actual reload
372 // and will report progress back via `reportStatus`. No event emitted.
373 yield* mutateExistingSession(input.threadId, input.tabId, (session) =>
374 Effect.succeed({ next: session, emit: null, result: undefined as void }),
375 );
376 },
377 );
378
379 const close: PreviewManager["Service"]["close"] = Effect.fn("PreviewManager.close")(
380 function* (input) {
381 const createdAt = yield* currentIsoTimestamp;
382 yield* SynchronizedRef.modifyEffect(stateRef, (state) => {
383 const eventsToEmit: PreviewEvent[] = [];
384 const sessions = new Map(state.sessions);
385 const targets = input.tabId
386 ? [state.sessions.get(compositeKey(input.threadId, input.tabId))].filter(
387 (entry): entry is PreviewSessionState => entry !== undefined,
388 )
389 : sessionsForThread(state, input.threadId);
390 let revision = state.revision;
391 for (const target of targets) {
392 revision += 1;
393 sessions.delete(compositeKey(target.threadId, target.tabId));
394 eventsToEmit.push({
395 type: "closed",
396 threadId: target.threadId,
397 tabId: target.tabId,
398 createdAt,
399 serverEpoch,
400 revision,
401 });
402 }
403 if (eventsToEmit.length === 0) {
404 return Effect.succeed([undefined, state] as const);
405 }
406 return Effect.as(
407 Effect.forEach(eventsToEmit, (event) => PubSub.publish(eventsPubSub, event), {
408 discard: true,
409 }),
410 [undefined, { sessions, revision }] as const,
411 );
412 });
413 },
414 );
415
416 const list: PreviewManager["Service"]["list"] = Effect.fn("PreviewManager.list")(
417 function* (input) {
418 return yield* SynchronizedRef.get(stateRef).pipe(
419 Effect.map(
420 (state): PreviewListResult => ({
421 sessions: sessionsForThread(state, input.threadId)
422 .map((s) => s.snapshot)
423 .toSorted((a, b) => a.updatedAt.localeCompare(b.updatedAt)),
424 serverEpoch,
425 revision: state.revision,
426 }),
427 ),
428 );
429 },
430 );
431
432 return PreviewManager.of({
433 open,
434 navigate,
435 reportStatus,
436 resize,
437 refresh,
438 close,
439 list,
440 events,
441 subscribeEvents: PubSub.subscribe(eventsPubSub),
442 });
443}).pipe(Effect.withSpan("PreviewManager.make"));
444
445export const layer = Layer.effect(PreviewManager, make);