@devries-cameron20 / t3code Mirror · read-only
Fork 0

The best way to control Claude Code, Codex and more from any computer or phone

Mirrored from https://github.com/Camo67/t3code.git

Synced Nov 21, 04:45 UTC

main
ts 513 lines 17.6 KB
Raw
1 import {
2 type PreviewCloseInput,
3 type PreviewEvent,
4 type PreviewError,
5 PreviewInvalidUrlError,
6 type PreviewListInput,
7 type PreviewListResult,
8 type PreviewOpenInput,
9 type PreviewReportStatusInput,
10 type PreviewResizeInput,
11 type PreviewAdjustInput,
12 FILL_PREVIEW_VIEWPORT,
13 PreviewSessionLookupError,
14 type PreviewSessionSnapshot,
15 } from "@t3tools/contracts";
16 import {
17 isPreviewUrlNormalizationError,
18 newPreviewTabId,
19 normalizePreviewUrl,
20 } from "@t3tools/shared/preview";
21 import * as Context from "effect/Context";
22 import * as SecureRandom from "effect/crypto/SecureRandom";
23 import * as DateTime from "effect/DateTime";
24 import * as Effect from "effect/Effect";
25 import * as Layer from "effect/Layer";
26 import * as PubSub from "effect/PubSub";
27 import * as Scope from "effect/Scope";
28 import * as Stream from "effect/Stream";
29 import * as SynchronizedRef from "effect/SynchronizedRef";
30 import { PreviewControlRequiredError } from "@t3tools/contracts";
31
32 export class PreviewManager extends Context.Service<
33 PreviewManager,
34 {
35 readonly open: (
36 input: PreviewOpenInput & {
37 readonly automationOwner?: string;
38 /** Runs before the `opened` event publishes, so subscribers find state keyed by the tab. */
39 readonly beforePublish?: (snapshot: PreviewSessionSnapshot) => void;
40 },
41 ) => Effect.Effect<PreviewSessionSnapshot, PreviewError>;
42 readonly reportStatus: (
43 input: PreviewReportStatusInput & { readonly serverControlled?: boolean },
44 ) => Effect.Effect<void, PreviewError>;
45 /** Records that a server tab runs headless. It stays headless until it closes. */
46 readonly markHeadless: (
47 input: PreviewCloseInput & { readonly tabId: string },
48 ) => Effect.Effect<void, PreviewError>;
49 /** Publishes the tab's unchanged snapshot again, for clients that dropped the tab. */
50 readonly announce: (
51 input: PreviewCloseInput & { readonly tabId: string },
52 ) => Effect.Effect<void, PreviewError>;
53 readonly requestReveal: (
54 input: PreviewCloseInput & { readonly tabId: string; readonly force: boolean },
55 ) => Effect.Effect<void, PreviewError>;
56 readonly resize: (
57 input: PreviewResizeInput,
58 ) => Effect.Effect<PreviewSessionSnapshot, PreviewError>;
59 readonly adjust: (
60 input: PreviewAdjustInput,
61 ) => Effect.Effect<PreviewSessionSnapshot, PreviewError>;
62 readonly close: (input: PreviewCloseInput) => Effect.Effect<void, PreviewError>;
63 /** Runs before closed events publish, while clients still own their page surfaces. */
64 readonly registerBeforeClose: (
65 handler: (snapshots: ReadonlyArray<PreviewSessionSnapshot>) => Effect.Effect<void>,
66 ) => Effect.Effect<void, never, Scope.Scope>;
67 readonly list: (input: PreviewListInput) => Effect.Effect<PreviewListResult>;
68 readonly events: Stream.Stream<PreviewEvent>;
69 readonly subscribeEvents: Effect.Effect<PubSub.Subscription<PreviewEvent>, never, Scope.Scope>;
70 }
71 >()("t3/preview/Manager/PreviewManager") {}
72
73 interface PreviewSessionState {
74 readonly threadId: string;
75 readonly tabId: string;
76 readonly snapshot: PreviewSessionSnapshot;
77 }
78
79 interface ManagerState {
80 readonly sessions: ReadonlyMap<string, PreviewSessionState>;
81 readonly revision: number;
82 }
83
84 const initialState: ManagerState = { sessions: new Map(), revision: 0 };
85
86 type PreviewEventDraft = PreviewEvent extends infer Event
87 ? Event extends { readonly revision: number }
88 ? Omit<Event, "revision" | "serverEpoch">
89 : never
90 : never;
91
92 const compositeKey = (threadId: string, tabId: string): string => `${threadId}\u0000${tabId}`;
93
94 const sessionsForThread = (
95 state: ManagerState,
96 threadId: string,
97 ): ReadonlyArray<PreviewSessionState> => {
98 const out: PreviewSessionState[] = [];
99 for (const session of state.sessions.values()) {
100 if (session.threadId === threadId) out.push(session);
101 }
102 return out;
103 };
104
105 const normalizeUrl = (rawUrl: string): Effect.Effect<string, PreviewInvalidUrlError> =>
106 Effect.try({
107 try: () => normalizePreviewUrl(rawUrl),
108 catch: (cause) => {
109 if (isPreviewUrlNormalizationError(cause)) {
110 return new PreviewInvalidUrlError({
111 inputLength: cause.inputLength,
112 reason: cause.reason,
113 protocol: cause.protocol,
114 cause,
115 });
116 }
117
118 return new PreviewInvalidUrlError({
119 inputLength: rawUrl.length,
120 reason: "unexpected",
121 cause,
122 });
123 },
124 });
125
126 const currentIsoTimestamp = DateTime.now.pipe(Effect.map(DateTime.formatIso));
127
128 /** @public */
129 export const make = Effect.gen(function* PreviewManagerMake() {
130 const random = yield* SecureRandom.SecureRandom;
131 const serverEpoch = yield* random.uuidV4();
132 const stateRef = yield* SynchronizedRef.make<ManagerState>(initialState);
133 const eventsPubSub = yield* PubSub.unbounded<PreviewEvent>();
134 const events: Stream.Stream<PreviewEvent> = Stream.fromPubSub(eventsPubSub);
135 const beforeClose = new Set<
136 (snapshots: ReadonlyArray<PreviewSessionSnapshot>) => Effect.Effect<void>
137 >();
138 const registerBeforeClose: PreviewManager["Service"]["registerBeforeClose"] = (handler) =>
139 Effect.acquireRelease(
140 Effect.sync(() => beforeClose.add(handler)),
141 () => Effect.sync(() => beforeClose.delete(handler)),
142 ).pipe(Effect.asVoid);
143
144 /** Publish inside the lock to preserve state-transition order. */
145 const mutateExistingSession = <R, E>(
146 threadId: string,
147 tabId: string,
148 mutator: (
149 session: PreviewSessionState,
150 ) => Effect.Effect<{ next: PreviewSessionState; emit: PreviewEventDraft | null; result: R }, E>,
151 ): Effect.Effect<R, E | PreviewSessionLookupError> => {
152 type ModifyResult =
153 | { kind: "fail"; error: PreviewSessionLookupError }
154 | { kind: "ok"; result: R };
155
156 return SynchronizedRef.modifyEffect(stateRef, (state) => {
157 const session = state.sessions.get(compositeKey(threadId, tabId));
158 if (!session) {
159 return Effect.succeed([
160 { kind: "fail", error: new PreviewSessionLookupError({ threadId, tabId }) },
161 state,
162 ] as readonly [ModifyResult, ManagerState]);
163 }
164 return mutator(session).pipe(
165 Effect.flatMap(
166 Effect.fn("PreviewManager.commitMutation")(function* ({ next, emit, result }) {
167 const revision = emit ? state.revision + 1 : state.revision;
168 if (emit) {
169 yield* PubSub.publish(eventsPubSub, {
170 ...emit,
171 revision,
172 serverEpoch,
173 } as PreviewEvent);
174 }
175 const sessions = new Map(state.sessions);
176 sessions.set(compositeKey(threadId, tabId), next);
177 return [{ kind: "ok", result } as ModifyResult, { sessions, revision }] as readonly [
178 ModifyResult,
179 ManagerState,
180 ];
181 }),
182 ),
183 );
184 }).pipe(
185 Effect.flatMap((modify) =>
186 modify.kind === "fail" ? Effect.fail(modify.error) : Effect.succeed(modify.result),
187 ),
188 );
189 };
190
191 const open: PreviewManager["Service"]["open"] = Effect.fn("PreviewManager.open")(
192 function* (input) {
193 const runtime = input.runtime;
194 // Persisted client surfaces must not bind to a different tab after a server restart.
195 const tabId = `${newPreviewTabId()}${runtime === "server" ? `_${serverEpoch}` : ""}`;
196 const updatedAt = yield* currentIsoTimestamp;
197 const snapshot: PreviewSessionSnapshot = {
198 threadId: input.threadId,
199 tabId,
200 navStatus: input.url
201 ? { _tag: "Loading", url: yield* normalizeUrl(input.url), title: "" }
202 : { _tag: "Idle" },
203 canGoBack: false,
204 canGoForward: false,
205 viewport: input.viewport ?? FILL_PREVIEW_VIEWPORT,
206 ...(input.profileId === undefined ? {} : { profileId: input.profileId }),
207 ...(runtime === undefined ? {} : { runtime }),
208 ...(input.colorScheme === undefined ? {} : { colorScheme: input.colorScheme }),
209 ...(input.zoomFactor === undefined ? {} : { zoomFactor: input.zoomFactor }),
210 ...(runtime === "server" && input.automationOwner !== undefined
211 ? { automationOwner: input.automationOwner }
212 : {}),
213 ...(input.reveal === undefined ? {} : { reveal: input.reveal }),
214 updatedAt,
215 };
216 yield* SynchronizedRef.modifyEffect(stateRef, (state) =>
217 Effect.gen(function* () {
218 const revision = state.revision + 1;
219 const sessions = new Map(state.sessions);
220 sessions.set(compositeKey(input.threadId, tabId), {
221 threadId: input.threadId,
222 tabId,
223 snapshot,
224 });
225 input.beforePublish?.(snapshot);
226 yield* PubSub.publish(eventsPubSub, {
227 type: "opened",
228 threadId: input.threadId,
229 tabId,
230 createdAt: snapshot.updatedAt,
231 serverEpoch,
232 revision,
233 snapshot,
234 });
235 return [snapshot, { sessions, revision }] as const;
236 }),
237 );
238 return snapshot;
239 },
240 );
241
242 const reportStatus: PreviewManager["Service"]["reportStatus"] = Effect.fn(
243 "PreviewManager.reportStatus",
244 )(function* (input) {
245 yield* mutateExistingSession(
246 input.threadId,
247 input.tabId,
248 Effect.fn("PreviewManager.reportSessionStatus")(function* (session) {
249 if (session.snapshot.runtime === "server" && !input.serverControlled)
250 return yield* new PreviewControlRequiredError({ tabId: input.tabId });
251 const updatedAt = yield* currentIsoTimestamp;
252 const snapshot: PreviewSessionSnapshot = {
253 ...session.snapshot,
254 navStatus: input.navStatus,
255 canGoBack: input.canGoBack,
256 canGoForward: input.canGoForward,
257 viewport: session.snapshot.viewport ?? FILL_PREVIEW_VIEWPORT,
258 updatedAt,
259 };
260 const emit: PreviewEventDraft =
261 input.navStatus._tag === "LoadFailed"
262 ? {
263 type: "failed",
264 threadId: session.threadId,
265 tabId: session.tabId,
266 createdAt: snapshot.updatedAt,
267 url: input.navStatus.url,
268 title: input.navStatus.title,
269 code: input.navStatus.code,
270 description: input.navStatus.description,
271 ...(input.navStatus.download === undefined
272 ? {}
273 : { download: input.navStatus.download }),
274 }
275 : {
276 type: "navigated",
277 threadId: session.threadId,
278 tabId: session.tabId,
279 createdAt: snapshot.updatedAt,
280 snapshot,
281 };
282 return {
283 next: { ...session, snapshot },
284 emit,
285 result: undefined as void,
286 };
287 }),
288 );
289 });
290
291 const markHeadless: PreviewManager["Service"]["markHeadless"] = Effect.fn(
292 "PreviewManager.markHeadless",
293 )(function* (input) {
294 return yield* mutateExistingSession(
295 input.threadId,
296 input.tabId,
297 Effect.fn("PreviewManager.markSessionHeadless")(function* (session) {
298 if (session.snapshot.headless) return { next: session, emit: null, result: undefined };
299 const snapshot: PreviewSessionSnapshot = {
300 ...session.snapshot,
301 headless: true,
302 updatedAt: yield* currentIsoTimestamp,
303 };
304 return {
305 next: { ...session, snapshot },
306 emit: {
307 type: "resized",
308 threadId: session.threadId,
309 tabId: session.tabId,
310 createdAt: snapshot.updatedAt,
311 snapshot,
312 },
313 result: undefined,
314 };
315 }),
316 );
317 });
318
319 const announce: PreviewManager["Service"]["announce"] = Effect.fn("PreviewManager.announce")(
320 function* (input) {
321 return yield* mutateExistingSession(
322 input.threadId,
323 input.tabId,
324 Effect.fn("PreviewManager.announceSession")(function* (session) {
325 return {
326 next: session,
327 emit: {
328 type: "resized",
329 threadId: session.threadId,
330 tabId: session.tabId,
331 createdAt: yield* currentIsoTimestamp,
332 snapshot: session.snapshot,
333 },
334 result: undefined,
335 };
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 adjust: PreviewManager["Service"]["adjust"] = Effect.fn("PreviewManager.adjust")(
370 function* (input) {
371 return yield* mutateExistingSession(
372 input.threadId,
373 input.tabId,
374 Effect.fn("PreviewManager.adjustSession")(function* (session) {
375 const updatedAt = yield* currentIsoTimestamp;
376 const snapshot: PreviewSessionSnapshot = {
377 ...session.snapshot,
378 ...(input.colorScheme === undefined ? {} : { colorScheme: input.colorScheme }),
379 ...(input.zoomFactor === undefined ? {} : { zoomFactor: input.zoomFactor }),
380 updatedAt,
381 };
382 const request =
383 input.hardReload || input.clear
384 ? {
385 request: {
386 ...(input.hardReload ? { hardReload: true } : {}),
387 ...(input.clear ? { clear: input.clear } : {}),
388 },
389 }
390 : {};
391 return {
392 next: { ...session, snapshot },
393 emit: {
394 ...request,
395 type: "resized",
396 threadId: session.threadId,
397 tabId: session.tabId,
398 createdAt: snapshot.updatedAt,
399 snapshot,
400 },
401 result: snapshot,
402 };
403 }),
404 );
405 },
406 );
407
408 const close: PreviewManager["Service"]["close"] = Effect.fn("PreviewManager.close")(
409 function* (input) {
410 // Unload runs outside the state lock; tabs opened meanwhile belong to a later close.
411 const current = yield* SynchronizedRef.get(stateRef);
412 const targets = input.tabId
413 ? [current.sessions.get(compositeKey(input.threadId, input.tabId))].filter(
414 (entry): entry is PreviewSessionState => entry !== undefined,
415 )
416 : sessionsForThread(current, input.threadId);
417 yield* Effect.forEach(
418 [...beforeClose],
419 (handler) => handler(targets.map((target) => target.snapshot)),
420 { discard: true },
421 );
422 const createdAt = yield* currentIsoTimestamp;
423 yield* SynchronizedRef.modifyEffect(stateRef, (state) => {
424 const eventsToEmit: PreviewEvent[] = [];
425 const sessions = new Map(state.sessions);
426 let revision = state.revision;
427 for (const target of targets) {
428 if (!sessions.delete(compositeKey(target.threadId, target.tabId))) continue;
429 revision += 1;
430 eventsToEmit.push({
431 type: "closed",
432 threadId: target.threadId,
433 tabId: target.tabId,
434 createdAt,
435 serverEpoch,
436 revision,
437 });
438 }
439 if (eventsToEmit.length === 0) {
440 return Effect.succeed([undefined, state] as const);
441 }
442 return Effect.as(
443 Effect.forEach(eventsToEmit, (event) => PubSub.publish(eventsPubSub, event), {
444 discard: true,
445 }),
446 [undefined, { sessions, revision }] as const,
447 );
448 });
449 },
450 );
451
452 const list: PreviewManager["Service"]["list"] = Effect.fn("PreviewManager.list")(
453 function* (input) {
454 return yield* SynchronizedRef.get(stateRef).pipe(
455 Effect.map((state): PreviewListResult => ({
456 sessions: sessionsForThread(state, input.threadId)
457 .map((s) => s.snapshot)
458 .toSorted((a, b) => a.updatedAt.localeCompare(b.updatedAt)),
459 serverEpoch,
460 revision: state.revision,
461 })),
462 );
463 },
464 );
465
466 const requestReveal: PreviewManager["Service"]["requestReveal"] = Effect.fn(
467 "PreviewManager.requestReveal",
468 )(function* (input) {
469 yield* mutateExistingSession(
470 input.threadId,
471 input.tabId,
472 Effect.fn("PreviewManager.revealSession")(function* (session) {
473 const snapshot = {
474 ...session.snapshot,
475 reveal: true,
476 revealRequest: {
477 id: yield* random.uuidV4(),
478 force: input.force,
479 },
480 updatedAt: yield* currentIsoTimestamp,
481 };
482 return {
483 next: { ...session, snapshot },
484 emit: {
485 type: "navigated" as const,
486 threadId: session.threadId,
487 tabId: session.tabId,
488 createdAt: snapshot.updatedAt,
489 snapshot,
490 },
491 result: undefined,
492 };
493 }),
494 );
495 });
496
497 return PreviewManager.of({
498 open,
499 requestReveal,
500 reportStatus,
501 markHeadless,
502 announce,
503 resize,
504 adjust,
505 close,
506 registerBeforeClose,
507 list,
508 events,
509 subscribeEvents: PubSub.subscribe(eventsPubSub),
510 });
511 }).pipe(Effect.withSpan("PreviewManager.make"));
512
513 export const layer = Layer.effect(PreviewManager, make);