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 = (allowSuspendRecovery: boolean) =>
203 Effect.gen(function* () {
204 const sampledAt = yield* DateTime.now;
205 const sampledAtUnixMs = DateTime.toEpochMillis(sampledAt);
206 const demand = (yield* Ref.get(diagnosticsDemandSources)).size > 0;
207 const [currentPower, idleSeconds, systemIdleState, onBattery, metrics] = yield* Effect.all(
208 [
209 Ref.get(powerState),
210 powerMonitor.getSystemIdleTime,
211 powerMonitor.getSystemIdleState(IDLE_THRESHOLD_SECONDS),
212 powerMonitor.isOnBatteryPower,
213 electronApp.getAppMetrics,
214 ],
215 { concurrency: "unbounded" },
216 );
217 // One Electron sampler preserves the shared CPU measurement interval.
218 yield* rendererHistory.recordMetrics(metrics);
219 const polledLocked =
220 systemIdleState === "unknown"
221 ? currentPower.locked
222 : booleanState(systemIdleState === "locked");
223 const polledOnBattery = booleanState(onBattery);
224 const observedPower = yield* Ref.modify(powerState, (latestPower) => {
225 const preserveEventLocked =
226 latestPower.lockedEventPending ||
227 latestPower.locked !== currentPower.locked ||
228 latestPower.lockedEventPending !== currentPower.lockedEventPending;
229 const preserveEventOnBattery =
230 latestPower.onBatteryEventPending ||
231 latestPower.onBattery !== currentPower.onBattery ||
232 latestPower.onBatteryEventPending !== currentPower.onBatteryEventPending;
233 const preserveEventSuspended =
234 latestPower.suspendedEventPending ||
235 latestPower.suspended !== currentPower.suspended ||
236 latestPower.suspendedEventPending !== currentPower.suspendedEventPending;
237 const next: PowerState = {
238 ...latestPower,
239 idle: idleState(systemIdleState),
240 locked: preserveEventLocked ? latestPower.locked : polledLocked,
241 lockedEventPending:
242 latestPower.lockedEventPending &&
243 (systemIdleState === "unknown" || polledLocked !== latestPower.locked),
244 suspended:
245 allowSuspendRecovery && !preserveEventSuspended ? false : latestPower.suspended,
246 suspendedEventPending: false,
247 onBattery: preserveEventOnBattery ? latestPower.onBattery : polledOnBattery,
248 onBatteryEventPending:
249 latestPower.onBatteryEventPending && polledOnBattery !== latestPower.onBattery,
250 };
251 return [next, next] as const;
252 });
253 const nextSequence = yield* Ref.modify(sequence, (current) => [current + 1, current + 1]);
254 const snapshot: DesktopHostTelemetrySnapshot = {
255 version: 1,
256 type: "desktopTelemetry",
257 sequence: nextSequence,
258 sampledAtUnixMs,
259 electronPid: process.pid,
260 power: {
261 source: "electron-main",
262 idle: observedPower.idle,
263 idleSeconds,
264 locked: observedPower.locked,
265 suspended: observedPower.suspended,
266 onBattery: observedPower.onBattery,
267 lowPowerMode: "unknown",
268 thermalState: observedPower.thermalState,
269 stale: false,
270 updatedAt: sampledAt,
271 },
272 speedLimitPercent: observedPower.speedLimitPercent,
273 electronProcesses: (demand ? metrics : []).map((metric) => ({
274 pid: metric.pid,
275 creationTimeMs: Math.max(0, Math.round(metric.creationTime)),
276 type: metric.type,
277 ...(metric.name === undefined ? {} : { name: metric.name }),
278 ...(metric.serviceName === undefined ? {} : { serviceName: metric.serviceName }),
279 cpuPercent: metric.cpu.percentCPUUsage,
280 ...(metric.cpu.cumulativeCPUUsage === undefined
281 ? {}
282 : { cumulativeCpuSeconds: metric.cpu.cumulativeCPUUsage }),
283 idleWakeupsPerSecond: metric.cpu.idleWakeupsPerSecond,
284 workingSetBytes: Math.max(0, Math.round(metric.memory.workingSetSize * 1024)),
285 peakWorkingSetBytes: Math.max(0, Math.round(metric.memory.peakWorkingSetSize * 1024)),
286 })),
287 };
288
289 yield* Ref.set(latest, Option.some(snapshot));
290 yield* PubSub.publish(changes, snapshot);
291 }).pipe(
292 Effect.catchCauseIf(
293 (cause) => !Cause.hasInterrupts(cause),
294 (cause) =>
295 Effect.logWarning("Failed to sample Electron telemetry", {
296 cause: String(cause),
297 }),
298 ),
299 );
300
301 yield* Effect.gen(function* () {
302 yield* sampleOnce(false);
303 while (true) {
304 const [currentPower, demand, intervals] = yield* Effect.all([
305 Ref.get(powerState),
306 Ref.get(diagnosticsDemandSources).pipe(Effect.map((sources) => sources.size > 0)),
307 Ref.get(hostPowerIntervals),
308 ]);
309 // @effect-diagnostics-next-line raceFirstWithSleepToTimeout:off - races a trigger queue against the interval; both arms are real outcomes, not a timeout
310 const allowSuspendRecovery = yield* Effect.raceFirst(
311 Queue.take(sampleTriggers).pipe(Effect.as(false)),
312 Effect.sleep(sampleInterval(currentPower, demand, intervals)).pipe(Effect.as(true)),
313 );
314 yield* sampleOnce(allowSuspendRecovery);
315 }
316 }).pipe(Effect.forkScoped);
317
318 const handleControlForSource: DesktopTelemetryPublisher["Service"]["handleControlForSource"] = (
319 sourceId,
320 message,
321 ) => {
322 switch (message.type) {
323 case "setDiagnosticsDemand":
324 return Ref.modify(diagnosticsDemandSources, (sources) => {
325 const previous = sources.size > 0;
326 const next = new Set(sources);
327 if (message.enabled) {
328 next.add(sourceId);
329 } else {
330 next.delete(sourceId);
331 }
332 return [[previous, next.size > 0] as const, next] as const;
333 }).pipe(
334 Effect.flatMap(([previous, enabled]) =>
335 previous === enabled
336 ? Effect.void
337 : Queue.offer(sampleTriggers, undefined).pipe(Effect.asVoid),
338 ),
339 );
340 case "setHostPowerIntervals":
341 return Ref.set(hostPowerIntervals, {
342 active: Duration.millis(message.activeIntervalMs),
343 idle: Duration.millis(message.idleIntervalMs),
344 }).pipe(Effect.andThen(Queue.offer(sampleTriggers, undefined)), Effect.asVoid);
345 case "requestDesktopUpdate":
346 return Queue.offer(updateRequestQueue, message).pipe(Effect.asVoid);
347 case "commitDesktopUpdate":
348 return Queue.offer(updateCommitQueue, message).pipe(Effect.asVoid);
349 case "cancelDesktopUpdate":
350 return Queue.offer(updateCancellationQueue, message).pipe(Effect.asVoid);
351 }
352 };
353 const removeControlSource: DesktopTelemetryPublisher["Service"]["removeControlSource"] = (
354 sourceId,
355 ) =>
356 Ref.modify(diagnosticsDemandSources, (sources) => {
357 const previous = sources.size > 0;
358 const next = new Set(sources);
359 next.delete(sourceId);
360 return [[previous, next.size > 0] as const, next] as const;
361 }).pipe(
362 Effect.flatMap(([previous, enabled]) =>
363 previous === enabled
364 ? Effect.void
365 : Queue.offer(sampleTriggers, undefined).pipe(Effect.asVoid),
366 ),
367 );
368
369 const snapshots = Stream.unwrap(
370 Effect.gen(function* () {
371 const subscription = yield* PubSub.subscribe(changes);
372 const initial = yield* Ref.get(latest);
373 return Stream.concat(
374 Option.match(initial, {
375 onNone: () => Stream.empty,
376 onSome: Stream.make,
377 }),
378 Stream.fromSubscription(subscription),
379 );
380 }),
381 );
382 const updateReports = Stream.unwrap(
383 Effect.gen(function* () {
384 const subscription = yield* PubSub.subscribe(updateReportChanges);
385 const initial = yield* Ref.get(latestUpdateReport);
386 return Stream.concat(
387 Option.match(initial, {
388 onNone: () => Stream.empty,
389 onSome: Stream.make,
390 }),
391 Stream.fromSubscription(subscription),
392 );
393 }),
394 );
395 const encoded = Stream.concat(
396 Stream.make({
397 version: 1,
398 type: "desktopTelemetryHello",
399 electronPid: process.pid,
400 } as const),
401 Stream.merge(snapshots, updateReports),
402 ).pipe(Stream.map((message) => textEncoder.encode(`${encodeMessage(message)}\n`)));
403
404 const publishUpdateReport: DesktopTelemetryPublisher["Service"]["publishUpdateReport"] = (
405 report,
406 ) =>
407 Ref.set(latestUpdateReport, Option.some(report)).pipe(
408 Effect.andThen(PubSub.publish(updateReportChanges, report)),
409 Effect.asVoid,
410 );
411
412 return DesktopTelemetryPublisher.of({
413 latest: Ref.get(latest),
414 changes: Stream.fromPubSub(changes),
415 encoded,
416 handleControlForSource,
417 removeControlSource,
418 publishUpdateReport,
419 updateRequests: Stream.fromQueue(updateRequestQueue),
420 updateCommits: Stream.fromQueue(updateCommitQueue),
421 updateCancellations: Stream.fromQueue(updateCancellationQueue),
422 });
423});
424
425export const layer = Layer.effect(DesktopTelemetryPublisher, make());