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

main
ts 62 lines 2.26 KB
Raw
1 // @effect-diagnostics globalTimers:off -- The shared native restart deadline must outlive individual IPC callers.
2 // @effect-diagnostics nodeBuiltinImport:off -- Only Electron's main process can restart its Chromium audio utility.
3 import * as NodeProcess from "node:process";
4 import * as Effect from "effect/Effect";
5 import * as Schema from "effect/Schema";
6 import * as HostProcess from "@t3tools/shared/HostProcess";
7 import { app, type Details, type Event } from "electron";
8
9 class AudioServiceRestartError extends Schema.TaggedError<AudioServiceRestartError>()(
10 "AudioServiceRestartError",
11 { cause: Schema.Defect() },
12 ) {}
13
14 let pendingRestart: Promise<boolean> | undefined;
15
16 export const restart = Effect.fn("ElectronAudio.restart")(function* () {
17 if ((yield* HostProcess.Platform) !== "linux") return false;
18 return yield* Effect.tryPromise({
19 try: () => {
20 if (pendingRestart) return pendingRestart;
21 const audio = app
22 .getAppMetrics()
23 .find(
24 (metric) =>
25 metric.type === "Utility" && metric.serviceName === "audio.mojom.AudioService",
26 );
27 if (!audio) return Promise.resolve(false);
28 // A failed PulseAudio context survives new getUserMedia calls; Chromium reconnects when its utility exits.
29 pendingRestart = new Promise<boolean>((resolve, reject) => {
30 const cleanup = () => {
31 clearTimeout(timer);
32 app.removeListener("child-process-gone", onGone);
33 };
34 const onGone = (_event: Event, details: Details) => {
35 if (details.type === "Utility" && details.serviceName === audio.serviceName) {
36 cleanup();
37 resolve(true);
38 }
39 };
40 const timer = setTimeout(() => {
41 cleanup();
42 resolve(false);
43 }, 5_000);
44 app.on("child-process-gone", onGone);
45 try {
46 NodeProcess.kill(audio.pid, "SIGTERM");
47 } catch (cause) {
48 cleanup();
49 reject(cause);
50 }
51 }).finally(() => {
52 pendingRestart = undefined;
53 });
54 return pendingRestart;
55 },
56 catch: (cause) => new AudioServiceRestartError({ cause }),
57 }).pipe(
58 Effect.catch((cause) =>
59 Effect.logWarning("Could not restart the audio service", cause).pipe(Effect.as(false)),
60 ),
61 );
62 });