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

main
ts 286 lines 9.78 KB
Raw
1 import type * as Electron from "electron";
2 import * as Cause from "effect/Cause";
3 import * as Clock from "effect/Clock";
4 import * as Context from "effect/Context";
5 import * as Effect from "effect/Effect";
6 import * as Fiber from "effect/Fiber";
7 import * as Layer from "effect/Layer";
8 import * as Path from "effect/Path";
9 import * as Queue from "effect/Queue";
10
11 import * as DesktopEnvironment from "../app/DesktopEnvironment.ts";
12 import { makeRotatingLogFileWriter } from "../app/DesktopObservability.ts";
13
14 export interface RendererIdentity {
15 readonly surface: "main" | "preview" | "splash" | "picture-in-picture" | "devtools";
16 readonly tabId?: string;
17 }
18
19 export class DesktopRendererHistory extends Context.Service<
20 DesktopRendererHistory,
21 {
22 readonly register: (
23 webContents: Electron.WebContents,
24 identity: RendererIdentity,
25 ) => Effect.Effect<void>;
26 readonly recordMetrics: (metrics: ReadonlyArray<Electron.ProcessMetric>) => Effect.Effect<void>;
27 readonly shutdown: Effect.Effect<void>;
28 }
29 >()("@t3tools/desktop/telemetry/DesktopRendererHistory") {}
30
31 interface RendererMemory {
32 readonly sampledAtUnixMs: number;
33 // Electron reports process-wide working sets in KiB, not JavaScript heaps.
34 readonly kind: "electron-process-working-set";
35 readonly workingSetBytes: number;
36 readonly peakWorkingSetBytes: number;
37 }
38
39 interface RendererRecord {
40 readonly version: 1;
41 readonly mainPid: number;
42 readonly mainSessionStartedAtUnixMs: number;
43 readonly timestampUnixMs: number;
44 readonly event:
45 | "created"
46 | "identified"
47 | "dom-ready"
48 | "sample"
49 | "render-process-gone"
50 | "destroyed";
51 readonly webContentsId: number;
52 readonly surface: RendererIdentity["surface"];
53 readonly tabId?: string;
54 readonly rendererPid: number | null;
55 readonly rendererPidSource: "current" | "last-known" | "unavailable";
56 readonly rendererCreationTimeMs: number | null;
57 readonly memory: RendererMemory | null;
58 readonly reason?: Electron.RenderProcessGoneDetails["reason"];
59 readonly exitCode?: number;
60 }
61
62 interface TrackedRenderer {
63 readonly webContents: Electron.WebContents;
64 identity: RendererIdentity;
65 pid: number | null;
66 creationTimeMs: number | null;
67 memory: RendererMemory | null;
68 gone: boolean;
69 readonly removeListeners: () => void;
70 }
71
72 const nonnegative = (value: number): number | null =>
73 Number.isFinite(value) && value >= 0 ? Math.round(value) : null;
74
75 const make = Effect.fn("DesktopRendererHistory.make")(function* () {
76 const environment = yield* DesktopEnvironment.DesktopEnvironment;
77 const path = yield* Path.Path;
78 const clock = yield* Clock.Clock;
79 const context = yield* Effect.context<never>();
80 const runFork = Effect.runForkWith(context);
81 const mainSessionStartedAtUnixMs = clock.currentTimeMillisUnsafe();
82 const records = yield* Queue.sliding<RendererRecord>(256);
83 const active = new Map<number, TrackedRenderer>();
84 let accepting = true;
85 const writer = yield* makeRotatingLogFileWriter({
86 filePath: path.join(environment.logDir, "renderer-history.ndjson"),
87 maxBytes: 256 * 1024,
88 maxFiles: 2,
89 }).pipe(
90 Effect.catch(() =>
91 Effect.logWarning("Renderer incident history could not be opened.").pipe(
92 Effect.as({ writeText: (_chunk: string) => Effect.void }),
93 ),
94 ),
95 );
96
97 const writeRecord = (record: RendererRecord) =>
98 writer.writeText(`${JSON.stringify(record)}\n`).pipe(Effect.ignore);
99 const writerFiber = yield* Effect.forever(
100 Effect.uninterruptibleMask((restore) =>
101 restore(Queue.take(records)).pipe(Effect.flatMap(writeRecord)),
102 ).pipe(
103 Effect.catchCauseIf(
104 (cause) => !Cause.hasInterrupts(cause),
105 () => Effect.void,
106 ),
107 ),
108 ).pipe(
109 Effect.ensuring(
110 Effect.gen(function* () {
111 while (Queue.sizeUnsafe(records) > 0) {
112 const pending = yield* Queue.takeAll(records);
113 yield* Effect.forEach(pending, writeRecord, { discard: true });
114 }
115 }),
116 ),
117 Effect.forkScoped,
118 );
119
120 const readPid = (renderer: TrackedRenderer): RendererRecord["rendererPidSource"] => {
121 try {
122 if (!renderer.gone && !renderer.webContents.isDestroyed()) {
123 const pid = renderer.webContents.getOSProcessId();
124 if (Number.isInteger(pid) && pid > 0) {
125 if (pid !== renderer.pid) {
126 renderer.pid = pid;
127 renderer.creationTimeMs = null;
128 renderer.memory = null;
129 }
130 return "current";
131 }
132 }
133 } catch {
134 // Electron can remove a guest before its destruction callback runs.
135 }
136 return renderer.pid === null ? "unavailable" : "last-known";
137 };
138 const record = (
139 renderer: TrackedRenderer,
140 event: RendererRecord["event"],
141 details?: Electron.RenderProcessGoneDetails,
142 ): void => {
143 const rendererPidSource = readPid(renderer);
144 Queue.offerUnsafe(records, {
145 version: 1,
146 mainPid: process.pid,
147 mainSessionStartedAtUnixMs,
148 timestampUnixMs: clock.currentTimeMillisUnsafe(),
149 event,
150 webContentsId: renderer.webContents.id,
151 ...renderer.identity,
152 rendererPid: renderer.pid,
153 rendererPidSource,
154 rendererCreationTimeMs: renderer.creationTimeMs,
155 memory: renderer.memory,
156 ...(details === undefined
157 ? {}
158 : {
159 reason: details.reason,
160 ...(Number.isFinite(details.exitCode)
161 ? { exitCode: Math.round(details.exitCode) }
162 : {}),
163 }),
164 });
165 };
166
167 const register = (webContents: Electron.WebContents, identity: RendererIdentity) =>
168 Effect.sync(() => {
169 if (!accepting || webContents.isDestroyed()) return;
170 const boundedIdentity: RendererIdentity = {
171 surface: identity.surface,
172 ...(identity.tabId === undefined ? {} : { tabId: identity.tabId.slice(0, 128) }),
173 };
174 const existing = active.get(webContents.id);
175 if (existing !== undefined) {
176 if (
177 existing.identity.surface !== boundedIdentity.surface ||
178 existing.identity.tabId !== boundedIdentity.tabId
179 ) {
180 existing.identity = boundedIdentity;
181 record(existing, "identified");
182 }
183 return;
184 }
185 const onDomReady = () => {
186 if (renderer.gone) {
187 renderer.pid = null;
188 renderer.creationTimeMs = null;
189 renderer.memory = null;
190 renderer.gone = false;
191 }
192 record(renderer, "dom-ready");
193 };
194 const onDevToolsOpened = () => {
195 const tools = webContents.devToolsWebContents;
196 if (tools)
197 runFork(
198 register(tools, {
199 surface: "devtools",
200 ...(renderer.identity.tabId === undefined ? {} : { tabId: renderer.identity.tabId }),
201 }),
202 );
203 };
204 const onGone = (_event: Electron.Event, details: Electron.RenderProcessGoneDetails) => {
205 readPid(renderer);
206 renderer.gone = true;
207 record(renderer, "render-process-gone", details);
208 };
209 const onDestroyed = () => {
210 record(renderer, "destroyed");
211 active.delete(webContents.id);
212 renderer.removeListeners();
213 };
214 const renderer: TrackedRenderer = {
215 webContents,
216 identity: boundedIdentity,
217 pid: null,
218 creationTimeMs: null,
219 memory: null,
220 gone: false,
221 removeListeners: () => {
222 webContents.removeListener("dom-ready", onDomReady);
223 webContents.removeListener("devtools-opened", onDevToolsOpened);
224 webContents.removeListener("render-process-gone", onGone);
225 webContents.removeListener("destroyed", onDestroyed);
226 },
227 };
228 active.set(webContents.id, renderer);
229 webContents.on("dom-ready", onDomReady);
230 webContents.on("devtools-opened", onDevToolsOpened);
231 webContents.on("render-process-gone", onGone);
232 webContents.once("destroyed", onDestroyed);
233 record(renderer, "created");
234 }).pipe(
235 Effect.catchCauseIf(
236 (cause) => !Cause.hasInterrupts(cause),
237 () => Effect.void,
238 ),
239 );
240
241 let lastSampledAtUnixMs = -Infinity;
242 const recordMetrics = (metrics: ReadonlyArray<Electron.ProcessMetric>) =>
243 Effect.sync(() => {
244 if (!accepting) return;
245 const sampledAtUnixMs = clock.currentTimeMillisUnsafe();
246 if (sampledAtUnixMs - lastSampledAtUnixMs < 30_000) return;
247 lastSampledAtUnixMs = sampledAtUnixMs;
248 const byPid = new Map(metrics.map((metric) => [metric.pid, metric]));
249 for (const renderer of active.values()) {
250 const pidSource = readPid(renderer);
251 // A last-known PID may already have been reused by another process.
252 const metric =
253 pidSource !== "current" || renderer.pid === null ? undefined : byPid.get(renderer.pid);
254 if (metric !== undefined) {
255 renderer.creationTimeMs = nonnegative(metric.creationTime);
256 renderer.memory = {
257 sampledAtUnixMs,
258 kind: "electron-process-working-set",
259 workingSetBytes: nonnegative(metric.memory.workingSetSize * 1024) ?? 0,
260 peakWorkingSetBytes: nonnegative(metric.memory.peakWorkingSetSize * 1024) ?? 0,
261 };
262 }
263 // A process can host multiple contents; these rows must not be summed.
264 record(renderer, "sample");
265 }
266 }).pipe(
267 Effect.catchCauseIf(
268 (cause) => !Cause.hasInterrupts(cause),
269 () => Effect.void,
270 ),
271 );
272 const shutdown = Effect.sync(() => {
273 accepting = false;
274 for (const renderer of active.values()) renderer.removeListeners();
275 active.clear();
276 }).pipe(
277 Effect.andThen(Fiber.interrupt(writerFiber)),
278 Effect.asVoid,
279 Effect.withSpan("desktop.rendererHistory.shutdown"),
280 );
281 yield* Effect.addFinalizer(() => shutdown);
282
283 return DesktopRendererHistory.of({ register, recordMetrics, shutdown });
284 });
285
286 export const layer = Layer.effect(DesktopRendererHistory, make());