Skip to content

armgit / Cap

Public Imported from GitHub
0

Open source Loom alternative. Beautiful, shareable screen recordings.

test(desktop): add memory soak test scripts

Richie McIlroyc9c5af8b7b32
diff --git a/apps/desktop/package.json b/apps/desktop/package.json
index dfa17e9d1..49eb8f37a 100644
--- a/apps/desktop/package.json
+++ b/apps/desktop/package.json
@@ -7,7 +7,9 @@
"preparescript": "node scripts/prepare.js",
"localdev": "dotenv -e ../../.env -- vinxi dev --port 3002",
"build": "vinxi build",
- "tauri": "tauri"
+ "tauri": "tauri",
+ "test:memory": "node scripts/desktop-memory-soak.js",
+ "test:memory:unit": "vitest run scripts/desktop-memory-soak.test.js"
},
"dependencies": {
"@aerofoil/rive-solid-canvas": "^2.1.4",
diff --git a/apps/desktop/scripts/desktop-memory-soak-lib.js b/apps/desktop/scripts/desktop-memory-soak-lib.js
new file mode 100644
index 000000000..66efbe64d
--- /dev/null
+++ b/apps/desktop/scripts/desktop-memory-soak-lib.js
@@ -0,0 +1,299 @@
+import { existsSync } from "node:fs";
+import { fileURLToPath } from "node:url";
+
+const DEV_APP_COMMAND_PREFIX = fileURLToPath(
+ new URL("../../../target/debug/cap-desktop", import.meta.url),
+);
+const INSTALLED_APP_COMMAND_PREFIX = "/Applications/Cap.app/Contents/MacOS/Cap";
+
+export const DEFAULTS = {
+ appCommandPrefix:
+ process.env.CAP_APP_COMMAND_PREFIX ||
+ (existsSync(DEV_APP_COMMAND_PREFIX)
+ ? DEV_APP_COMMAND_PREFIX
+ : INSTALLED_APP_COMMAND_PREFIX),
+ baselineSeconds: 30,
+ cycles: 3,
+ initialWebKitWindowSeconds: 180,
+ intervalSeconds: 10,
+ maxCycleRatchetMb: 128,
+ maxTotalGrowthMb: 768,
+ newWebKitWindowSeconds: 180,
+ recordingSeconds: 20,
+ displaySleepSeconds: 20,
+ launchTimeoutSeconds: 30,
+ stopTimeoutSeconds: 10,
+ storePath:
+ process.env.CAP_STORE_PATH ||
+ `${process.env.HOME}/Library/Application Support/so.cap.desktop.dev/store`,
+ settleSeconds: 120,
+ trailingSamples: 3,
+};
+
+const MEDIA_PROCESS_PATTERNS = [
+ ["coreaudiod", /\/usr\/sbin\/coreaudiod$/],
+ [
+ "cmio-host",
+ /com\.apple\.cmio\.videodriverkithostextension\.systemextension/,
+ ],
+ ["cameracaptured", /\/usr\/libexec\/cameracaptured$/],
+ ["continuity-agent", /\/usr\/libexec\/ContinuityCaptureAgent(?:\s|$)/],
+ ["audioaccessoryd", /\/System\/Library\/CoreServices\/audioaccessoryd$/],
+ ["avconferenced", /\/usr\/libexec\/avconferenced$/],
+ ["vdcassistant", /\/VDC\.plugin\/Contents\/Resources\/VDCAssistant$/],
+];
+
+function toKb(mb) {
+ return Math.round(mb * 1024);
+}
+
+function parseElapsedSeconds(etime) {
+ const parts = etime.split("-");
+ const dayPart = parts.length === 2 ? Number(parts[0]) : 0;
+ const timePart = parts.length === 2 ? parts[1] : parts[0];
+ const segments = timePart.split(":").map(Number);
+
+ let hours = 0;
+ let minutes = 0;
+ let seconds = 0;
+
+ if (segments.length === 3) {
+ [hours, minutes, seconds] = segments;
+ } else if (segments.length === 2) {
+ [minutes, seconds] = segments;
+ }
+
+ return dayPart * 24 * 60 * 60 + hours * 60 * 60 + minutes * 60 + seconds;
+}
+
+export function parsePsOutput(output) {
+ return output
+ .split("\n")
+ .map((line) => line.trim())
+ .filter(Boolean)
+ .map((line) => {
+ const match = line.match(/^(\d+)\s+(\d+)\s+(\d+)\s+(\S+)\s+(.*)$/);
+
+ if (!match) return null;
+
+ const [, pid, rssKb, vszKb, etime, command] = match;
+
+ return {
+ command,
+ etimes: parseElapsedSeconds(etime),
+ pid: Number(pid),
+ rssKb: Number(rssKb),
+ vszKb: Number(vszKb),
+ };
+ })
+ .filter(Boolean);
+}
+
+export function classifyProcess(
+ command,
+ appCommandPrefix = DEFAULTS.appCommandPrefix,
+) {
+ if (
+ command.startsWith(
+ "/System/Library/PrivateFrameworks/SkyLight.framework/Resources/WindowServer",
+ )
+ ) {
+ return {
+ group: "system",
+ kind: "window-server",
+ label: "windowserver",
+ };
+ }
+
+ if (command === appCommandPrefix) {
+ return { group: "cap", kind: "cap-main", label: "cap-main" };
+ }
+
+ if (command.startsWith(`${appCommandPrefix} --crash-reporter-server=`)) {
+ return { group: "cap", kind: "cap-crash", label: "cap-crash" };
+ }
+
+ if (command.includes("com.apple.WebKit.GPU.xpc")) {
+ return { group: "cap", kind: "webkit-gpu", label: "wk-gpu" };
+ }
+
+ if (command.includes("com.apple.WebKit.Networking.xpc")) {
+ return { group: "cap", kind: "webkit-networking", label: "wk-net" };
+ }
+
+ if (command.includes("com.apple.WebKit.WebContent.xpc")) {
+ return { group: "cap", kind: "webkit-webcontent", label: "wk-webcontent" };
+ }
+
+ for (const [label, pattern] of MEDIA_PROCESS_PATTERNS) {
+ if (pattern.test(command)) {
+ return { group: "media", kind: label, label };
+ }
+ }
+
+ return null;
+}
+
+export function findCapMainProcess(
+ processes,
+ appCommandPrefix = DEFAULTS.appCommandPrefix,
+) {
+ return processes
+ .filter((processInfo) => processInfo.command === appCommandPrefix)
+ .sort((left, right) => right.etimes - left.etimes)[0];
+}
+
+export function discoverTrackedProcesses(
+ processes,
+ tracked,
+ options = DEFAULTS,
+) {
+ const nextTracked = new Map(tracked);
+ const capMain = findCapMainProcess(processes, options.appCommandPrefix);
+
+ if (!capMain) {
+ throw new Error(
+ `No running Cap process found for ${options.appCommandPrefix}`,
+ );
+ }
+
+ for (const processInfo of processes) {
+ const classification = classifyProcess(
+ processInfo.command,
+ options.appCommandPrefix,
+ );
+
+ if (!classification) continue;
+
+ const isAlreadyTracked = nextTracked.has(processInfo.pid);
+ const isLongLivedCapWebKit =
+ classification.group === "cap" &&
+ classification.kind.startsWith("webkit-") &&
+ Math.abs(processInfo.etimes - capMain.etimes) <=
+ options.initialWebKitWindowSeconds;
+ const isFreshCapWebKit =
+ classification.group === "cap" &&
+ classification.kind.startsWith("webkit-") &&
+ processInfo.etimes <= options.newWebKitWindowSeconds;
+ const shouldTrack =
+ classification.kind === "cap-main" ||
+ classification.kind === "cap-crash" ||
+ classification.group === "system" ||
+ classification.group === "media" ||
+ isLongLivedCapWebKit ||
+ isFreshCapWebKit;
+
+ if (!shouldTrack) continue;
+
+ nextTracked.set(processInfo.pid, {
+ ...processInfo,
+ ...classification,
+ isNew: !isAlreadyTracked,
+ });
+ }
+
+ return nextTracked;
+}
+
+export function buildSample(processes, tracked, options = DEFAULTS) {
+ const discoveredTracked = discoverTrackedProcesses(
+ processes,
+ tracked,
+ options,
+ );
+ const liveTracked = new Map();
+ let capTotalKb = 0;
+ let mediaTotalKb = 0;
+ let windowServerTotalKb = 0;
+ const processRows = [];
+ const newPids = [];
+
+ for (const [pid, trackedProcess] of discoveredTracked.entries()) {
+ const liveProcess = processes.find(
+ (processInfo) => processInfo.pid === pid,
+ );
+
+ if (!liveProcess) continue;
+
+ const row = {
+ ...trackedProcess,
+ etimes: liveProcess.etimes,
+ rssKb: liveProcess.rssKb,
+ vszKb: liveProcess.vszKb,
+ };
+
+ liveTracked.set(pid, row);
+ processRows.push(row);
+
+ if (row.group === "cap") capTotalKb += row.rssKb;
+ if (row.group === "media") mediaTotalKb += row.rssKb;
+ if (row.group === "system") windowServerTotalKb += row.rssKb;
+ if (row.isNew) newPids.push(pid);
+ }
+
+ processRows.sort((left, right) => right.rssKb - left.rssKb);
+
+ return {
+ capTotalKb,
+ grandTotalKb: capTotalKb + mediaTotalKb + windowServerTotalKb,
+ mediaTotalKb,
+ newPids: newPids.sort((left, right) => left - right),
+ processRows,
+ tracked: liveTracked,
+ windowServerTotalKb,
+ };
+}
+
+export function pickSettledSample(
+ samples,
+ trailingSamples = DEFAULTS.trailingSamples,
+) {
+ if (samples.length === 0) {
+ throw new Error("Cannot pick a settled sample from an empty set");
+ }
+
+ const window = samples.slice(-Math.min(trailingSamples, samples.length));
+
+ return window.reduce((best, sample) =>
+ sample.grandTotalKb < best.grandTotalKb ? sample : best,
+ );
+}
+
+export function evaluateCycles(
+ baselineKb,
+ settledCycleKbs,
+ options = DEFAULTS,
+) {
+ const maxCycleRatchetKb = toKb(options.maxCycleRatchetMb);
+ const maxTotalGrowthKb = toKb(options.maxTotalGrowthMb);
+ const failures = [];
+
+ for (let index = 0; index < settledCycleKbs.length; index += 1) {
+ const current = settledCycleKbs[index];
+ const previous = index === 0 ? baselineKb : settledCycleKbs[index - 1];
+ const cycleDeltaKb = current - previous;
+ const totalDeltaKb = current - baselineKb;
+
+ if (cycleDeltaKb > maxCycleRatchetKb) {
+ failures.push({
+ cycle: index + 1,
+ type: "cycle-ratchet",
+ valueKb: cycleDeltaKb,
+ });
+ }
+
+ if (totalDeltaKb > maxTotalGrowthKb) {
+ failures.push({
+ cycle: index + 1,
+ type: "total-growth",
+ valueKb: totalDeltaKb,
+ });
+ }
+ }
+
+ return failures;
+}
+
+export function formatMb(kb) {
+ return `${(kb / 1024).toFixed(1)} MB`;
+}
diff --git a/apps/desktop/scripts/desktop-memory-soak.js b/apps/desktop/scripts/desktop-memory-soak.js
new file mode 100644
index 000000000..cca10c634
--- /dev/null
+++ b/apps/desktop/scripts/desktop-memory-soak.js
@@ -0,0 +1,583 @@
+import { execFileSync, spawn } from "node:child_process";
+import { existsSync, readFileSync, writeFileSync } from "node:fs";
+import process from "node:process";
+import { createInterface } from "node:readline/promises";
+import { setTimeout as sleep } from "node:timers/promises";
+import {
+ buildSample,
+ DEFAULTS,
+ evaluateCycles,
+ findCapMainProcess,
+ formatMb,
+ parsePsOutput,
+ pickSettledSample,
+} from "./desktop-memory-soak-lib.js";
+
+const HOTKEYS = {
+ startStudioRecording: {
+ code: "KeyR",
+ meta: true,
+ ctrl: true,
+ alt: true,
+ shift: true,
+ },
+ stopRecording: {
+ code: "KeyT",
+ meta: true,
+ ctrl: true,
+ alt: true,
+ shift: true,
+ },
+};
+
+const APPLE_KEY_CODES = {
+ KeyR: 15,
+ KeyT: 17,
+};
+
+const INSTALLED_APP_COMMAND_PREFIX = "/Applications/Cap.app/Contents/MacOS/Cap";
+
+function parseArgs(argv) {
+ const options = {
+ ...DEFAULTS,
+ manual: false,
+ skipDisplaySleep: false,
+ };
+
+ for (let index = 0; index < argv.length; index += 1) {
+ const token = argv[index];
+ const next = argv[index + 1];
+
+ if (token === "--help" || token === "-h") {
+ options.help = true;
+ continue;
+ }
+
+ if (!token.startsWith("--")) continue;
+
+ if (token === "--manual") {
+ options.manual = true;
+ continue;
+ }
+
+ if (token === "--skip-display-sleep") {
+ options.skipDisplaySleep = true;
+ continue;
+ }
+
+ const rawValue = token.includes("=")
+ ? token.slice(token.indexOf("=") + 1)
+ : next;
+
+ if (token.startsWith("--app-command-prefix")) {
+ options.appCommandPrefix = rawValue;
+ if (!token.includes("=")) index += 1;
+ continue;
+ }
+
+ if (token.startsWith("--store-path")) {
+ options.storePath = rawValue;
+ if (!token.includes("=")) index += 1;
+ continue;
+ }
+
+ const value = Number(rawValue);
+
+ if (token.startsWith("--cycles")) {
+ options.cycles = value;
+ if (!token.includes("=")) index += 1;
+ continue;
+ }
+
+ if (token.startsWith("--baseline-seconds")) {
+ options.baselineSeconds = value;
+ if (!token.includes("=")) index += 1;
+ continue;
+ }
+
+ if (token.startsWith("--settle-seconds")) {
+ options.settleSeconds = value;
+ if (!token.includes("=")) index += 1;
+ continue;
+ }
+
+ if (token.startsWith("--interval-seconds")) {
+ options.intervalSeconds = value;
+ if (!token.includes("=")) index += 1;
+ continue;
+ }
+
+ if (token.startsWith("--max-cycle-ratchet-mb")) {
+ options.maxCycleRatchetMb = value;
+ if (!token.includes("=")) index += 1;
+ continue;
+ }
+
+ if (token.startsWith("--max-total-growth-mb")) {
+ options.maxTotalGrowthMb = value;
+ if (!token.includes("=")) index += 1;
+ continue;
+ }
+
+ if (token.startsWith("--new-webkit-window-seconds")) {
+ options.newWebKitWindowSeconds = value;
+ if (!token.includes("=")) index += 1;
+ continue;
+ }
+
+ if (token.startsWith("--initial-webkit-window-seconds")) {
+ options.initialWebKitWindowSeconds = value;
+ if (!token.includes("=")) index += 1;
+ continue;
+ }
+
+ if (token.startsWith("--recording-seconds")) {
+ options.recordingSeconds = value;
+ if (!token.includes("=")) index += 1;
+ continue;
+ }
+
+ if (token.startsWith("--display-sleep-seconds")) {
+ options.displaySleepSeconds = value;
+ if (!token.includes("=")) index += 1;
+ continue;
+ }
+
+ if (token.startsWith("--launch-timeout-seconds")) {
+ options.launchTimeoutSeconds = value;
+ if (!token.includes("=")) index += 1;
+ continue;
+ }
+
+ if (token.startsWith("--stop-timeout-seconds")) {
+ options.stopTimeoutSeconds = value;
+ if (!token.includes("=")) index += 1;
+ }
+ }
+
+ return options;
+}
+
+function printHelp() {
+ console.log("Cap desktop memory soak test");
+ console.log("");
+ console.log("Usage:");
+ console.log(" pnpm --dir apps/desktop test:memory [options]");
+ console.log("");
+ console.log("Options:");
+ console.log(
+ ` --cycles <n> default ${DEFAULTS.cycles}`,
+ );
+ console.log(
+ ` --baseline-seconds <n> default ${DEFAULTS.baselineSeconds}`,
+ );
+ console.log(
+ ` --settle-seconds <n> default ${DEFAULTS.settleSeconds}`,
+ );
+ console.log(
+ ` --interval-seconds <n> default ${DEFAULTS.intervalSeconds}`,
+ );
+ console.log(
+ ` --max-cycle-ratchet-mb <n> default ${DEFAULTS.maxCycleRatchetMb}`,
+ );
+ console.log(
+ ` --max-total-growth-mb <n> default ${DEFAULTS.maxTotalGrowthMb}`,
+ );
+ console.log(
+ ` --new-webkit-window-seconds <n> default ${DEFAULTS.newWebKitWindowSeconds}`,
+ );
+ console.log(
+ ` --initial-webkit-window-seconds <n> default ${DEFAULTS.initialWebKitWindowSeconds}`,
+ );
+ console.log(
+ ` --recording-seconds <n> default ${DEFAULTS.recordingSeconds}`,
+ );
+ console.log(
+ ` --display-sleep-seconds <n> default ${DEFAULTS.displaySleepSeconds}`,
+ );
+ console.log(
+ ` --launch-timeout-seconds <n> default ${DEFAULTS.launchTimeoutSeconds}`,
+ );
+ console.log(
+ ` --stop-timeout-seconds <n> default ${DEFAULTS.stopTimeoutSeconds}`,
+ );
+ console.log(
+ ` --app-command-prefix <path> default ${DEFAULTS.appCommandPrefix}`,
+ );
+ console.log(
+ ` --store-path <path> default ${DEFAULTS.storePath}`,
+ );
+ console.log(
+ " --manual keep the old prompt-driven flow",
+ );
+ console.log(
+ " --skip-display-sleep skip pmset displaysleepnow",
+ );
+ console.log("");
+ console.log(
+ "The script launches the target Cap binary, rewrites the selected store with temporary hotkeys, tracks Cap, WindowServer, related WebKit helpers, and camera/audio daemons, and restores the store afterward.",
+ );
+ console.log(
+ "Quit any other Cap instance before running this so WindowServer noise stays attributable to the dev build.",
+ );
+}
+
+function readProcesses() {
+ const output = execFileSync(
+ "ps",
+ ["-axo", "pid=,rss=,vsz=,etime=,command="],
+ { encoding: "utf8" },
+ );
+
+ return parsePsOutput(output);
+}
+
+function sampleCount(durationSeconds, intervalSeconds) {
+ return Math.max(1, Math.ceil(durationSeconds / intervalSeconds));
+}
+
+function renderTopProcesses(sample) {
+ return sample.processRows
+ .slice(0, 5)
+ .map((row) => `${row.label}:${row.pid}:${formatMb(row.rssKb)}`)
+ .join(" ");
+}
+
+async function collectPhase(name, seconds, intervalSeconds, tracked, options) {
+ const samples = [];
+ let currentTracked = tracked;
+ const totalSamples = sampleCount(seconds, intervalSeconds);
+
+ for (let index = 0; index < totalSamples; index += 1) {
+ const sample = buildSample(readProcesses(), currentTracked, options);
+ currentTracked = sample.tracked;
+ samples.push(sample);
+
+ const newPidSummary =
+ sample.newPids.length > 0 ? ` new:${sample.newPids.join(",")}` : "";
+
+ console.log(
+ `${name} ${index + 1}/${totalSamples} cap=${formatMb(sample.capTotalKb)} ws=${formatMb(sample.windowServerTotalKb)} media=${formatMb(sample.mediaTotalKb)} total=${formatMb(sample.grandTotalKb)}${newPidSummary}`,
+ );
+ console.log(` ${renderTopProcesses(sample)}`);
+
+ if (index < totalSamples - 1) {
+ await sleep(intervalSeconds * 1000);
+ }
+ }
+
+ return {
+ samples,
+ settled: pickSettledSample(samples, options.trailingSamples),
+ tracked: currentTracked,
+ };
+}
+
+function restoreStore(path, originalStoreContents) {
+ writeFileSync(path, originalStoreContents);
+}
+
+function writeAutomationStore(path) {
+ if (!existsSync(path)) {
+ throw new Error(`Store not found: ${path}`);
+ }
+
+ const originalStoreContents = readFileSync(path, "utf8");
+ const originalStore = JSON.parse(originalStoreContents);
+ const nextStore = {
+ ...originalStore,
+ hotkeys: {
+ hotkeys: {
+ ...(originalStore.hotkeys?.hotkeys ?? {}),
+ startStudioRecording: HOTKEYS.startStudioRecording,
+ stopRecording: HOTKEYS.stopRecording,
+ },
+ },
+ recording_settings: {
+ ...(originalStore.recording_settings ?? {}),
+ mode: "studio",
+ target: null,
+ },
+ };
+
+ writeFileSync(path, `${JSON.stringify(nextStore, null, 2)}\n`);
+
+ return originalStoreContents;
+}
+
+function modifiersForHotkey(hotkey) {
+ return [
+ hotkey.meta ? "command down" : null,
+ hotkey.ctrl ? "control down" : null,
+ hotkey.alt ? "option down" : null,
+ hotkey.shift ? "shift down" : null,
+ ]
+ .filter(Boolean)
+ .join(", ");
+}
+
+function pressHotkey(hotkey) {
+ const keyCode = APPLE_KEY_CODES[hotkey.code];
+
+ if (keyCode === undefined) {
+ throw new Error(`Unsupported hotkey code: ${hotkey.code}`);
+ }
+
+ execFileSync("osascript", [
+ "-e",
+ `tell application "System Events" to key code ${keyCode} using {${modifiersForHotkey(hotkey)}}`,
+ ]);
+}
+
+function sleepDisplay() {
+ execFileSync("pmset", ["displaysleepnow"]);
+}
+
+function listOtherCapProcesses(options) {
+ return readProcesses().filter(
+ (processInfo) =>
+ processInfo.command !== options.appCommandPrefix &&
+ (processInfo.command === INSTALLED_APP_COMMAND_PREFIX ||
+ processInfo.command ===
+ `${INSTALLED_APP_COMMAND_PREFIX} --crash-reporter-server=/tmp/socket` ||
+ processInfo.command.startsWith(
+ `${INSTALLED_APP_COMMAND_PREFIX} --crash-reporter-server=`,
+ ) ||
+ processInfo.command.endsWith("/target/debug/cap-desktop")),
+ );
+}
+
+async function waitForApp(options) {
+ const deadline = Date.now() + options.launchTimeoutSeconds * 1000;
+
+ while (Date.now() < deadline) {
+ const app = findCapMainProcess(readProcesses(), options.appCommandPrefix);
+
+ if (app) return app;
+
+ await sleep(500);
+ }
+
+ throw new Error(
+ `Cap did not launch within ${options.launchTimeoutSeconds} seconds: ${options.appCommandPrefix}`,
+ );
+}
+
+async function waitForAppExit(child, timeoutSeconds) {
+ const deadline = Date.now() + timeoutSeconds * 1000;
+
+ while (Date.now() < deadline) {
+ if (child.exitCode !== null) return;
+ await sleep(250);
+ }
+}
+
+async function stopChild(child, timeoutSeconds) {
+ if (!child || child.exitCode !== null) return;
+
+ child.kill("SIGTERM");
+ await waitForAppExit(child, timeoutSeconds);
+
+ if (child.exitCode !== null) return;
+
+ child.kill("SIGKILL");
+ await waitForAppExit(child, 2);
+}
+
+async function runAutomatedCycle(cycle, tracked, options) {
+ console.log(`Cycle ${cycle}/${options.cycles}: start recording`);
+ pressHotkey(HOTKEYS.startStudioRecording);
+ await sleep(options.recordingSeconds * 1000);
+
+ if (!options.skipDisplaySleep) {
+ console.log(
+ `Cycle ${cycle}/${options.cycles}: sleep display for ${options.displaySleepSeconds}s`,
+ );
+ sleepDisplay();
+ await sleep(options.displaySleepSeconds * 1000);
+ }
+
+ console.log(`Cycle ${cycle}/${options.cycles}: stop recording`);
+ pressHotkey(HOTKEYS.stopRecording);
+ await sleep(1000);
+ pressHotkey(HOTKEYS.stopRecording);
+ await sleep(3000);
+
+ return collectPhase(
+ `cycle-${cycle}`,
+ options.settleSeconds,
+ options.intervalSeconds,
+ tracked,
+ options,
+ );
+}
+
+async function main() {
+ if (process.platform !== "darwin") {
+ console.error("This soak test only supports macOS.");
+ process.exit(1);
+ }
+
+ const options = parseArgs(process.argv.slice(2));
+
+ if (options.help) {
+ printHelp();
+ return;
+ }
+
+ const existingTargetProcess = findCapMainProcess(
+ readProcesses(),
+ options.appCommandPrefix,
+ );
+ if (existingTargetProcess) {
+ throw new Error(
+ `Quit the target app before running the soak test: ${options.appCommandPrefix}`,
+ );
+ }
+
+ const otherCapProcesses = listOtherCapProcesses(options);
+ if (otherCapProcesses.length > 0) {
+ throw new Error(
+ `Quit other Cap processes before running the soak test: ${otherCapProcesses.map((processInfo) => processInfo.command).join(", ")}`,
+ );
+ }
+
+ let originalStoreContents = null;
+ let child = null;
+ let cleanupStarted = false;
+ const rl = options.manual
+ ? createInterface({
+ input: process.stdin,
+ output: process.stdout,
+ })
+ : null;
+
+ const cleanup = async () => {
+ if (cleanupStarted) return;
+ cleanupStarted = true;
+ await stopChild(child, options.stopTimeoutSeconds);
+ if (originalStoreContents !== null) {
+ restoreStore(options.storePath, originalStoreContents);
+ }
+ };
+
+ for (const signal of ["SIGINT", "SIGTERM", "SIGHUP"]) {
+ process.on(signal, () => {
+ cleanup()
+ .then(() => process.exit(1))
+ .catch((error) => {
+ console.error(error instanceof Error ? error.message : String(error));
+ process.exit(1);
+ });
+ });
+ }
+
+ try {
+ originalStoreContents = writeAutomationStore(options.storePath);
+
+ if (!existsSync(options.appCommandPrefix)) {
+ throw new Error(`App binary not found: ${options.appCommandPrefix}`);
+ }
+
+ child = spawn(options.appCommandPrefix, [], {
+ stdio: "ignore",
+ });
+
+ await waitForApp(options);
+ await sleep(3000);
+
+ let tracked = new Map();
+
+ console.log("Collecting baseline...");
+ const baselinePhase = await collectPhase(
+ "baseline",
+ options.baselineSeconds,
+ options.intervalSeconds,
+ tracked,
+ options,
+ );
+ tracked = baselinePhase.tracked;
+
+ const baseline = baselinePhase.settled;
+ console.log(
+ `Baseline settled total=${formatMb(baseline.grandTotalKb)} cap=${formatMb(baseline.capTotalKb)} ws=${formatMb(baseline.windowServerTotalKb)} media=${formatMb(baseline.mediaTotalKb)}`,
+ );
+
+ const cycleSettledTotals = [];
+
+ for (let cycle = 1; cycle <= options.cycles; cycle += 1) {
+ const phase = options.manual
+ ? await rl
+ .question(
+ `Cycle ${cycle}/${options.cycles}: start and stop a recording in Cap, then press Enter.`,
+ )
+ .then(() =>
+ collectPhase(
+ `cycle-${cycle}`,
+ options.settleSeconds,
+ options.intervalSeconds,
+ tracked,
+ options,
+ ),
+ )
+ : await runAutomatedCycle(cycle, tracked, options);
+ tracked = phase.tracked;
+
+ const settled = phase.settled;
+ cycleSettledTotals.push(settled.grandTotalKb);
+
+ const previousSettled =
+ cycle === 1
+ ? baseline.grandTotalKb
+ : cycleSettledTotals[cycleSettledTotals.length - 2];
+ const cycleDeltaKb = settled.grandTotalKb - previousSettled;
+ const totalDeltaKb = settled.grandTotalKb - baseline.grandTotalKb;
+ const newWebContent = settled.processRows
+ .filter((row) => row.kind === "webkit-webcontent" && row.isNew)
+ .map((row) => row.pid);
+
+ console.log(
+ `Settled cycle ${cycle}: total=${formatMb(settled.grandTotalKb)} cap=${formatMb(settled.capTotalKb)} ws=${formatMb(settled.windowServerTotalKb)} media=${formatMb(settled.mediaTotalKb)} delta-prev=${formatMb(cycleDeltaKb)} delta-baseline=${formatMb(totalDeltaKb)}`,
+ );
+
+ if (newWebContent.length > 0) {
+ console.log(` new-webcontent=${newWebContent.join(",")}`);
+ }
+ }
+
+ const failures = evaluateCycles(
+ baseline.grandTotalKb,
+ cycleSettledTotals,
+ options,
+ );
+
+ console.log("");
+ console.log("Summary");
+ console.log(
+ ` baseline=${formatMb(baseline.grandTotalKb)} final=${formatMb(cycleSettledTotals[cycleSettledTotals.length - 1] ?? baseline.grandTotalKb)}`,
+ );
+
+ if (failures.length === 0) {
+ console.log(" result=PASS");
+ return;
+ }
+
+ console.log(" result=FAIL");
+
+ for (const failure of failures) {
+ console.log(
+ ` cycle=${failure.cycle} type=${failure.type} value=${formatMb(failure.valueKb)}`,
+ );
+ }
+
+ process.exitCode = 1;
+ } finally {
+ await cleanup();
+ rl?.close();
+ }
+}
+
+main().catch((error) => {
+ console.error(error instanceof Error ? error.message : String(error));
+ process.exit(1);
+});
diff --git a/apps/desktop/scripts/desktop-memory-soak.test.js b/apps/desktop/scripts/desktop-memory-soak.test.js
new file mode 100644
index 000000000..d367a1536
--- /dev/null
+++ b/apps/desktop/scripts/desktop-memory-soak.test.js
@@ -0,0 +1,95 @@
+import { describe, expect, it } from "vitest";
+import {
+ buildSample,
+ classifyProcess,
+ DEFAULTS,
+ evaluateCycles,
+ parsePsOutput,
+ pickSettledSample,
+} from "./desktop-memory-soak-lib.js";
+
+describe("desktop-memory-soak", () => {
+ it("classifies Cap and media processes", () => {
+ expect(classifyProcess(DEFAULTS.appCommandPrefix)).toMatchObject({
+ group: "cap",
+ kind: "cap-main",
+ });
+ expect(
+ classifyProcess(
+ `${DEFAULTS.appCommandPrefix} --crash-reporter-server=/tmp/socket`,
+ ),
+ ).toMatchObject({
+ group: "cap",
+ kind: "cap-crash",
+ });
+ expect(
+ classifyProcess(
+ "/System/Library/Frameworks/WebKit.framework/Versions/A/XPCServices/com.apple.WebKit.WebContent.xpc/Contents/MacOS/com.apple.WebKit.WebContent",
+ ),
+ ).toMatchObject({
+ group: "cap",
+ kind: "webkit-webcontent",
+ });
+ expect(classifyProcess("/usr/sbin/coreaudiod")).toMatchObject({
+ group: "media",
+ kind: "coreaudiod",
+ });
+ expect(
+ classifyProcess(
+ "/System/Library/PrivateFrameworks/SkyLight.framework/Resources/WindowServer -daemon",
+ ),
+ ).toMatchObject({
+ group: "system",
+ kind: "window-server",
+ });
+ });
+
+ it("parses ps output and totals tracked processes", () => {
+ const processes = parsePsOutput(`
+1000 1200000 435000000 00:16:39 /System/Library/PrivateFrameworks/SkyLight.framework/Resources/WindowServer -daemon
+2004 400000 441000000 00:02:00 ${DEFAULTS.appCommandPrefix}
+2005 25000 435000000 00:02:00 ${DEFAULTS.appCommandPrefix} --crash-reporter-server=/tmp/socket
+2008 90000 440000000 00:02:00 /System/Library/Frameworks/WebKit.framework/Versions/A/XPCServices/com.apple.WebKit.GPU.xpc/Contents/MacOS/com.apple.WebKit.GPU
+2075 300000 507000000 00:01:55 /System/Library/Frameworks/WebKit.framework/Versions/A/XPCServices/com.apple.WebKit.WebContent.xpc/Contents/MacOS/com.apple.WebKit.WebContent
+431 50000 435000000 00:16:39 /usr/sbin/coreaudiod
+532 20000 435000000 00:16:39 /usr/libexec/cameracaptured
+`);
+
+ const sample = buildSample(processes, new Map(), DEFAULTS);
+
+ expect(sample.capTotalKb).toBe(815000);
+ expect(sample.mediaTotalKb).toBe(70000);
+ expect(sample.windowServerTotalKb).toBe(1200000);
+ expect(sample.grandTotalKb).toBe(2085000);
+ expect(sample.newPids).toEqual([431, 532, 1000, 2004, 2005, 2008, 2075]);
+ });
+
+ it("picks the lowest sample from the trailing settle window", () => {
+ const settled = pickSettledSample(
+ [
+ { grandTotalKb: 1200 },
+ { grandTotalKb: 1000 },
+ { grandTotalKb: 900 },
+ { grandTotalKb: 950 },
+ ],
+ 3,
+ );
+
+ expect(settled.grandTotalKb).toBe(900);
+ });
+
+ it("flags cycle ratchet and total growth failures", () => {
+ const failures = evaluateCycles(1000, [1200, 1400, 2200], {
+ ...DEFAULTS,
+ maxCycleRatchetMb: 0.1,
+ maxTotalGrowthMb: 0.5,
+ });
+
+ expect(failures).toEqual([
+ { cycle: 1, type: "cycle-ratchet", valueKb: 200 },
+ { cycle: 2, type: "cycle-ratchet", valueKb: 200 },
+ { cycle: 3, type: "cycle-ratchet", valueKb: 800 },
+ { cycle: 3, type: "total-growth", valueKb: 1200 },
+ ]);
+ });
+});
diff --git a/package.json b/package.json
index 9ec212b2b..00e3a15d0 100644
--- a/package.json
+++ b/package.json
@@ -38,6 +38,8 @@
"test:suite:encoding": "pnpm with-env cargo run -p cap-test -- suite encoding",
"test:suite:playback": "pnpm with-env cargo run -p cap-test -- suite playback",
"test:suite:sync": "pnpm with-env cargo run -p cap-test -- suite sync",
+ "test:desktop:memory": "pnpm --dir apps/desktop test:memory",
+ "test:desktop:memory:unit": "pnpm --dir apps/desktop test:memory:unit",
"web": "pnpm --filter=@cap/web",
"env-setup": "node scripts/env-cli.js",
"check-tauri-versions": "node scripts/check-tauri-plugin-versions.js",