Open History to see the last commit
1import { EnvironmentRegistry } from "@t3tools/client-runtime/connection";
2import {
3 EnvironmentRpcSubscriptionObserver,
4 request,
5 type EnvironmentRpcSubscriptionObservation,
6} from "@t3tools/client-runtime/rpc";
7import {
8 type BackgroundScope,
9 type ClientActivityReportInput,
10 type EnvironmentId,
11 WS_METHODS,
12} from "@t3tools/contracts";
13import * as Clock from "effect/Clock";
14import * as DateTime from "effect/DateTime";
15import * as Effect from "effect/Effect";
16import * as Layer from "effect/Layer";
17import * as Queue from "effect/Queue";
18import * as Schedule from "effect/Schedule";
19import * as Stream from "effect/Stream";
20import * as SubscriptionRef from "effect/SubscriptionRef";
21
22import { randomUUID } from "./utils";
23
24const CLIENT_ID_STORAGE_KEY = "t3.backgroundActivity.clientId";
25const REPORT_INTERVAL_MS = 25_000;
26const LEASE_TTL_MS = 45_000;
27const RECENT_INTERACTION_WINDOW_MS = LEASE_TTL_MS;
28const BASELINE_SCOPES: ReadonlyArray<BackgroundScope> = [{ type: "provider-status" }];
29
30interface RetainedScope {
31 readonly environmentId: EnvironmentId;
32 readonly scope: BackgroundScope;
33 refCount: number;
34}
35
36const retainedScopes = new Map<string, RetainedScope>();
37const retainedScopeListeners = new Set<() => void>();
38
39function notifyRetainedScopesChanged(): void {
40 for (const listener of retainedScopeListeners) {
41 try {
42 listener();
43 } catch {
44 // A failing observer must not corrupt retained-scope lifetime.
45 }
46 }
47}
48
49function stableScopeKey(environmentId: EnvironmentId, scope: BackgroundScope): string {
50 switch (scope.type) {
51 case "server-config":
52 case "diagnostics":
53 return JSON.stringify([environmentId, scope.type]);
54 case "provider-status":
55 return JSON.stringify([environmentId, scope.type, scope.instanceId ?? null]);
56 case "vcs-status":
57 case "git-refs":
58 return JSON.stringify([environmentId, scope.type, scope.cwd]);
59 case "thread":
60 return JSON.stringify([environmentId, scope.type, scope.threadId]);
61 }
62}
63
64function getClientId(): string {
65 try {
66 const existing = window.localStorage.getItem(CLIENT_ID_STORAGE_KEY);
67 if (existing) return existing;
68 const next = randomUUID();
69 window.localStorage.setItem(CLIENT_ID_STORAGE_KEY, next);
70 return next;
71 } catch {
72 return "ephemeral-browser-client";
73 }
74}
75
76function resolveClientKind(): ClientActivityReportInput["clientKind"] {
77 return window.desktopBridge ? "desktop-renderer" : "web";
78}
79
80export function wasRecentlyInteracted(lastInteractionAtMs: number, observedAtMs: number): boolean {
81 return (
82 lastInteractionAtMs <= observedAtMs &&
83 observedAtMs - lastInteractionAtMs <= RECENT_INTERACTION_WINDOW_MS
84 );
85}
86
87function createActivityReport(
88 environmentId: EnvironmentId,
89 lastInteractionAtMs: number,
90 observedAtMs: number,
91): ClientActivityReportInput {
92 const scopes = [...BASELINE_SCOPES];
93 for (const entry of retainedScopes.values()) {
94 if (entry.environmentId === environmentId) {
95 scopes.push(entry.scope);
96 }
97 }
98 return {
99 environmentId,
100 clientId: getClientId(),
101 clientKind: resolveClientKind(),
102 visible: document.visibilityState === "visible",
103 focused: document.hasFocus(),
104 recentlyInteracted: wasRecentlyInteracted(lastInteractionAtMs, observedAtMs),
105 appState: document.visibilityState === "visible" ? "active" : "background",
106 scopes,
107 ttlMs: LEASE_TTL_MS,
108 observedAt: DateTime.makeUnsafe(observedAtMs),
109 };
110}
111
112function scopeForSubscription(
113 observation: EnvironmentRpcSubscriptionObservation,
114): BackgroundScope | null {
115 if (observation.method === WS_METHODS.subscribeResourceTelemetry) {
116 return { type: "diagnostics" };
117 }
118 if (observation.method !== WS_METHODS.subscribeVcsStatus) {
119 return null;
120 }
121 const input = observation.input as { readonly cwd?: unknown };
122 return typeof input.cwd === "string" ? { type: "vcs-status", cwd: input.cwd } : null;
123}
124
125function retainBackgroundScope(environmentId: EnvironmentId, scope: BackgroundScope): () => void {
126 const key = stableScopeKey(environmentId, scope);
127 const existing = retainedScopes.get(key);
128 if (existing) {
129 existing.refCount += 1;
130 } else {
131 retainedScopes.set(key, { environmentId, scope, refCount: 1 });
132 notifyRetainedScopesChanged();
133 }
134
135 return () => {
136 const current = retainedScopes.get(key);
137 if (!current) return;
138 current.refCount -= 1;
139 if (current.refCount <= 0) {
140 retainedScopes.delete(key);
141 notifyRetainedScopesChanged();
142 }
143 };
144}
145
146export function observeBackgroundActivitySubscription(
147 observation: EnvironmentRpcSubscriptionObservation,
148): Effect.Effect<Effect.Effect<void>> {
149 const scope = scopeForSubscription(observation);
150 if (scope === null) {
151 return Effect.succeed(Effect.void);
152 }
153 return Effect.sync(() => {
154 const release = retainBackgroundScope(observation.environmentId as EnvironmentId, scope);
155 return Effect.sync(release);
156 });
157}
158
159export function retainedBackgroundScopes(
160 environmentId: EnvironmentId,
161): ReadonlyArray<BackgroundScope> {
162 return Array.from(retainedScopes.values(), (entry) =>
163 entry.environmentId === environmentId ? entry.scope : null,
164 ).filter((scope): scope is BackgroundScope => scope !== null);
165}
166
167export const backgroundActivityObserverLayer = Layer.succeed(
168 EnvironmentRpcSubscriptionObserver,
169 EnvironmentRpcSubscriptionObserver.of({
170 observe: observeBackgroundActivitySubscription,
171 }),
172);
173
174export const backgroundActivityReporterLayer = Layer.effectDiscard(
175 Effect.gen(function* () {
176 if (typeof window === "undefined" || typeof document === "undefined") {
177 return;
178 }
179
180 const registry = yield* EnvironmentRegistry.EnvironmentRegistry;
181 const clock = yield* Clock.Clock;
182 const reportRequests = yield* Queue.sliding<void>(1);
183 const requestReport = () => Queue.offerUnsafe(reportRequests, undefined);
184 let lastInteractionAtMs = clock.currentTimeMillisUnsafe();
185 const recordInteraction = () => {
186 const observedAtMs = clock.currentTimeMillisUnsafe();
187 const wasRecent = wasRecentlyInteracted(lastInteractionAtMs, observedAtMs);
188 lastInteractionAtMs = observedAtMs;
189 if (!wasRecent) {
190 requestReport();
191 }
192 };
193 const passiveListenerOptions = { passive: true } as const;
194
195 const report = Effect.gen(function* () {
196 const observedAtMs = yield* Clock.currentTimeMillis;
197 const entries = yield* SubscriptionRef.get(registry.entries);
198 yield* Effect.forEach(
199 entries.keys(),
200 (environmentId) =>
201 registry
202 .run(
203 environmentId,
204 request(
205 WS_METHODS.serverReportClientActivity,
206 createActivityReport(environmentId, lastInteractionAtMs, observedAtMs),
207 ),
208 )
209 .pipe(Effect.ignore),
210 { concurrency: "unbounded", discard: true },
211 );
212 }).pipe(Effect.withSpan("web.backgroundActivity.report"));
213
214 yield* Effect.acquireRelease(
215 Effect.sync(() => {
216 retainedScopeListeners.add(requestReport);
217 document.addEventListener("visibilitychange", requestReport);
218 window.addEventListener("focus", requestReport);
219 window.addEventListener("blur", requestReport);
220 window.addEventListener("online", requestReport);
221 window.addEventListener("pointermove", recordInteraction);
222 window.addEventListener("keydown", recordInteraction);
223 window.addEventListener("wheel", recordInteraction, passiveListenerOptions);
224 window.addEventListener("touchstart", recordInteraction, passiveListenerOptions);
225 }),
226 () =>
227 Effect.sync(() => {
228 retainedScopeListeners.delete(requestReport);
229 document.removeEventListener("visibilitychange", requestReport);
230 window.removeEventListener("focus", requestReport);
231 window.removeEventListener("blur", requestReport);
232 window.removeEventListener("online", requestReport);
233 window.removeEventListener("pointermove", recordInteraction);
234 window.removeEventListener("keydown", recordInteraction);
235 window.removeEventListener("wheel", recordInteraction);
236 window.removeEventListener("touchstart", recordInteraction);
237 }),
238 );
239
240 yield* SubscriptionRef.changes(registry.entries).pipe(
241 Stream.runForEach(() => Effect.sync(requestReport)),
242 Effect.forkScoped,
243 );
244 yield* Stream.fromQueue(reportRequests).pipe(
245 Stream.debounce("250 millis"),
246 Stream.runForEach(() => report),
247 Effect.forkScoped,
248 );
249 yield* Effect.sync(requestReport).pipe(
250 Effect.repeat(Schedule.spaced(`${REPORT_INTERVAL_MS} millis`)),
251 Effect.forkScoped,
252 );
253 }),
254);