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

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