Open History to see the last commit
1import {
2 DesktopHostTelemetryMessage,
3 type DesktopHostTelemetrySnapshot,
4 type DesktopTelemetryControlMessage,
5 type DesktopTelemetryCancelDesktopUpdate,
6 type DesktopTelemetryCommitDesktopUpdate,
7 type DesktopTelemetryRequestDesktopUpdate,
8 type DesktopUpdateStatusReport,
9 type HostPowerSnapshot,
10} from "@t3tools/contracts";
11import * as Cause from "effect/Cause";
12import * as Context from "effect/Context";
13import * as DateTime from "effect/DateTime";
14import * as Duration from "effect/Duration";
15import * as Effect from "effect/Effect";
16import * as Layer from "effect/Layer";
17import * as Option from "effect/Option";
18import * as PubSub from "effect/PubSub";
19import * as Queue from "effect/Queue";
20import * as Ref from "effect/Ref";
21import * as Schema from "effect/Schema";
22import * as Stream from "effect/Stream";
23
24import * as ElectronApp from "../electron/ElectronApp.ts";
25import * as ElectronPowerMonitor from "../electron/ElectronPowerMonitor.ts";
26import * as DesktopRendererHistory from "./DesktopRendererHistory.ts";
27
28const LIVE_SAMPLE_INTERVAL = Duration.seconds(1);
29const BATTERY_SAMPLE_INTERVAL = Duration.seconds(5);
30const CONSTRAINED_SAMPLE_INTERVAL = Duration.seconds(15);
31const DEFAULT_HOST_POWER_ACTIVE_INTERVAL = Duration.seconds(30);
32const DEFAULT_HOST_POWER_IDLE_INTERVAL = Duration.minutes(2);
33const IDLE_THRESHOLD_SECONDS = 60;
34const encodeMessage = Schema.encodeSync(Schema.fromJsonString(DesktopHostTelemetryMessage));
35const textEncoder = new TextEncoder();
36
37type PowerEvent =
38 | { readonly type: "locked"; readonly value: boolean }
39 | { readonly type: "suspended"; readonly value: boolean }
40 | { readonly type: "onBattery"; readonly value: boolean }
41 | { readonly type: "thermal"; readonly value: HostPowerSnapshot["thermalState"] }
42 | { readonly type: "speedLimit"; readonly value: number };
43
44interface PowerState {
45 readonly idle: HostPowerSnapshot["idle"];
46 readonly locked: HostPowerSnapshot["locked"];
47 readonly lockedEventPending: boolean;
48 readonly suspended: boolean;
49 readonly suspendedEventPending: boolean;
50 readonly onBattery: HostPowerSnapshot["onBattery"];
51 readonly onBatteryEventPending: boolean;
52 readonly thermalState: HostPowerSnapshot["thermalState"];
53 readonly speedLimitPercent: Option.Option<number>;
54}
55
56interface HostPowerIntervals {
57 readonly active: Duration.Duration;
58 readonly idle: Duration.Duration;
59}
60
61export class DesktopTelemetryPublisher extends Context.Service<
62 DesktopTelemetryPublisher,
63 {
64 readonly latest: Effect.Effect<Option.Option<DesktopHostTelemetrySnapshot>>;
65 readonly changes: Stream.Stream<DesktopHostTelemetrySnapshot>;
66 readonly encoded: Stream.Stream<Uint8Array>;
67 readonly handleControlForSource: (
68 sourceId: string,
69 message: DesktopTelemetryControlMessage,
70 ) => Effect.Effect<void>;
71 readonly removeControlSource: (sourceId: string) => Effect.Effect<void>;
72 readonly publishUpdateReport: (report: DesktopUpdateStatusReport) => Effect.Effect<void>;
73 readonly updateRequests: Stream.Stream<DesktopTelemetryRequestDesktopUpdate>;
74 readonly updateCommits: Stream.Stream<DesktopTelemetryCommitDesktopUpdate>;
75 readonly updateCancellations: Stream.Stream<DesktopTelemetryCancelDesktopUpdate>;
76 }
77>()("@t3tools/desktop/telemetry/DesktopTelemetryPublisher") {}
78
79function booleanState(value: boolean): HostPowerSnapshot["onBattery"] {
80 return value ? "true" : "false";
81}
82
83function idleState(value: ElectronPowerMonitor.ElectronIdleState): HostPowerSnapshot["idle"] {
84 switch (value) {
85 case "active":
86 return "false";
87 case "idle":
88 case "locked":
89 return "true";
90 case "unknown":
91 return "unknown";
92 }
93}
94
95function updatePowerState(state: PowerState, event: PowerEvent): PowerState {
96 switch (event.type) {
97 case "locked":
98 return {
99 ...state,
100 locked: booleanState(event.value),
101 lockedEventPending: true,
102 };
103 case "suspended":
104 return {
105 ...state,
106 suspended: event.value,
107 suspendedEventPending: event.value,
108 };
109 case "onBattery":
110 return {
111 ...state,
112 onBattery: booleanState(event.value),
113 onBatteryEventPending: true,
114 };
115 case "thermal":
116 return { ...state, thermalState: event.value };
117 case "speedLimit":
118 return { ...state, speedLimitPercent: Option.some(event.value) };
119 }
120}
121
122function sampleInterval(
123 power: PowerState,
124 diagnosticsDemand: boolean,
125 hostPowerIntervals: HostPowerIntervals,
126): Duration.Duration {
127 if (!diagnosticsDemand) {
128 return power.suspended || power.locked === "true" || power.idle === "true"
129 ? hostPowerIntervals.idle
130 : hostPowerIntervals.active;
131 }
132 if (
133 power.suspended ||
134 power.locked === "true" ||
135 power.thermalState === "serious" ||
136 power.thermalState === "critical"
137 ) {
138 return CONSTRAINED_SAMPLE_INTERVAL;
139 }
140 if (power.onBattery === "true") return BATTERY_SAMPLE_INTERVAL;
141 return LIVE_SAMPLE_INTERVAL;
142}
143
144/** @public Service construction is part of the canonical Effect module API. */
145export const make = Effect.fn("desktop.telemetryPublisher.make")(function* () {
146 const electronApp = yield* ElectronApp.ElectronApp;
147 const powerMonitor = yield* ElectronPowerMonitor.ElectronPowerMonitor;
148 const rendererHistory = yield* DesktopRendererHistory.DesktopRendererHistory;
149 yield* electronApp.whenReady;
150
151 const initialPowerState: PowerState = {
152 idle: "unknown",
153 locked: "unknown",
154 lockedEventPending: false,
155 suspended: false,
156 suspendedEventPending: false,
157 onBattery: booleanState(yield* powerMonitor.isOnBatteryPower),
158 onBatteryEventPending: false,
159 thermalState: yield* powerMonitor.getCurrentThermalState,
160 speedLimitPercent: Option.none(),
161 };
162 const powerState = yield* Ref.make(initialPowerState);
163 const hostPowerIntervals = yield* Ref.make<HostPowerIntervals>({
164 active: DEFAULT_HOST_POWER_ACTIVE_INTERVAL,
165 idle: DEFAULT_HOST_POWER_IDLE_INTERVAL,
166 });
167 const powerEvents = yield* Queue.unbounded<PowerEvent>();
168 const sampleTriggers = yield* Queue.sliding<void>(1);
169 const diagnosticsDemandSources = yield* Ref.make<ReadonlySet<string>>(new Set());
170 const latest = yield* Ref.make(Option.none<DesktopHostTelemetrySnapshot>());
171 const changes = yield* PubSub.sliding<DesktopHostTelemetrySnapshot>(8);
172 const sequence = yield* Ref.make(0);
173 const latestUpdateReport = yield* Ref.make(Option.none<DesktopUpdateStatusReport>());
174 const updateReportChanges = yield* PubSub.sliding<DesktopUpdateStatusReport>(16);
175 const updateRequestQueue = yield* Queue.unbounded<DesktopTelemetryRequestDesktopUpdate>();
176 const updateCommitQueue = yield* Queue.unbounded<DesktopTelemetryCommitDesktopUpdate>();
177 const updateCancellationQueue = yield* Queue.unbounded<DesktopTelemetryCancelDesktopUpdate>();
178
179 const offer = (event: PowerEvent): void => {
180 Queue.offerUnsafe(powerEvents, event);
181 };
182 yield* Effect.all(
183 [
184 powerMonitor.onSimpleEvent("lock-screen", () => offer({ type: "locked", value: true })),
185 powerMonitor.onSimpleEvent("unlock-screen", () => offer({ type: "locked", value: false })),
186 powerMonitor.onSimpleEvent("suspend", () => offer({ type: "suspended", value: true })),
187 powerMonitor.onSimpleEvent("resume", () => offer({ type: "suspended", value: false })),
188 powerMonitor.onSimpleEvent("on-battery", () => offer({ type: "onBattery", value: true })),
189 powerMonitor.onSimpleEvent("on-ac", () => offer({ type: "onBattery", value: false })),
190 powerMonitor.onThermalStateChange((value) => offer({ type: "thermal", value })),
191 powerMonitor.onSpeedLimitChange((value) => offer({ type: "speedLimit", value })),
192 ],
193 { concurrency: "unbounded" },
194 );
195 yield* Effect.forever(
196 Queue.take(powerEvents).pipe(
197 Effect.flatMap((event) => Ref.update(powerState, (state) => updatePowerState(state, event))),
198 Effect.andThen(Queue.offer(sampleTriggers, undefined)),
199 ),
200 ).pipe(Effect.forkScoped);
201
202 const sampleOnce =
203 /* Periodic telemetry sampling should not generate its own tracing traffic. */
204 Effect.fnUntraced(
205 function* (allowSuspendRecovery: boolean) {
206 const sampledAt = yield* DateTime.now;
207 const sampledAtUnixMs = DateTime.toEpochMillis(sampledAt);
208 const demand = (yield* Ref.get(diagnosticsDemandSources)).size > 0;
209 const [currentPower, idleSeconds, systemIdleState, onBattery, metrics] = yield* Effect.all(
210 [
211 Ref.get(powerState),
212 powerMonitor.getSystemIdleTime,
213 powerMonitor.getSystemIdleState(IDLE_THRESHOLD_SECONDS),
214 powerMonitor.isOnBatteryPower,
215 electronApp.getAppMetrics,
216 ],
217 { concurrency: "unbounded" },
218 );
219 // One Electron sampler preserves the shared CPU measurement interval.
220 yield* rendererHistory.recordMetrics(metrics);
221 const polledLocked =
222 systemIdleState === "unknown"
223 ? currentPower.locked
224 : booleanState(systemIdleState === "locked");
225 const polledOnBattery = booleanState(onBattery);
226 const observedPower = yield* Ref.modify(powerState, (latestPower) => {
227 const preserveEventLocked =
228 latestPower.lockedEventPending ||
229 latestPower.locked !== currentPower.locked ||
230 latestPower.lockedEventPending !== currentPower.lockedEventPending;
231 const preserveEventOnBattery =
232 latestPower.onBatteryEventPending ||
233 latestPower.onBattery !== currentPower.onBattery ||
234 latestPower.onBatteryEventPending !== currentPower.onBatteryEventPending;
235 const preserveEventSuspended =
236 latestPower.suspendedEventPending ||
237 latestPower.suspended !== currentPower.suspended ||
238 latestPower.suspendedEventPending !== currentPower.suspendedEventPending;
239 const next: PowerState = {
240 ...latestPower,
241 idle: idleState(systemIdleState),
242 locked: preserveEventLocked ? latestPower.locked : polledLocked,
243 lockedEventPending:
244 latestPower.lockedEventPending &&
245 (systemIdleState === "unknown" || polledLocked !== latestPower.locked),
246 suspended:
247 allowSuspendRecovery && !preserveEventSuspended ? false : latestPower.suspended,
248 suspendedEventPending: false,
249 onBattery: preserveEventOnBattery ? latestPower.onBattery : polledOnBattery,
250 onBatteryEventPending:
251 latestPower.onBatteryEventPending && polledOnBattery !== latestPower.onBattery,
252 };
253 return [next, next] as const;
254 });
255 const nextSequence = yield* Ref.modify(sequence, (current) => [current + 1, current + 1]);
256 const snapshot: DesktopHostTelemetrySnapshot = {
257 version: 1,
258 type: "desktopTelemetry",
259 sequence: nextSequence,
260 sampledAtUnixMs,
261 electronPid: process.pid,
262 power: {
263 source: "electron-main",
264 idle: observedPower.idle,
265 idleSeconds,
266 locked: observedPower.locked,
267 suspended: observedPower.suspended,
268 onBattery: observedPower.onBattery,
269 lowPowerMode: "unknown",
270 thermalState: observedPower.thermalState,
271 stale: false,
272 updatedAt: sampledAt,
273 },
274 speedLimitPercent: observedPower.speedLimitPercent,
275 electronProcesses: (demand ? metrics : []).map((metric) => ({
276 pid: metric.pid,
277 creationTimeMs: Math.max(0, Math.round(metric.creationTime)),
278 type: metric.type,
279 ...(metric.name === undefined ? {} : { name: metric.name }),
280 ...(metric.serviceName === undefined ? {} : { serviceName: metric.serviceName }),
281 cpuPercent: metric.cpu.percentCPUUsage,
282 ...(metric.cpu.cumulativeCPUUsage === undefined
283 ? {}
284 : { cumulativeCpuSeconds: metric.cpu.cumulativeCPUUsage }),
285 idleWakeupsPerSecond: metric.cpu.idleWakeupsPerSecond,
286 workingSetBytes: Math.max(0, Math.round(metric.memory.workingSetSize * 1024)),
287 peakWorkingSetBytes: Math.max(0, Math.round(metric.memory.peakWorkingSetSize * 1024)),
288 })),
289 };
290
291 yield* Ref.set(latest, Option.some(snapshot));
292 yield* PubSub.publish(changes, snapshot);
293 },
294 Effect.catchCauseIf(
295 (cause) => !Cause.hasInterrupts(cause),
296 (cause) =>
297 Effect.logWarning("Failed to sample Electron telemetry", {
298 cause: String(cause),
299 }),
300 ),
301 );
302
303 yield* Effect.gen(function* () {
304 yield* sampleOnce(false);
305 while (true) {
306 const [currentPower, demand, intervals] = yield* Effect.all([
307 Ref.get(powerState),
308 Ref.get(diagnosticsDemandSources).pipe(Effect.map((sources) => sources.size > 0)),
309 Ref.get(hostPowerIntervals),
310 ]);
311 // @effect-diagnostics-next-line raceFirstWithSleepToTimeout:off - races a trigger queue against the interval; both arms are real outcomes, not a timeout
312 const allowSuspendRecovery = yield* Effect.raceFirst(
313 Queue.take(sampleTriggers).pipe(Effect.as(false)),
314 Effect.sleep(sampleInterval(currentPower, demand, intervals)).pipe(Effect.as(true)),
315 );
316 yield* sampleOnce(allowSuspendRecovery);
317 }
318 }).pipe(Effect.forkScoped);
319
320 const handleControlForSource: DesktopTelemetryPublisher["Service"]["handleControlForSource"] = (
321 sourceId,
322 message,
323 ) => {
324 switch (message.type) {
325 case "setDiagnosticsDemand":
326 return Ref.modify(diagnosticsDemandSources, (sources) => {
327 const previous = sources.size > 0;
328 const next = new Set(sources);
329 if (message.enabled) {
330 next.add(sourceId);
331 } else {
332 next.delete(sourceId);
333 }
334 return [[previous, next.size > 0] as const, next] as const;
335 }).pipe(
336 Effect.flatMap(([previous, enabled]) =>
337 previous === enabled
338 ? Effect.void
339 : Queue.offer(sampleTriggers, undefined).pipe(Effect.asVoid),
340 ),
341 );
342 case "setHostPowerIntervals":
343 return Ref.set(hostPowerIntervals, {
344 active: Duration.millis(message.activeIntervalMs),
345 idle: Duration.millis(message.idleIntervalMs),
346 }).pipe(Effect.andThen(Queue.offer(sampleTriggers, undefined)), Effect.asVoid);
347 case "requestDesktopUpdate":
348 return Queue.offer(updateRequestQueue, message).pipe(Effect.asVoid);
349 case "commitDesktopUpdate":
350 return Queue.offer(updateCommitQueue, message).pipe(Effect.asVoid);
351 case "cancelDesktopUpdate":
352 return Queue.offer(updateCancellationQueue, message).pipe(Effect.asVoid);
353 }
354 };
355 const removeControlSource: DesktopTelemetryPublisher["Service"]["removeControlSource"] = (
356 sourceId,
357 ) =>
358 Ref.modify(diagnosticsDemandSources, (sources) => {
359 const previous = sources.size > 0;
360 const next = new Set(sources);
361 next.delete(sourceId);
362 return [[previous, next.size > 0] as const, next] as const;
363 }).pipe(
364 Effect.flatMap(([previous, enabled]) =>
365 previous === enabled
366 ? Effect.void
367 : Queue.offer(sampleTriggers, undefined).pipe(Effect.asVoid),
368 ),
369 );
370
371 const snapshots = Stream.unwrap(
372 Effect.gen(function* () {
373 const subscription = yield* PubSub.subscribe(changes);
374 const initial = yield* Ref.get(latest);
375 return Stream.concat(
376 Option.match(initial, {
377 onNone: () => Stream.empty,
378 onSome: Stream.make,
379 }),
380 Stream.fromSubscription(subscription),
381 );
382 }),
383 );
384 const updateReports = Stream.unwrap(
385 Effect.gen(function* () {
386 const subscription = yield* PubSub.subscribe(updateReportChanges);
387 const initial = yield* Ref.get(latestUpdateReport);
388 return Stream.concat(
389 Option.match(initial, {
390 onNone: () => Stream.empty,
391 onSome: Stream.make,
392 }),
393 Stream.fromSubscription(subscription),
394 );
395 }),
396 );
397 const encoded = Stream.concat(
398 Stream.make({
399 version: 1,
400 type: "desktopTelemetryHello",
401 electronPid: process.pid,
402 } as const),
403 Stream.merge(snapshots, updateReports),
404 ).pipe(Stream.map((message) => textEncoder.encode(`${encodeMessage(message)}\n`)));
405
406 const publishUpdateReport: DesktopTelemetryPublisher["Service"]["publishUpdateReport"] = (
407 report,
408 ) =>
409 Ref.set(latestUpdateReport, Option.some(report)).pipe(
410 Effect.andThen(PubSub.publish(updateReportChanges, report)),
411 Effect.asVoid,
412 );
413
414 return DesktopTelemetryPublisher.of({
415 latest: Ref.get(latest),
416 changes: Stream.fromPubSub(changes),
417 encoded,
418 handleControlForSource,
419 removeControlSource,
420 publishUpdateReport,
421 updateRequests: Stream.fromQueue(updateRequestQueue),
422 updateCommits: Stream.fromQueue(updateCommitQueue),
423 updateCancellations: Stream.fromQueue(updateCancellationQueue),
424 });
425});
426
427export const layer = Layer.effect(DesktopTelemetryPublisher, make());