Record your screen, ship a demo. Free and open-source, GPU-accelerated, no watermarks, no subscriptions. Windows, macOS, Linux. Actively maintained.
TypeScript cross-platformelectronffmpegopen-sourceproduct-demorustscreen-capturescreen-recorderscreen-recordingscreen-studioscreencastspeech-to-texttypescriptvideo-editingvideo-editorwaylandwgpuwhisper
fix(cli): key CLI session folders by run, and judge a pid only in its own namespace
EtienneLescot8cc61aebfca7
diff --git a/electron/cli/sessionData.test.ts b/electron/cli/sessionData.test.tsindex b23c91dfa..d770b6a66 100644--- a/electron/cli/sessionData.test.ts+++ b/electron/cli/sessionData.test.ts@@ -1,24 +1,33 @@-import path from "node:path";import { describe, expect, it } from "vitest";-import { cliSessionDataDir, staleCliSessionDirs } from "./sessionData";+import { isAbandonedSession, type SessionOwner } from "./sessionData";-describe("cliSessionDataDir", () => {- it("gives each process its own folder under userData, apart from the GUI's profile", () => {- const userData = path.join("home", "openscreen");- expect(cliSessionDataDir(userData, 4242)).toBe(path.join(userData, "cli-sessions", "4242"));- expect(cliSessionDataDir(userData, 4242)).not.toBe(cliSessionDataDir(userData, 4243));+const DAY = 24 * 60 * 60 * 1000;+const self: SessionOwner = { host: "box", pidNamespace: "pid:[1]", pid: 100 };+const dead = () => false;+const alive = () => true;++describe("isAbandonedSession", () => {+ it("retires a run on this host and namespace whose pid is gone", () => {+ expect(isAbandonedSession({ ...self, pid: 300 }, DAY, self, dead)).toBe(true);+ });++ it("keeps a run whose pid is still alive", () => {+ expect(isAbandonedSession({ ...self, pid: 200 }, DAY, self, alive)).toBe(false);+ });++ it("never judges a pid from another host or pid namespace", () => {+ expect(isAbandonedSession({ ...self, host: "other", pid: 300 }, DAY, self, dead)).toBe(false);+ expect(+ isAbandonedSession({ ...self, pidNamespace: "pid:[2]", pid: 300 }, DAY, self, dead),+ ).toBe(false);});-});-describe("staleCliSessionDirs", () => {- it("keeps its own folder and those of live runs, and returns those of exited runs", () => {- const alive = new Set([200]);- expect(staleCliSessionDirs(["100", "200", "300"], 100, (pid) => alive.has(pid))).toEqual([- "300",- ]);+ it("keeps a folder with no owner file until it is too old to be live", () => {+ expect(isAbandonedSession(null, DAY, self, dead)).toBe(false);+ expect(isAbandonedSession(null, 8 * DAY, self, dead)).toBe(true);});- it("never touches a folder whose name is not a pid", () => {- expect(staleCliSessionDirs(["notes", "12a", ".DS_Store"], 1, () => false)).toEqual([]);+ it("retires any owner left unrefreshed for longer than a live run allows", () => {+ expect(isAbandonedSession({ ...self, host: "other" }, 8 * DAY, self, alive)).toBe(true);});});diff --git a/electron/cli/sessionData.ts b/electron/cli/sessionData.tsindex 821e8ef65..0d2ade872 100644--- a/electron/cli/sessionData.ts+++ b/electron/cli/sessionData.ts@@ -1,27 +1,56 @@// A CLI run keeps the app's userData (projects, recordings, settings, models) but// must not open the GUI's Chromium profile: its Local Storage, caches and GPU cache// are single-process, so whichever of the two starts first holds them and the other-// silently runs on in-memory storage (#1137). Each CLI process gets its own-// sessionData folder, so concurrent CLI runs do not fight over one either.+// silently runs on in-memory storage (#1137). Each CLI run gets a fresh sessionData+// folder of its own, so concurrent CLI runs do not fight over one either.import fs from "node:fs";+import os from "node:os";import path from "node:path";import type { App } from "electron";const CLI_SESSIONS_DIR = "cli-sessions";+const OWNER_FILE = "owner.json";+const DAY_MS = 24 * 60 * 60 * 1000;+/** A live run refreshes its owner file daily, so one this old belongs to no live run. */+const ABANDONED_AFTER_MS = 7 * DAY_MS;-export function cliSessionDataDir(userDataDir: string, pid: number): string {- return path.join(userDataDir, CLI_SESSIONS_DIR, String(pid));+/** Who a run folder belongs to. A pid only means something on its own host and pid namespace. */+export interface SessionOwner {+ host: string;+ /** `/proc/self/ns/pid` on Linux, where a Flatpak sandbox has a namespace of its own. */+ pidNamespace: string;+ pid: number;}-/** The folders, among `names`, left behind by CLI processes that are no longer running. */-export function staleCliSessionDirs(- names: string[],- ownPid: number,+function currentOwner(): SessionOwner {+ let pidNamespace = "";+ try {+ pidNamespace = fs.readlinkSync("/proc/self/ns/pid");+ } catch {+ // Not Linux: one namespace per host.+ }+ return { host: os.hostname(), pidNamespace, pid: process.pid };+}++/**+ * Whether another run's folder can be deleted. Either its owner provably exited (same+ * host and pid namespace, and no such pid), or it has gone unrefreshed for longer than+ * any live run allows. `owner` is null when the folder has no readable owner file.+ */+export function isAbandonedSession(+ owner: SessionOwner | null,+ ageMs: number,+ self: SessionOwner,isAlive: (pid: number) => boolean,-): string[] {- return names.filter(- (name) => /^\d+$/.test(name) && Number(name) !== ownPid && !isAlive(Number(name)),+): boolean {+ if (ageMs > ABANDONED_AFTER_MS) return true;+ if (!owner) return false;+ return (+ owner.host === self.host &&+ owner.pidNamespace === self.pidNamespace &&+ owner.pid !== self.pid &&+ !isAlive(owner.pid));}@@ -30,21 +59,62 @@ function isProcessAlive(pid: number): boolean {process.kill(pid, 0);return true;} catch (error) {- // EPERM: the process exists, it is just not ours to signal.- return (error as NodeJS.ErrnoException).code === "EPERM";+ // Only ESRCH proves there is no such process; EPERM and anything else may hide a live one.+ return (error as NodeJS.ErrnoException).code !== "ESRCH";+ }+}++async function readOwner(dir: string): Promise<{ owner: SessionOwner | null; ageMs: number }> {+ const ownerPath = path.join(dir, OWNER_FILE);+ try {+ const [text, stat] = await Promise.all([+ fs.promises.readFile(ownerPath, "utf8"),+ fs.promises.stat(ownerPath),+ ]);+ return { owner: JSON.parse(text) as SessionOwner, ageMs: Date.now() - stat.mtimeMs };+ } catch {+ // No owner file: a run that died before writing it. Only age can retire it.+ const stat = await fs.promises.stat(dir);+ return { owner: null, ageMs: Date.now() - stat.mtimeMs };+ }+}++async function sweepAbandonedSessions(root: string, ownDir: string, self: SessionOwner) {+ for (const entry of await fs.promises.readdir(root, { withFileTypes: true })) {+ const dir = path.join(root, entry.name);+ if (!entry.isDirectory() || dir === ownDir) continue;+ try {+ const { owner, ageMs } = await readOwner(dir);+ if (isAbandonedSession(owner, ageMs, self, isProcessAlive)) {+ await fs.promises.rm(dir, { recursive: true, force: true });+ }+ } catch {+ // Still locked or already gone; the next run tries again.+ }}}/**- * Point this process's Chromium session storage at its own folder, then delete the- * folders of CLI runs that have exited. Must run before `app` is ready.+ * Point this process's Chromium session storage at a fresh folder of its own, then+ * delete the folders of CLI runs that are gone. Must run before `app` is ready.*/export function isolateCliSessionData(app: Pick<App, "getPath" | "setPath">): void {const root = path.join(app.getPath("userData"), CLI_SESSIONS_DIR);- const own = cliSessionDataDir(app.getPath("userData"), process.pid);+ const self = currentOwner();+ let ownDir: string;try {- fs.mkdirSync(own, { recursive: true });- app.setPath("sessionData", own);+ fs.mkdirSync(root, { recursive: true });+ // Fresh per run: a recycled pid must never inherit an earlier run's storage.+ ownDir = fs.mkdtempSync(path.join(root, `${self.pid}-`));+ const ownerPath = path.join(ownDir, OWNER_FILE);+ fs.writeFileSync(ownerPath, JSON.stringify(self));+ app.setPath("sessionData", ownDir);+ setInterval(() => {+ const now = new Date();+ fs.promises.utimes(ownerPath, now, now).catch(() => {+ // Missed once; the next day's refresh is still far inside the margin.+ });+ }, DAY_MS).unref();} catch (error) {// A throw here, at module load, would surface as Electron's error dialog. The// shared profile is the lesser harm.@@ -54,10 +124,7 @@ export function isolateCliSessionData(app: Pick<App, "getPath" | "setPath">): vo// A crashed run cannot clean up after itself, and a live one cannot delete what its// own Chromium still holds open, so every run sweeps for the runs before it.- const stale = staleCliSessionDirs(fs.readdirSync(root), process.pid, isProcessAlive);- for (const name of stale) {- fs.promises.rm(path.join(root, name), { recursive: true, force: true }).catch(() => {- // Still locked or already gone; the next run tries again.- });- }+ sweepAbandonedSessions(root, ownDir, self).catch((error) => {+ console.warn("[cli] could not sweep old CLI session data:", error);+ });}