The best way to control Claude Code, Codex and more from any computer or phone
| 1 | // @effect-diagnostics nodeBuiltinImport:off |
| 2 | import * as NodeFS from "node:fs"; |
| 3 | import * as NodeNet from "node:net"; |
| 4 | import * as NodeTls from "node:tls"; |
| 5 | |
| 6 | import * as NodeStream from "@effect/platform-node/NodeStream"; |
| 7 | import { |
| 8 | DesktopHostTelemetryMessage, |
| 9 | type DesktopHostTelemetryMessage as DesktopHostTelemetryMessageValue, |
| 10 | type DesktopHostTelemetrySnapshot, |
| 11 | type DesktopShellEnvironmentSnapshot, |
| 12 | DesktopTelemetryControlMessage, |
| 13 | type DesktopUpdateChannel, |
| 14 | type DesktopUpdateStatusReport, |
| 15 | type ResourceTelemetrySourceStatus, |
| 16 | } from "@t3tools/contracts"; |
| 17 | import { resolveServerBackgroundActivitySettings } from "@t3tools/shared/backgroundActivitySettings"; |
| 18 | import * as HostProcess from "@t3tools/shared/HostProcess"; |
| 19 | import { applyShellEnvironment } from "@t3tools/shared/shell"; |
| 20 | import * as Cause from "effect/Cause"; |
| 21 | import * as Context from "effect/Context"; |
| 22 | import * as DateTime from "effect/DateTime"; |
| 23 | import * as Duration from "effect/Duration"; |
| 24 | import * as Effect from "effect/Effect"; |
| 25 | import * as FileSystem from "effect/FileSystem"; |
| 26 | import * as Layer from "effect/Layer"; |
| 27 | import * as Option from "effect/Option"; |
| 28 | import * as PubSub from "effect/PubSub"; |
| 29 | import * as Ref from "effect/Ref"; |
| 30 | import * as Schema from "effect/Schema"; |
| 31 | import * as Semaphore from "effect/Semaphore"; |
| 32 | import * as Scope from "effect/Scope"; |
| 33 | import * as Stream from "effect/Stream"; |
| 34 | import * as Ndjson from "effect/encoding/Ndjson"; |
| 35 | |
| 36 | import { eventVersion as messageVersion } from "./NativeTelemetryClient.ts"; |
| 37 | import * as ServerConfig from "../config.ts"; |
| 38 | import * as ServerSettings from "../serverSettings.ts"; |
| 39 | import { subscribeBeforeSnapshotWithoutMutex } from "../utils/subscribeBeforeSnapshot.ts"; |
| 40 | |
| 41 | const INITIAL_SAMPLE_DEADLINE_MS = 90_000; |
| 42 | const MIN_SNAPSHOT_STALE_AFTER_MS = 90_000; |
| 43 | const STALE_GRACE_MS = 30_000; |
| 44 | const DEFAULT_HOST_POWER_ACTIVE_INTERVAL_MS = 30_000; |
| 45 | const DEFAULT_HOST_POWER_IDLE_INTERVAL_MS = 120_000; |
| 46 | const STALE_CHECK_INTERVAL = Duration.seconds(30); |
| 47 | |
| 48 | export class DesktopTelemetryDescriptorUnavailable extends Schema.TaggedError<DesktopTelemetryDescriptorUnavailable>()( |
| 49 | "DesktopTelemetryDescriptorUnavailable", |
| 50 | { |
| 51 | mode: Schema.String, |
| 52 | }, |
| 53 | ) { |
| 54 | override get message(): string { |
| 55 | return `Desktop telemetry descriptor is unavailable in '${this.mode}' mode.`; |
| 56 | } |
| 57 | } |
| 58 | |
| 59 | export class DesktopTelemetryProtocolMismatch extends Schema.TaggedError<DesktopTelemetryProtocolMismatch>()( |
| 60 | "DesktopTelemetryProtocolMismatch", |
| 61 | { |
| 62 | expectedVersion: Schema.Number, |
| 63 | receivedVersion: Schema.Number, |
| 64 | }, |
| 65 | ) { |
| 66 | override get message(): string { |
| 67 | return `Desktop telemetry protocol ${this.receivedVersion} is incompatible with expected protocol ${this.expectedVersion}.`; |
| 68 | } |
| 69 | } |
| 70 | |
| 71 | export class DesktopTelemetryDecodeFailed extends Schema.TaggedError<DesktopTelemetryDecodeFailed>()( |
| 72 | "DesktopTelemetryDecodeFailed", |
| 73 | { |
| 74 | cause: Schema.Defect(), |
| 75 | }, |
| 76 | ) { |
| 77 | override get message(): string { |
| 78 | return "Failed to decode desktop telemetry."; |
| 79 | } |
| 80 | } |
| 81 | |
| 82 | export class DesktopTelemetryStreamFailed extends Schema.TaggedError<DesktopTelemetryStreamFailed>()( |
| 83 | "DesktopTelemetryStreamFailed", |
| 84 | { |
| 85 | fd: Schema.Number, |
| 86 | cause: Schema.Defect(), |
| 87 | }, |
| 88 | ) { |
| 89 | override get message(): string { |
| 90 | return `Desktop telemetry stream on fd ${this.fd} failed.`; |
| 91 | } |
| 92 | } |
| 93 | |
| 94 | export class DesktopTelemetryStreamClosed extends Schema.TaggedError<DesktopTelemetryStreamClosed>()( |
| 95 | "DesktopTelemetryStreamClosed", |
| 96 | { |
| 97 | fd: Schema.Number, |
| 98 | }, |
| 99 | ) { |
| 100 | override get message(): string { |
| 101 | return `Desktop telemetry stream on fd ${this.fd} closed.`; |
| 102 | } |
| 103 | } |
| 104 | |
| 105 | export class DesktopTelemetryStale extends Schema.TaggedError<DesktopTelemetryStale>()( |
| 106 | "DesktopTelemetryStale", |
| 107 | { |
| 108 | fd: Schema.Number, |
| 109 | staleAfterMs: Schema.Number, |
| 110 | }, |
| 111 | ) { |
| 112 | override get message(): string { |
| 113 | return `Desktop telemetry on fd ${this.fd} has not updated for ${this.staleAfterMs}ms.`; |
| 114 | } |
| 115 | } |
| 116 | |
| 117 | export type DesktopTelemetryReceiverError = |
| 118 | | DesktopTelemetryDescriptorUnavailable |
| 119 | | DesktopTelemetryProtocolMismatch |
| 120 | | DesktopTelemetryDecodeFailed |
| 121 | | DesktopTelemetryStreamFailed |
| 122 | | DesktopTelemetryStreamClosed; |
| 123 | |
| 124 | export class DesktopTelemetryControlFailed extends Schema.TaggedError<DesktopTelemetryControlFailed>()( |
| 125 | "DesktopTelemetryControlFailed", |
| 126 | { |
| 127 | fd: Schema.Number, |
| 128 | operation: Schema.String, |
| 129 | cause: Schema.Defect(), |
| 130 | }, |
| 131 | ) { |
| 132 | override get message(): string { |
| 133 | return `Desktop telemetry control '${this.operation}' failed on fd ${this.fd}.`; |
| 134 | } |
| 135 | } |
| 136 | |
| 137 | export class DesktopTelemetryControlStalled extends Schema.TaggedError<DesktopTelemetryControlStalled>()( |
| 138 | "DesktopTelemetryControlStalled", |
| 139 | { |
| 140 | fd: Schema.Number, |
| 141 | remainingBytes: Schema.Number, |
| 142 | }, |
| 143 | ) { |
| 144 | override get message(): string { |
| 145 | return `Desktop telemetry control stalled on fd ${this.fd} with ${this.remainingBytes} bytes remaining.`; |
| 146 | } |
| 147 | } |
| 148 | |
| 149 | export type DesktopTelemetryControlError = |
| 150 | | DesktopTelemetryControlFailed |
| 151 | | DesktopTelemetryControlStalled; |
| 152 | |
| 153 | export interface DesktopTelemetryReceiverHealth { |
| 154 | readonly status: ResourceTelemetrySourceStatus; |
| 155 | readonly lastSampleAt: Option.Option<DateTime.Utc>; |
| 156 | readonly lastError: Option.Option<string>; |
| 157 | } |
| 158 | |
| 159 | /** Moves the desktop app to `channel` and installs only `targetVersion`. */ |
| 160 | export interface DesktopTrackSwitch { |
| 161 | readonly channel: DesktopUpdateChannel; |
| 162 | readonly targetVersion: string; |
| 163 | } |
| 164 | |
| 165 | export class DesktopTelemetryReceiver extends Context.Service< |
| 166 | DesktopTelemetryReceiver, |
| 167 | { |
| 168 | readonly latest: Effect.Effect<Option.Option<DesktopHostTelemetrySnapshot>>; |
| 169 | readonly changes: Stream.Stream<DesktopHostTelemetrySnapshot>; |
| 170 | readonly subscribe: Effect.Effect< |
| 171 | { |
| 172 | readonly latest: Option.Option<DesktopHostTelemetrySnapshot>; |
| 173 | readonly changes: Stream.Stream<DesktopHostTelemetrySnapshot>; |
| 174 | }, |
| 175 | never, |
| 176 | Scope.Scope |
| 177 | >; |
| 178 | readonly health: Effect.Effect<DesktopTelemetryReceiverHealth>; |
| 179 | readonly subscribeHealth: Effect.Effect< |
| 180 | { |
| 181 | readonly latest: DesktopTelemetryReceiverHealth; |
| 182 | readonly changes: Stream.Stream<DesktopTelemetryReceiverHealth>; |
| 183 | }, |
| 184 | never, |
| 185 | Scope.Scope |
| 186 | >; |
| 187 | readonly setDiagnosticsDemand: ( |
| 188 | enabled: boolean, |
| 189 | ) => Effect.Effect<void, DesktopTelemetryControlError>; |
| 190 | /** Tells the desktop parent that the server accepts requests, so it can skip readiness polling. */ |
| 191 | readonly announceServerReady: Effect.Effect<void, DesktopTelemetryControlError>; |
| 192 | readonly requestDesktopUpdate: ( |
| 193 | requestId: string, |
| 194 | trackSwitch?: DesktopTrackSwitch, |
| 195 | ) => Effect.Effect<void, DesktopTelemetryControlError>; |
| 196 | readonly commitDesktopUpdate: ( |
| 197 | requestId: string, |
| 198 | ) => Effect.Effect<void, DesktopTelemetryControlError>; |
| 199 | readonly cancelDesktopUpdate: ( |
| 200 | requestId: string, |
| 201 | ) => Effect.Effect<void, DesktopTelemetryControlError>; |
| 202 | readonly desktopUpdates: Effect.Effect< |
| 203 | { |
| 204 | readonly latest: Option.Option<DesktopUpdateStatusReport>; |
| 205 | readonly changes: Stream.Stream<DesktopUpdateStatusReport>; |
| 206 | }, |
| 207 | never, |
| 208 | Scope.Scope |
| 209 | >; |
| 210 | } |
| 211 | >()("t3/resourceTelemetry/DesktopTelemetryReceiver") {} |
| 212 | |
| 213 | class DesktopShellCertificatesUpdateFailed extends Schema.TaggedError<DesktopShellCertificatesUpdateFailed>()( |
| 214 | "DesktopShellCertificatesUpdateFailed", |
| 215 | { cause: Schema.Defect() }, |
| 216 | ) { |
| 217 | override get message(): string { |
| 218 | return "Failed to update desktop shell TLS certificates."; |
| 219 | } |
| 220 | } |
| 221 | |
| 222 | export function makeApplyDesktopShellEnvironmentSnapshot( |
| 223 | environment: NodeJS.ProcessEnv, |
| 224 | platform: NodeJS.Platform, |
| 225 | ) { |
| 226 | let baseCertificates: Array<string> | undefined; |
| 227 | return Effect.fn("resourceTelemetry.desktopTelemetryReceiver.applyShellEnvironment")(function* ( |
| 228 | message: DesktopShellEnvironmentSnapshot, |
| 229 | ) { |
| 230 | if (message.platform !== platform) return; |
| 231 | // Node's first default-CA enumeration consults process.env, so capture it before the patch. |
| 232 | if (message.environment.NODE_EXTRA_CA_CERTS !== undefined && baseCertificates === undefined) { |
| 233 | // Remove only the startup extras, preserving duplicates from bundled or system trust. |
| 234 | const extras = [...NodeTls.getCACertificates("extra")]; |
| 235 | baseCertificates = NodeTls.getCACertificates("default").filter((certificate) => { |
| 236 | const index = extras.indexOf(certificate); |
| 237 | if (index === -1) return true; |
| 238 | extras.splice(index, 1); |
| 239 | return false; |
| 240 | }); |
| 241 | } |
| 242 | applyShellEnvironment(environment, message.environment, platform); |
| 243 | if (message.environment.NODE_EXTRA_CA_CERTS !== undefined) { |
| 244 | yield* Effect.gen(function* () { |
| 245 | const certificates = baseCertificates; |
| 246 | // --use-openssl-ca roots are not enumerable; replacing the list would discard them. |
| 247 | if (certificates === undefined || certificates.length === 0) { |
| 248 | yield* Effect.logWarning( |
| 249 | "Preserving non-enumerable TLS trust. Restart to apply updated desktop shell certificates.", |
| 250 | ); |
| 251 | return; |
| 252 | } |
| 253 | const fs = yield* FileSystem.FileSystem; |
| 254 | const file = message.environment.NODE_EXTRA_CA_CERTS; |
| 255 | const bundle = file ? yield* fs.readFileString(file) : undefined; |
| 256 | yield* Effect.try({ |
| 257 | try: () => { |
| 258 | const extras = |
| 259 | bundle?.match(/-----BEGIN CERTIFICATE-----[\s\S]*?-----END CERTIFICATE-----/g) ?? []; |
| 260 | if (bundle?.trim() && extras.length === 0) { |
| 261 | throw new Error("No PEM certificates found."); |
| 262 | } |
| 263 | NodeTls.setDefaultCACertificates([...certificates, ...extras]); |
| 264 | }, |
| 265 | catch: (cause) => new DesktopShellCertificatesUpdateFailed({ cause }), |
| 266 | }); |
| 267 | }).pipe( |
| 268 | Effect.catch((cause) => |
| 269 | Effect.logWarning("Failed to update desktop shell TLS certificates.", Cause.fail(cause)), |
| 270 | ), |
| 271 | ); |
| 272 | } |
| 273 | if (message.discovered) delete environment.T3CODE_DESKTOP_SHELL_DISCOVERY_PENDING; |
| 274 | }); |
| 275 | } |
| 276 | |
| 277 | const decodeMessage = Schema.decodeUnknownEffect(DesktopHostTelemetryMessage); |
| 278 | const encodeControlMessage = Schema.encodeEffect( |
| 279 | Schema.fromJsonString(DesktopTelemetryControlMessage), |
| 280 | ); |
| 281 | const isDescriptorUnavailable = Schema.is(DesktopTelemetryDescriptorUnavailable); |
| 282 | const isProtocolMismatch = Schema.is(DesktopTelemetryProtocolMismatch); |
| 283 | const isDecodeFailed = Schema.is(DesktopTelemetryDecodeFailed); |
| 284 | const isStreamFailed = Schema.is(DesktopTelemetryStreamFailed); |
| 285 | |
| 286 | function isDesktopTelemetryContactStale( |
| 287 | lastContactAtMs: Option.Option<number>, |
| 288 | nowMs: number, |
| 289 | ): boolean { |
| 290 | return Option.exists( |
| 291 | lastContactAtMs, |
| 292 | (lastContact) => nowMs - lastContact >= INITIAL_SAMPLE_DEADLINE_MS, |
| 293 | ); |
| 294 | } |
| 295 | |
| 296 | function resolveDesktopTelemetrySnapshotStaleAfterMs( |
| 297 | activeIntervalMs: number, |
| 298 | idleIntervalMs: number, |
| 299 | ): number { |
| 300 | return Math.max( |
| 301 | MIN_SNAPSHOT_STALE_AFTER_MS, |
| 302 | Math.max(activeIntervalMs, idleIntervalMs) + STALE_GRACE_MS, |
| 303 | ); |
| 304 | } |
| 305 | |
| 306 | function initialDesktopTelemetryContactAt( |
| 307 | desktopTelemetryFd: number | undefined, |
| 308 | nowMs: number, |
| 309 | ): Option.Option<number> { |
| 310 | return desktopTelemetryFd === undefined ? Option.none() : Option.some(nowMs); |
| 311 | } |
| 312 | |
| 313 | const recordDesktopTelemetrySampleHealth = Effect.fn( |
| 314 | "resourceTelemetry.desktopTelemetryReceiver.recordSampleHealth", |
| 315 | )(function* ( |
| 316 | health: Ref.Ref<DesktopTelemetryReceiverHealth>, |
| 317 | healthChanges: PubSub.PubSub<DesktopTelemetryReceiverHealth>, |
| 318 | sampledAt: DateTime.Utc, |
| 319 | ) { |
| 320 | const next: DesktopTelemetryReceiverHealth = { |
| 321 | status: "healthy", |
| 322 | lastSampleAt: Option.some(sampledAt), |
| 323 | lastError: Option.none(), |
| 324 | }; |
| 325 | yield* Ref.set(health, next); |
| 326 | yield* PubSub.publish(healthChanges, next); |
| 327 | }); |
| 328 | |
| 329 | function normalizeReceiverError(error: unknown): DesktopTelemetryReceiverError { |
| 330 | if ( |
| 331 | isDescriptorUnavailable(error) || |
| 332 | isProtocolMismatch(error) || |
| 333 | isDecodeFailed(error) || |
| 334 | isStreamFailed(error) |
| 335 | ) { |
| 336 | return error; |
| 337 | } |
| 338 | return new DesktopTelemetryDecodeFailed({ cause: error }); |
| 339 | } |
| 340 | |
| 341 | export const writeAllToFileDescriptor = Effect.fn( |
| 342 | "resourceTelemetry.desktopTelemetryReceiver.writeAllToFileDescriptor", |
| 343 | )(function* (fd: number, payload: Buffer) { |
| 344 | let offset = 0; |
| 345 | while (offset < payload.byteLength) { |
| 346 | const written = yield* Effect.callback<number, DesktopTelemetryControlFailed>( |
| 347 | (resume, signal) => { |
| 348 | if (signal.aborted) return; |
| 349 | try { |
| 350 | NodeFS.write( |
| 351 | fd, |
| 352 | payload, |
| 353 | offset, |
| 354 | payload.byteLength - offset, |
| 355 | null, |
| 356 | (error, bytesWritten) => { |
| 357 | if (error) { |
| 358 | resume( |
| 359 | Effect.fail( |
| 360 | new DesktopTelemetryControlFailed({ |
| 361 | fd, |
| 362 | operation: "write", |
| 363 | cause: error, |
| 364 | }), |
| 365 | ), |
| 366 | ); |
| 367 | return; |
| 368 | } |
| 369 | resume(Effect.succeed(bytesWritten)); |
| 370 | }, |
| 371 | ); |
| 372 | } catch (cause) { |
| 373 | resume( |
| 374 | Effect.fail( |
| 375 | new DesktopTelemetryControlFailed({ |
| 376 | fd, |
| 377 | operation: "write", |
| 378 | cause, |
| 379 | }), |
| 380 | ), |
| 381 | ); |
| 382 | } |
| 383 | }, |
| 384 | ); |
| 385 | yield* requireDesktopTelemetryWriteProgress(fd, payload.byteLength - offset, written); |
| 386 | offset += written; |
| 387 | } |
| 388 | }); |
| 389 | |
| 390 | export function requireDesktopTelemetryWriteProgress( |
| 391 | fd: number, |
| 392 | remainingBytes: number, |
| 393 | written: number, |
| 394 | ): Effect.Effect<void, DesktopTelemetryControlStalled> { |
| 395 | return written > 0 |
| 396 | ? Effect.void |
| 397 | : Effect.fail(new DesktopTelemetryControlStalled({ fd, remainingBytes })); |
| 398 | } |
| 399 | |
| 400 | /** @public */ |
| 401 | export const make = Effect.fn("resourceTelemetry.desktopTelemetryReceiver.make")(function* () { |
| 402 | const config = yield* ServerConfig.ServerConfig; |
| 403 | const environment = yield* HostProcess.Environment; |
| 404 | const platform = yield* HostProcess.Platform; |
| 405 | const applyShellSnapshot = makeApplyDesktopShellEnvironmentSnapshot(environment, platform); |
| 406 | const serverSettings = yield* ServerSettings.ServerSettingsService; |
| 407 | const latest = yield* Ref.make(Option.none<DesktopHostTelemetrySnapshot>()); |
| 408 | const receiverStartedAt = yield* DateTime.now; |
| 409 | const lastContactAtMs = yield* Ref.make( |
| 410 | initialDesktopTelemetryContactAt( |
| 411 | config.desktopTelemetryFd, |
| 412 | DateTime.toEpochMillis(receiverStartedAt), |
| 413 | ), |
| 414 | ); |
| 415 | const snapshotStaleAfterMs = yield* Ref.make( |
| 416 | resolveDesktopTelemetrySnapshotStaleAfterMs( |
| 417 | DEFAULT_HOST_POWER_ACTIVE_INTERVAL_MS, |
| 418 | DEFAULT_HOST_POWER_IDLE_INTERVAL_MS, |
| 419 | ), |
| 420 | ); |
| 421 | const changes = yield* PubSub.sliding<DesktopHostTelemetrySnapshot>(8); |
| 422 | const healthChanges = yield* PubSub.sliding<DesktopTelemetryReceiverHealth>(4); |
| 423 | const latestUpdateReport = yield* Ref.make(Option.none<DesktopUpdateStatusReport>()); |
| 424 | const updateReportChanges = yield* PubSub.sliding<DesktopUpdateStatusReport>(16); |
| 425 | const controlMutex = yield* Semaphore.make(1); |
| 426 | const snapshotMutex = yield* Semaphore.make(1); |
| 427 | const health = yield* Ref.make<DesktopTelemetryReceiverHealth>({ |
| 428 | status: config.desktopTelemetryFd === undefined ? "unavailable" : "starting", |
| 429 | lastSampleAt: Option.none(), |
| 430 | lastError: |
| 431 | config.desktopTelemetryFd === undefined |
| 432 | ? Option.some( |
| 433 | new DesktopTelemetryDescriptorUnavailable({ |
| 434 | mode: config.mode, |
| 435 | }).message, |
| 436 | ) |
| 437 | : Option.none(), |
| 438 | }); |
| 439 | const updateHealth = ( |
| 440 | update: (current: DesktopTelemetryReceiverHealth) => DesktopTelemetryReceiverHealth, |
| 441 | ) => |
| 442 | Ref.modify(health, (current) => { |
| 443 | const next = update(current); |
| 444 | return [next, next]; |
| 445 | }).pipe( |
| 446 | Effect.flatMap((next) => PubSub.publish(healthChanges, next)), |
| 447 | Effect.asVoid, |
| 448 | ); |
| 449 | const updateSampleHealth = (sampledAt: DateTime.Utc) => |
| 450 | recordDesktopTelemetrySampleHealth(health, healthChanges, sampledAt); |
| 451 | |
| 452 | const sendControlMessage = (message: DesktopTelemetryControlMessage) => |
| 453 | controlMutex.withPermits(1)( |
| 454 | Effect.gen(function* () { |
| 455 | const fd = config.desktopTelemetryControlFd; |
| 456 | if (fd === undefined) return; |
| 457 | const encoded = yield* encodeControlMessage(message).pipe( |
| 458 | Effect.mapError( |
| 459 | (cause) => |
| 460 | new DesktopTelemetryControlFailed({ |
| 461 | fd, |
| 462 | operation: "encode", |
| 463 | cause, |
| 464 | }), |
| 465 | ), |
| 466 | ); |
| 467 | yield* writeAllToFileDescriptor(fd, Buffer.from(`${encoded}\n`)).pipe( |
| 468 | Effect.tapError((error) => |
| 469 | updateHealth((current) => ({ |
| 470 | ...current, |
| 471 | status: "degraded", |
| 472 | lastError: Option.some(error.message), |
| 473 | })), |
| 474 | ), |
| 475 | ); |
| 476 | }), |
| 477 | ); |
| 478 | const setDiagnosticsDemand: DesktopTelemetryReceiver["Service"]["setDiagnosticsDemand"] = ( |
| 479 | enabled, |
| 480 | ) => |
| 481 | sendControlMessage({ |
| 482 | version: 1, |
| 483 | type: "setDiagnosticsDemand", |
| 484 | enabled, |
| 485 | }); |
| 486 | |
| 487 | const sendHostPowerIntervals = ( |
| 488 | settings: Parameters<typeof resolveServerBackgroundActivitySettings>[0], |
| 489 | ) => { |
| 490 | const resolved = resolveServerBackgroundActivitySettings(settings); |
| 491 | const activeIntervalMs = Math.max( |
| 492 | 1, |
| 493 | Math.round(Duration.toMillis(resolved.hostPowerMonitorActiveInterval)), |
| 494 | ); |
| 495 | const idleIntervalMs = Math.max( |
| 496 | 1, |
| 497 | Math.round(Duration.toMillis(resolved.hostPowerMonitorIdleInterval)), |
| 498 | ); |
| 499 | return sendControlMessage({ |
| 500 | version: 1, |
| 501 | type: "setHostPowerIntervals", |
| 502 | activeIntervalMs, |
| 503 | idleIntervalMs, |
| 504 | }).pipe( |
| 505 | Effect.andThen( |
| 506 | Ref.set( |
| 507 | snapshotStaleAfterMs, |
| 508 | resolveDesktopTelemetrySnapshotStaleAfterMs(activeIntervalMs, idleIntervalMs), |
| 509 | ), |
| 510 | ), |
| 511 | ); |
| 512 | }; |
| 513 | if (config.desktopTelemetryControlFd !== undefined) { |
| 514 | const settingsChanges = yield* serverSettings.subscribeChanges; |
| 515 | const settings = yield* serverSettings.getSettings; |
| 516 | yield* sendHostPowerIntervals(settings).pipe( |
| 517 | Effect.catchCause((cause) => |
| 518 | Effect.logWarning("Failed to configure desktop host-power intervals", { |
| 519 | cause: String(cause), |
| 520 | }), |
| 521 | ), |
| 522 | ); |
| 523 | yield* settingsChanges.pipe( |
| 524 | Stream.runForEach((settings) => |
| 525 | sendHostPowerIntervals(settings).pipe( |
| 526 | Effect.catchCause((cause) => |
| 527 | Effect.logWarning("Failed to update desktop host-power intervals", { |
| 528 | cause: String(cause), |
| 529 | }), |
| 530 | ), |
| 531 | ), |
| 532 | ), |
| 533 | Effect.forkScoped, |
| 534 | ); |
| 535 | } |
| 536 | |
| 537 | if (config.desktopTelemetryFd !== undefined) { |
| 538 | const fd = config.desktopTelemetryFd; |
| 539 | // The parent waits before closing; use cancellable socket reads so filesystem reads cannot block exit. |
| 540 | const readable = yield* Effect.acquireRelease( |
| 541 | Effect.try({ |
| 542 | try: () => new NodeNet.Socket({ fd, readable: true, writable: false }), |
| 543 | catch: (cause) => new DesktopTelemetryStreamFailed({ fd, cause }), |
| 544 | }), |
| 545 | (stream) => |
| 546 | Effect.sync(() => { |
| 547 | stream.destroy(); |
| 548 | }), |
| 549 | ); |
| 550 | |
| 551 | const messages: Stream.Stream<DesktopHostTelemetryMessageValue, DesktopTelemetryReceiverError> = |
| 552 | NodeStream.fromReadable<Uint8Array, DesktopTelemetryStreamFailed>({ |
| 553 | evaluate: () => readable, |
| 554 | closeOnDone: true, |
| 555 | onError: (cause) => new DesktopTelemetryStreamFailed({ fd, cause }), |
| 556 | }).pipe( |
| 557 | Stream.pipeThroughChannel(Ndjson.decode({ ignoreEmptyLines: true })), |
| 558 | Stream.mapEffect( |
| 559 | ( |
| 560 | value, |
| 561 | ): Effect.Effect< |
| 562 | DesktopHostTelemetryMessageValue, |
| 563 | DesktopTelemetryProtocolMismatch | DesktopTelemetryDecodeFailed |
| 564 | > => { |
| 565 | const version = messageVersion(value); |
| 566 | if (version !== undefined && version !== 1) { |
| 567 | return Effect.fail( |
| 568 | new DesktopTelemetryProtocolMismatch({ |
| 569 | expectedVersion: 1, |
| 570 | receivedVersion: version, |
| 571 | }), |
| 572 | ); |
| 573 | } |
| 574 | return decodeMessage(value).pipe( |
| 575 | Effect.mapError((cause) => new DesktopTelemetryDecodeFailed({ cause })), |
| 576 | ); |
| 577 | }, |
| 578 | ), |
| 579 | Stream.mapError(normalizeReceiverError), |
| 580 | ); |
| 581 | |
| 582 | yield* messages.pipe( |
| 583 | Stream.runForEach((message) => { |
| 584 | const recordContact = DateTime.now.pipe( |
| 585 | Effect.flatMap((now) => |
| 586 | Ref.set(lastContactAtMs, Option.some(DateTime.toEpochMillis(now))), |
| 587 | ), |
| 588 | ); |
| 589 | if (message.type === "desktopTelemetryHello") { |
| 590 | return recordContact.pipe( |
| 591 | Effect.andThen( |
| 592 | updateHealth((current): DesktopTelemetryReceiverHealth => ({ |
| 593 | ...current, |
| 594 | status: "healthy", |
| 595 | lastError: Option.none(), |
| 596 | })), |
| 597 | ), |
| 598 | ); |
| 599 | } |
| 600 | |
| 601 | if (message.type === "shellEnvironment") { |
| 602 | return recordContact.pipe(Effect.andThen(applyShellSnapshot(message))); |
| 603 | } |
| 604 | |
| 605 | if (message.type === "desktopUpdateStatus") { |
| 606 | return recordContact.pipe( |
| 607 | Effect.andThen(Ref.set(latestUpdateReport, Option.some(message))), |
| 608 | Effect.andThen(PubSub.publish(updateReportChanges, message)), |
| 609 | Effect.asVoid, |
| 610 | ); |
| 611 | } |
| 612 | |
| 613 | const sampledAt = DateTime.makeUnsafe(message.sampledAtUnixMs); |
| 614 | return snapshotMutex.withPermits(1)( |
| 615 | recordContact.pipe( |
| 616 | Effect.andThen(Ref.set(latest, Option.some(message))), |
| 617 | Effect.andThen(updateSampleHealth(sampledAt)), |
| 618 | Effect.andThen(PubSub.publish(changes, message)), |
| 619 | Effect.asVoid, |
| 620 | ), |
| 621 | ); |
| 622 | }), |
| 623 | Effect.andThen( |
| 624 | updateHealth((current): DesktopTelemetryReceiverHealth => ({ |
| 625 | ...current, |
| 626 | status: "stopped", |
| 627 | lastError: Option.some(new DesktopTelemetryStreamClosed({ fd }).message), |
| 628 | })), |
| 629 | ), |
| 630 | Effect.catch((error) => |
| 631 | updateHealth((current): DesktopTelemetryReceiverHealth => ({ |
| 632 | ...current, |
| 633 | status: "degraded", |
| 634 | lastError: Option.some(error.message), |
| 635 | })), |
| 636 | ), |
| 637 | Effect.forkScoped, |
| 638 | ); |
| 639 | |
| 640 | yield* Effect.forever( |
| 641 | Effect.sleep(STALE_CHECK_INTERVAL).pipe( |
| 642 | Effect.andThen( |
| 643 | snapshotMutex.withPermits(1)( |
| 644 | Effect.gen(function* () { |
| 645 | const now = yield* DateTime.now; |
| 646 | const nowMs = DateTime.toEpochMillis(now); |
| 647 | const staleAfterMs = yield* Ref.get(snapshotStaleAfterMs); |
| 648 | const staleSnapshot = yield* Ref.modify(latest, (current) => { |
| 649 | if ( |
| 650 | Option.isNone(current) || |
| 651 | current.value.power.stale || |
| 652 | nowMs - current.value.sampledAtUnixMs < staleAfterMs |
| 653 | ) { |
| 654 | return [Option.none<DesktopHostTelemetrySnapshot>(), current] as const; |
| 655 | } |
| 656 | const stale: DesktopHostTelemetrySnapshot = { |
| 657 | ...current.value, |
| 658 | power: { ...current.value.power, stale: true }, |
| 659 | }; |
| 660 | return [Option.some(stale), Option.some(stale)] as const; |
| 661 | }); |
| 662 | if (Option.isNone(staleSnapshot)) { |
| 663 | const lastContact = yield* Ref.get(lastContactAtMs); |
| 664 | if (!isDesktopTelemetryContactStale(lastContact, nowMs)) return; |
| 665 | const staleMessage = new DesktopTelemetryStale({ |
| 666 | fd, |
| 667 | staleAfterMs: INITIAL_SAMPLE_DEADLINE_MS, |
| 668 | }).message; |
| 669 | const changed = yield* Ref.modify(health, (current) => { |
| 670 | if ( |
| 671 | current.status === "stopped" || |
| 672 | Option.isSome(current.lastSampleAt) || |
| 673 | (current.status === "degraded" && |
| 674 | Option.contains(current.lastError, staleMessage)) |
| 675 | ) { |
| 676 | return [Option.none<DesktopTelemetryReceiverHealth>(), current] as const; |
| 677 | } |
| 678 | const next: DesktopTelemetryReceiverHealth = { |
| 679 | ...current, |
| 680 | status: "degraded", |
| 681 | lastError: Option.some(staleMessage), |
| 682 | }; |
| 683 | return [Option.some(next), next] as const; |
| 684 | }); |
| 685 | if (Option.isSome(changed)) { |
| 686 | yield* PubSub.publish(healthChanges, changed.value); |
| 687 | } |
| 688 | return; |
| 689 | } |
| 690 | yield* updateHealth((currentHealth) => ({ |
| 691 | ...currentHealth, |
| 692 | status: currentHealth.status === "stopped" ? "stopped" : "degraded", |
| 693 | lastError: |
| 694 | currentHealth.status === "stopped" |
| 695 | ? currentHealth.lastError |
| 696 | : Option.some(new DesktopTelemetryStale({ fd, staleAfterMs }).message), |
| 697 | })); |
| 698 | yield* PubSub.publish(changes, staleSnapshot.value); |
| 699 | }), |
| 700 | ), |
| 701 | ), |
| 702 | ), |
| 703 | ).pipe(Effect.forkScoped); |
| 704 | } |
| 705 | |
| 706 | return DesktopTelemetryReceiver.of({ |
| 707 | latest: Ref.get(latest), |
| 708 | changes: Stream.fromPubSub(changes), |
| 709 | subscribe: snapshotMutex.withPermits(1)( |
| 710 | Effect.gen(function* () { |
| 711 | const initial = yield* Ref.get(latest); |
| 712 | const subscription = yield* PubSub.subscribe(changes); |
| 713 | return { |
| 714 | latest: initial, |
| 715 | changes: Stream.fromSubscription(subscription), |
| 716 | }; |
| 717 | }), |
| 718 | ), |
| 719 | health: Ref.get(health), |
| 720 | subscribeHealth: subscribeBeforeSnapshotWithoutMutex(healthChanges, Ref.get(health)), |
| 721 | setDiagnosticsDemand, |
| 722 | announceServerReady: sendControlMessage({ version: 1, type: "serverReady" }).pipe( |
| 723 | Effect.withSpan("DesktopTelemetryReceiver.announceServerReady"), |
| 724 | ), |
| 725 | requestDesktopUpdate: Effect.fn("DesktopTelemetryReceiver.requestDesktopUpdate")( |
| 726 | function (requestId, trackSwitch) { |
| 727 | return sendControlMessage({ |
| 728 | version: 1, |
| 729 | type: "requestDesktopUpdate", |
| 730 | requestId, |
| 731 | ...trackSwitch, |
| 732 | }); |
| 733 | }, |
| 734 | ), |
| 735 | commitDesktopUpdate: Effect.fn("DesktopTelemetryReceiver.commitDesktopUpdate")( |
| 736 | function (requestId) { |
| 737 | return sendControlMessage({ version: 1, type: "commitDesktopUpdate", requestId }); |
| 738 | }, |
| 739 | ), |
| 740 | cancelDesktopUpdate: Effect.fn("DesktopTelemetryReceiver.cancelDesktopUpdate")( |
| 741 | function (requestId) { |
| 742 | return sendControlMessage({ version: 1, type: "cancelDesktopUpdate", requestId }); |
| 743 | }, |
| 744 | ), |
| 745 | desktopUpdates: Effect.gen(function* () { |
| 746 | const subscription = yield* PubSub.subscribe(updateReportChanges); |
| 747 | const initial = yield* Ref.get(latestUpdateReport); |
| 748 | return { |
| 749 | latest: initial, |
| 750 | changes: Stream.fromSubscription(subscription), |
| 751 | }; |
| 752 | }), |
| 753 | }); |
| 754 | }); |
| 755 | |
| 756 | export const layer = Layer.effect(DesktopTelemetryReceiver, make()); |
| 757 | |
| 758 | export const layerTest = ( |
| 759 | overrides: Partial<DesktopTelemetryReceiver["Service"]> = {}, |
| 760 | ): Layer.Layer<DesktopTelemetryReceiver> => { |
| 761 | const latest = overrides.latest ?? Effect.succeedNone; |
| 762 | const changes = overrides.changes ?? Stream.empty; |
| 763 | const health = |
| 764 | overrides.health ?? |
| 765 | Effect.succeed({ |
| 766 | status: "unavailable" as const, |
| 767 | lastSampleAt: Option.none<DateTime.Utc>(), |
| 768 | lastError: Option.some("Desktop telemetry test implementation is unavailable."), |
| 769 | }); |
| 770 | return Layer.succeed( |
| 771 | DesktopTelemetryReceiver, |
| 772 | DesktopTelemetryReceiver.of({ |
| 773 | latest, |
| 774 | changes, |
| 775 | subscribe: |
| 776 | overrides.subscribe ?? |
| 777 | latest.pipe( |
| 778 | Effect.map((initial) => ({ |
| 779 | latest: initial, |
| 780 | changes, |
| 781 | })), |
| 782 | ), |
| 783 | health, |
| 784 | subscribeHealth: |
| 785 | overrides.subscribeHealth ?? |
| 786 | health.pipe( |
| 787 | Effect.map((initial) => ({ |
| 788 | latest: initial, |
| 789 | changes: Stream.empty, |
| 790 | })), |
| 791 | ), |
| 792 | setDiagnosticsDemand: Effect.fn("DesktopTelemetryReceiver.setDiagnosticsDemand")(function () { |
| 793 | return Effect.void; |
| 794 | }), |
| 795 | announceServerReady: Effect.void, |
| 796 | requestDesktopUpdate: Effect.fn("DesktopTelemetryReceiver.requestDesktopUpdate")(function () { |
| 797 | return Effect.void; |
| 798 | }), |
| 799 | commitDesktopUpdate: Effect.fn("DesktopTelemetryReceiver.commitDesktopUpdate")(function () { |
| 800 | return Effect.void; |
| 801 | }), |
| 802 | cancelDesktopUpdate: Effect.fn("DesktopTelemetryReceiver.cancelDesktopUpdate")(function () { |
| 803 | return Effect.void; |
| 804 | }), |
| 805 | desktopUpdates: |
| 806 | overrides.desktopUpdates ?? |
| 807 | Effect.succeed({ |
| 808 | latest: Option.none<DesktopUpdateStatusReport>(), |
| 809 | changes: Stream.empty, |
| 810 | }), |
| 811 | ...overrides, |
| 812 | }), |
| 813 | ); |
| 814 | }; |