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