Repository navigation
chore(desktop): fleet memory telemetry — periodic resource_snapshot to PostHog - #5777
Conversation
|
No actionable comments were generated in the recent review. 🎉 ℹ️ Recent review info⚙️ Run configurationConfiguration used: defaults Review profile: CHILL Plan: Pro Run ID: 📒 Files selected for processing (1)
🚧 Files skipped from review as they are similar to previous changes (1)
📝 WalkthroughWalkthroughAdds a desktop main-process memory telemetry module that aggregates Electron and Node memory metrics into allowlisted snapshots, emits them periodically with jitter, and manages startup/shutdown lifecycle. Tests cover aggregation, filtering, enablement, scheduling, idempotence, and cleanup. ChangesMemory telemetry
Estimated code review effort: 3 (Moderate) | ~20 minutes Sequence Diagram(s)sequenceDiagram
participant MainProcess
participant MemoryTelemetry
participant ElectronAPIs
participant track
MainProcess->>MemoryTelemetry: startMemoryTelemetry()
MemoryTelemetry->>ElectronAPIs: collect periodic resource metrics
ElectronAPIs-->>MemoryTelemetry: return process and window metrics
MemoryTelemetry->>track: emit resource_snapshot
MainProcess->>MemoryTelemetry: stopMemoryTelemetry() before quit
MemoryTelemetry->>MemoryTelemetry: clear pending timer
🚥 Pre-merge checks | ✅ 5✅ Passed checks (5 passed)
✨ Finishing Touches📝 Generate docstrings
🧪 Generate unit tests (beta)
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. Comment |
|
Ready to review this PR? Stage has broken it down into 3 individual chapters for you:
Chapters generated by Stage for commit a150237 on Jul 19, 2026 6:08pm UTC. |
…o PostHog Add a privacy-safe aggregate memory sampler in the main process (SUPER-1550). Every ~5 minutes it emits one flat, numbers-only resource_snapshot event: Electron per-process-class RSS/counts via app.getAppMetrics() (no ps subprocess), this process's heap/RSS via process.memoryUsage(), uptime, and bounded window/webContents counts. A hard RESOURCE_SNAPSHOT_KEYS allowlist filters the payload to exactly those numeric keys — no IDs, names, paths, commands, or terminal/repo/user data can be emitted. Telemetry is gated off in test/dev and honors the telemetry-enabled flag; the timer is jittered, unref'd, idempotent (no HMR/startup dupes), and cleaned up on quit. electron is imported as a namespace and dereferenced lazily so the module links in the test suite regardless of which per-file electron mock is active. Fully dependency-injected with bun:test fake-timer coverage for cadence, payload allowlist, disabled state, and cleanup.
ec8c413 to
343774c
Compare
There was a problem hiding this comment.
🧹 Nitpick comments (2)
apps/desktop/src/main/lib/memory-telemetry/memory-telemetry.test.ts (2)
50-52: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winConsolidate timer cleanup in
afterEach.You can eliminate the repetitive
try/finally { jest.useRealTimers(); }boilerplate across the four tests by movingjest.useRealTimers()into this existingafterEachblock.♻️ Proposed refactor
afterEach(() => { stopMemoryTelemetry(); + jest.useRealTimers(); });After making this change, you can safely remove the
try/finallyblocks from the tests below and let them execute directly.🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@apps/desktop/src/main/lib/memory-telemetry/memory-telemetry.test.ts` around lines 50 - 52, Update the existing afterEach cleanup alongside stopMemoryTelemetry() to also call jest.useRealTimers(). Then remove the repetitive try/finally wrappers and their per-test jest.useRealTimers() calls from the four affected tests, allowing each test body to execute directly while preserving cleanup after every test.
195-202: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winMake the
unrefmock robust against chaining.If
startMemoryTelemetryuses chaining (e.g.,timer = setTimeout().unref()), returningundefinedfrom this mock would result in the internally stored timer beingundefined. This would causeclearTimeout(undefined)to silently fail during cleanup, leaving the active real timer running in the background and hanging the test runner process for the full 5 minutes.Making the mock return
thisprevents this risk.♻️ Proposed fix
- const unref = mock(() => {}); + const unref = mock(function (this: any) { return this; }); const realSetTimeout = globalThis.setTimeout; const setTimeoutSpy = mock((fn: () => void, ms?: number) => { const handle = realSetTimeout(fn, ms); (handle as { unref?: () => void }).unref = unref; return handle; });🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@apps/desktop/src/main/lib/memory-telemetry/memory-telemetry.test.ts` around lines 195 - 202, Update the unref mock in the “unrefs the pending timer so it can't keep the process alive” test to return its timer handle (`this`) after invoking the mock, so chained setTimeout().unref() usage preserves the stored timer and allows cleanup via clearTimeout.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
Nitpick comments:
In `@apps/desktop/src/main/lib/memory-telemetry/memory-telemetry.test.ts`:
- Around line 50-52: Update the existing afterEach cleanup alongside
stopMemoryTelemetry() to also call jest.useRealTimers(). Then remove the
repetitive try/finally wrappers and their per-test jest.useRealTimers() calls
from the four affected tests, allowing each test body to execute directly while
preserving cleanup after every test.
- Around line 195-202: Update the unref mock in the “unrefs the pending timer so
it can't keep the process alive” test to return its timer handle (`this`) after
invoking the mock, so chained setTimeout().unref() usage preserves the stored
timer and allows cleanup via clearTimeout.
ℹ️ Review info
⚙️ Run configuration
Configuration used: defaults
Review profile: CHILL
Plan: Pro
Run ID: 440a8c2a-eed5-425d-9459-508bf6f76edc
📒 Files selected for processing (5)
apps/desktop/src/main/index.tsapps/desktop/src/main/lib/memory-telemetry/index.tsapps/desktop/src/main/lib/memory-telemetry/memory-telemetry.test.tsapps/desktop/src/main/lib/memory-telemetry/memory-telemetry.tsapps/desktop/test-setup.ts
Greptile SummaryAdds a periodic, privacy-safe
Confidence Score: 4/5Safe to merge; the two findings are minor and neither affects correctness of the emitted data in practice. The telemetry module is well-designed with proper cleanup, privacy safeguards, and comprehensive tests. Two small issues exist: normalizeBytes uses value > 0 which incorrectly classifies exactly-zero values as invalid (though the fallback is also 0, so no data is actually wrong), and emitResourceSnapshot is exported without an isEnabled guard, leaving an inconsistency in the public API that a future caller could accidentally exploit. apps/desktop/src/main/lib/memory-telemetry/memory-telemetry.ts — the normalizeBytes predicate and the exported emitResourceSnapshot surface are the two spots worth a second look before merge.
|
| Filename | Overview |
|---|---|
| apps/desktop/src/main/lib/memory-telemetry/memory-telemetry.ts | Core telemetry module: well-structured with hard allowlist, jittered timer, unref'd handle, and idempotent start/stop. Two minor issues: emitResourceSnapshot is exported without an isEnabled guard, and normalizeBytes uses value > 0 making 0 semantically invalid even though it returns 0 either way. |
| apps/desktop/src/main/lib/memory-telemetry/memory-telemetry.test.ts | Solid test coverage: cadence, idempotency, disabled state, payload allowlist, NaN-value filtering, stop/cleanup, and unref verification. Fake-timer tests correctly inject random: () => 0 to make jitter deterministic. |
| apps/desktop/src/main/index.ts | Minimal, correct wiring: startMemoryTelemetry() added after app setup, stopMemoryTelemetry() added at the top of the before-quit cleanup block before async teardown. |
| apps/desktop/test-setup.ts | Electron mock extended with BrowserWindow.getAllWindows and webContents.getAllWebContents stubs needed by the new module; uses Object.assign to preserve the constructor mock while adding the static method. |
| apps/desktop/src/main/lib/memory-telemetry/index.ts | Standard barrel re-export; no issues. |
Sequence Diagram
%%{init: {'theme': 'neutral'}}%%
sequenceDiagram
participant App as index.ts (main)
participant MT as startMemoryTelemetry()
participant SN as scheduleNext()
participant ER as emitResourceSnapshot()
participant BR as buildResourceSnapshot()
participant PH as PostHog (track)
App->>MT: startMemoryTelemetry() [after app ready]
MT->>MT: guard: running? no-op
MT->>MT: isEnabled()? (NODE_ENV + DEFAULT_TELEMETRY_ENABLED)
MT->>SN: scheduleNext(deps)
SN->>SN: setTimeout(SAMPLE_INTERVAL_MS + jitter).unref()
Note over SN: ~5 min + up to 60s jitter, unref'd
loop Every ~5 min
SN-->>ER: timer fires
ER->>BR: buildResourceSnapshot(deps)
BR->>BR: app.getAppMetrics() KB to bytes
BR->>BR: process.memoryUsage()
BR->>BR: BrowserWindow.getAllWindows().length
BR->>BR: webContents.getAllWebContents().length
BR-->>ER: ResourceSnapshot
ER->>ER: filter to RESOURCE_SNAPSHOT_KEYS allowlist
ER->>PH: track resource_snapshot payload
SN->>SN: if running scheduleNext(deps)
end
App->>MT: stopMemoryTelemetry() [before-quit]
MT->>MT: "running = false, clearTimeout(sampleTimer)"
%%{init: {'theme': 'base', 'themeVariables': {"darkMode": true, "background": "#0d1117", "primaryColor": "#21262d", "primaryTextColor": "#e6edf3", "primaryBorderColor": "#8b949e", "lineColor": "#8b949e", "textColor": "#e6edf3", "edgeLabelBackground": "#161b22", "actorBkg": "#21262d", "actorBorder": "#8b949e", "actorTextColor": "#e6edf3", "actorLineColor": "#8b949e", "signalColor": "#8b949e", "signalTextColor": "#e6edf3", "noteBkgColor": "#373320", "noteBorderColor": "#d4a72c", "noteTextColor": "#f0e6c0", "labelBoxBkgColor": "#21262d", "labelBoxBorderColor": "#8b949e", "labelTextColor": "#e6edf3", "loopTextColor": "#e6edf3", "activationBkgColor": "#30363d", "activationBorderColor": "#8b949e"}}}%%
sequenceDiagram
participant App as index.ts (main)
participant MT as startMemoryTelemetry()
participant SN as scheduleNext()
participant ER as emitResourceSnapshot()
participant BR as buildResourceSnapshot()
participant PH as PostHog (track)
App->>MT: startMemoryTelemetry() [after app ready]
MT->>MT: guard: running? no-op
MT->>MT: isEnabled()? (NODE_ENV + DEFAULT_TELEMETRY_ENABLED)
MT->>SN: scheduleNext(deps)
SN->>SN: setTimeout(SAMPLE_INTERVAL_MS + jitter).unref()
Note over SN: ~5 min + up to 60s jitter, unref'd
loop Every ~5 min
SN-->>ER: timer fires
ER->>BR: buildResourceSnapshot(deps)
BR->>BR: app.getAppMetrics() KB to bytes
BR->>BR: process.memoryUsage()
BR->>BR: BrowserWindow.getAllWindows().length
BR->>BR: webContents.getAllWebContents().length
BR-->>ER: ResourceSnapshot
ER->>ER: filter to RESOURCE_SNAPSHOT_KEYS allowlist
ER->>PH: track resource_snapshot payload
SN->>SN: if running scheduleNext(deps)
end
App->>MT: stopMemoryTelemetry() [before-quit]
MT->>MT: "running = false, clearTimeout(sampleTimer)"
Prompt To Fix All With AI
Fix the following 2 code review issues. Work through them one at a time, proposing concise fixes.
---
### Issue 1 of 2
apps/desktop/src/main/lib/memory-telemetry/memory-telemetry.ts:64-68
The condition `value > 0` rejects exactly-zero values and treats them as invalid, yet the fallback is also `0` — so a genuinely zero `workingSetSize` (e.g. a just-started process with no reported RSS) still produces the correct output, but the predicate incorrectly classifies valid data as bad. Using `>= 0` makes the intent precise: accept any non-negative finite number, reject only negatives and non-numbers.
```suggestion
function normalizeBytes(value: number | undefined): number {
return typeof value === "number" && Number.isFinite(value) && value >= 0
? value
: 0;
}
```
### Issue 2 of 2
apps/desktop/src/main/lib/memory-telemetry/memory-telemetry.ts:153-163
`emitResourceSnapshot` exported without `isEnabled` guard — `startMemoryTelemetry` enforces the enabled check before scheduling, but any future caller that imports and invokes `emitResourceSnapshot` directly (e.g. a "capture now" diagnostic call) would bypass that gate entirely. The secondary guard inside `track()` (PostHog key + user identification) provides a safety net, but the exported surface is inconsistent with the stated contract. Consider either not exporting it, or adding a `if (!deps.isEnabled()) return;` guard at the top of the function.
Reviews (1): Last reviewed commit: "chore(desktop): fleet memory telemetry —..." | Re-trigger Greptile
| random: () => number; | ||
| } | ||
|
|
||
| function normalizeBytes(value: number | undefined): number { | ||
| return typeof value === "number" && Number.isFinite(value) && value > 0 |
There was a problem hiding this comment.
The condition
value > 0 rejects exactly-zero values and treats them as invalid, yet the fallback is also 0 — so a genuinely zero workingSetSize (e.g. a just-started process with no reported RSS) still produces the correct output, but the predicate incorrectly classifies valid data as bad. Using >= 0 makes the intent precise: accept any non-negative finite number, reject only negatives and non-numbers.
| random: () => number; | |
| } | |
| function normalizeBytes(value: number | undefined): number { | |
| return typeof value === "number" && Number.isFinite(value) && value > 0 | |
| function normalizeBytes(value: number | undefined): number { | |
| return typeof value === "number" && Number.isFinite(value) && value >= 0 | |
| ? value | |
| : 0; | |
| } |
Prompt To Fix With AI
This is a comment left during a code review.
Path: apps/desktop/src/main/lib/memory-telemetry/memory-telemetry.ts
Line: 64-68
Comment:
The condition `value > 0` rejects exactly-zero values and treats them as invalid, yet the fallback is also `0` — so a genuinely zero `workingSetSize` (e.g. a just-started process with no reported RSS) still produces the correct output, but the predicate incorrectly classifies valid data as bad. Using `>= 0` makes the intent precise: accept any non-negative finite number, reject only negatives and non-numbers.
```suggestion
function normalizeBytes(value: number | undefined): number {
return typeof value === "number" && Number.isFinite(value) && value >= 0
? value
: 0;
}
```
How can I resolve this? If you propose a fix, please make it concise.| /** | ||
| * Emit one snapshot, filtered to exactly the allowlisted numeric keys. | ||
| */ | ||
| export function emitResourceSnapshot(deps: MemoryTelemetryDeps): void { | ||
| const snapshot = buildResourceSnapshot(deps); | ||
| const payload: Record<string, number> = {}; | ||
| for (const key of RESOURCE_SNAPSHOT_KEYS) { | ||
| const value = snapshot[key]; | ||
| if (typeof value === "number" && Number.isFinite(value)) { | ||
| payload[key] = value; | ||
| } |
There was a problem hiding this comment.
emitResourceSnapshot exported without isEnabled guard — startMemoryTelemetry enforces the enabled check before scheduling, but any future caller that imports and invokes emitResourceSnapshot directly (e.g. a "capture now" diagnostic call) would bypass that gate entirely. The secondary guard inside track() (PostHog key + user identification) provides a safety net, but the exported surface is inconsistent with the stated contract. Consider either not exporting it, or adding a if (!deps.isEnabled()) return; guard at the top of the function.
Prompt To Fix With AI
This is a comment left during a code review.
Path: apps/desktop/src/main/lib/memory-telemetry/memory-telemetry.ts
Line: 153-163
Comment:
`emitResourceSnapshot` exported without `isEnabled` guard — `startMemoryTelemetry` enforces the enabled check before scheduling, but any future caller that imports and invokes `emitResourceSnapshot` directly (e.g. a "capture now" diagnostic call) would bypass that gate entirely. The secondary guard inside `track()` (PostHog key + user identification) provides a safety net, but the exported surface is inconsistent with the stated contract. Consider either not exporting it, or adding a `if (!deps.isEnabled()) return;` guard at the top of the function.
How can I resolve this? If you propose a fix, please make it concise.Note: If this suggestion doesn't match your team's coding style, reply to this and let me know. I'll remember it for next time!
…st cleanup - emitResourceSnapshot honors deps.isEnabled() so the exported surface can't bypass the disabled gate (greptile) - normalizeBytes accepts a genuine 0-byte reading (>= 0) instead of treating it as invalid (greptile) - consolidate jest.useRealTimers() into afterEach; drop per-test try/finally (coderabbit)
|
Addressed review feedback in de3e0c6:
Skipped coderabbit's "make the Desktop suite 2173 pass / 0 fail, lint + typecheck clean. |
🧹 Preview Cleanup CompleteThe following preview resources have been cleaned up:
Thank you for your contribution! 🎉 |
What
Adds a privacy-safe aggregate memory telemetry sampler in the desktop main process (SUPER-1550). Every ~5 minutes it emits one flat, numbers-only
resource_snapshotPostHog event so we finally have fleet memory data (renderer RSS vs process/window/webview counts, release-over-release regression detection, before/after proof for perf fixes). ~12 tiny events/user/hour.Closes SUPER-1550.
Schema —
resource_snapshotAll properties are finite numbers. Enforced by the
RESOURCE_SNAPSHOT_KEYSallowlist; emission filters the payload to exactly these keys.uptime_secondsprocess.uptime()(rounded)process_rss_bytes,process_heap_used_bytes,process_heap_total_bytes,process_external_bytes,process_array_buffers_bytesprocess.memoryUsage()electron_main_rss_bytes,electron_renderer_rss_bytes,electron_other_rss_bytes,electron_total_rss_bytesapp.getAppMetrics()by process class (KB→bytes)electron_main_process_count,electron_renderer_process_count,electron_other_process_count,electron_process_countapp.getAppMetrics()countswindow_countBrowserWindow.getAllWindows().lengthweb_contents_countwebContents.getAllWebContents().length(plus the standard
track()context:app_name,platform,desktop_version.)Privacy
emitResourceSnapshotcopies only allowlisted keys whose value is a finite number. Anything else is structurally impossible to emit. A test asserts no key matches/id|name|path|command|repo|url|user|org|title/i.pssubprocess:app.getAppMetrics()reads Electron internals;process.memoryUsage()is in-process. Never spawns per-sample process scans (does not touch the existingresource-metricspspath).Perf / lifecycle
setTimeoutat ~5 min with up to 60s per-tick jitter (fleet doesn't emit in lockstep)..unref()ed — never keeps the process alive.startMemoryTelemetry()(dup-timer guard) so startup + HMR re-entry can't double-schedule.stopMemoryTelemetry()wired intobefore-quitcleanup;emitis wrapped so a telemetry error can never crash the app.DEFAULT_TELEMETRY_ENABLED;track()additionally no-ops until a user is identified and a PostHog key is set.electronis imported as a namespace and dereferenced lazily insidedefaultDeps, so the module links in the test suite regardless of which per-fileelectronmock is active (a static namedimport { webContents }breaks when another test replaces the mock).Validation
bun test(full desktop suite) — 2173 pass, 0 fail across 221 files. The memory-telemetry unit tests (9) are fake-timer based and cover cadence, payload allowlist, disabled state, and cleanup/unref; each was verified to fail under a deliberate mutation (leaked key / broken cleanup).bun run lint— clean (0 warnings).tsc --noEmit— clean across all packages.resourceMetrics.getSnapshot— which calls the sameapp.getAppMetrics()the sampler uses — returns valid live per-class RSS (main 425MB / renderer 735MB). Theresource_snapshotemission itself is intentionally disabled in dev (gated, no PostHog key), so it is not observable in dev by design; that path is covered by the unit tests above.Summary by CodeRabbit
New Features
Reliability
Tests