Skip to content

Create polished demo videos without editing skills. Mac/Windows/Linux

Restore Linux source selection and fix portal cancellation

webadderall783c80f89508
diff --git a/README.md b/README.md
index 121ef934..c13d0fcd 100644
--- a/README.md
+++ b/README.md
@@ -36,7 +36,7 @@ Platform notes:
- **macOS** uses native ScreenCaptureKit-based capture helpers.
- **Windows** uses a native Windows Graphics Capture (WGC) helper on supported builds, with native WASAPI audio support.
-- **Linux** records through Electron capture APIs. Cursor hiding is not supported on Linux today.
+- **Linux** records through Electron capture APIs. X11 uses a screen/window source list; Wayland opens the system picker when recording starts. Cursor hiding is not supported on Linux today.
---
diff --git a/electron/ipc/capturePickerSources.test.ts b/electron/ipc/capturePickerSources.test.ts
index bc7a54c9..f6780f5b 100644
--- a/electron/ipc/capturePickerSources.test.ts
+++ b/electron/ipc/capturePickerSources.test.ts
@@ -3,21 +3,19 @@ const mocks = vi.hoisted(() => ({
exec: vi.fn(),
sources: vi.fn(),
mac: vi.fn(),
- linux: vi.fn(),
dip: vi.fn(),
}));
vi.mock("electron", () => ({ systemPreferences: { getMediaAccessStatus: () => "granted" } }));
vi.mock("node:util", () => ({ promisify: () => mocks.exec }));
vi.mock("./cursor/bounds", () => ({
getNativeMacWindowsFrontToBack: mocks.mac,
- resolveLinuxWindowBounds: mocks.linux,
}));
vi.mock("./register/sources", () => ({ getDesktopSources: mocks.sources }));
vi.mock("./utils", () => ({
parseWindowId: (id?: string) => Number(id?.split(":")[1]),
getScreen: () => ({ screenToDipRect: mocks.dip }),
}));
-import { listCapturePickerWindows, parseStackingOrder } from "./capturePickerSources";
+import { listCapturePickerWindows } from "./capturePickerSources";
const platform = process.platform;
afterEach(() => Object.defineProperty(process, "platform", { value: platform }));
beforeEach(() => {
@@ -28,17 +26,10 @@ beforeEach(() => {
]);
});
describe("capture picker source adapters", () => {
- it("reads X11 stacking from topmost to bottommost", async () => {
+ it("keeps Linux window selection on its source list without X11 helper probes", async () => {
Object.defineProperty(process, "platform", { value: "linux" });
- mocks.exec.mockResolvedValue({
- stdout: "_NET_CLIENT_LIST_STACKING(WINDOW): window id # 0x66, 0x65",
- });
- mocks.linux.mockResolvedValue({ x: 0, y: 0, width: 400, height: 300 });
- expect(parseStackingOrder("0x66, 0x65")).toEqual([101, 102]);
- expect((await listCapturePickerWindows()).map((entry) => entry.id)).toEqual([
- "window:101:0",
- "window:102:0",
- ]);
+ await expect(listCapturePickerWindows()).rejects.toThrow("Use the source list on Linux");
+ expect(mocks.exec).not.toHaveBeenCalled();
});
it("matches Windows handles to real capture IDs and converts physical bounds to DIP", async () => {
Object.defineProperty(process, "platform", { value: "win32" });
diff --git a/electron/ipc/capturePickerSources.ts b/electron/ipc/capturePickerSources.ts
index 2c9b8da4..37d78bbe 100644
--- a/electron/ipc/capturePickerSources.ts
+++ b/electron/ipc/capturePickerSources.ts
@@ -1,19 +1,13 @@
import { systemPreferences } from "electron";
import { execFile } from "node:child_process";
import { promisify } from "node:util";
-import { getNativeMacWindowsFrontToBack, resolveLinuxWindowBounds } from "./cursor/bounds";
+import { getNativeMacWindowsFrontToBack } from "./cursor/bounds";
import type { CapturePickerWindow, SelectedSource } from "./types";
import { getScreen, parseWindowId } from "./utils";
import { getDesktopSources } from "./register/sources";
const exec = promisify(execFile);
-export function parseStackingOrder(text: string): number[] {
- return [...text.matchAll(/0x[0-9a-f]+/gi)]
- .map((match) => Number.parseInt(match[0], 16))
- .reverse();
-}
-
// GetTopWindow/GetWindow walks front to back. Restrict the result to Electron's
// capturable sources rather than inventing source IDs or changing capture routes.
const WINDOWS_SCRIPT = `Add-Type -TypeDefinition @"
@@ -68,6 +62,7 @@ export async function listCapturePickerWindows(): Promise<CapturePickerWindow[]>
height: entry.height!,
}));
}
+ if (process.platform !== "win32") throw new Error("Use the source list on Linux.");
const sources = await getDesktopSources(
{
types: ["window"],
@@ -81,62 +76,31 @@ export async function listCapturePickerWindows(): Promise<CapturePickerWindow[]>
typeof source.id === "string" && source.id.startsWith("window:"),
);
const byId = new Map(capturable.map((source) => [parseWindowId(source.id), source]));
- if (process.platform === "win32") {
- const { stdout } = await exec(
- "powershell.exe",
- ["-NoProfile", "-NonInteractive", "-Command", WINDOWS_SCRIPT],
- { timeout: 10000, maxBuffer: 4 * 1024 * 1024 },
- );
- const entries: unknown = JSON.parse(stdout);
- if (!Array.isArray(entries)) throw new Error("Unable to read window positions.");
- return entries.flatMap((entry) => {
- const source = byId.get(entry.id);
- if (
- !source ||
- ![entry.x, entry.y, entry.width, entry.height].every(Number.isFinite) ||
- entry.width <= 0 ||
- entry.height <= 0
- )
- return [];
- const bounds = getScreen().screenToDipRect(null, entry);
- return [
- {
- ...bounds,
- id: source.id,
- appName: "",
- title: source.name,
- display_id: source.display_id,
- },
- ];
- });
- }
- const { stdout } = await exec("xprop", ["-root", "_NET_CLIENT_LIST_STACKING"], {
- timeout: 3000,
- });
- if (!stdout.includes("window id #"))
- throw new Error("Unable to detect windows on this desktop.");
- const ordered = parseStackingOrder(stdout).flatMap((id) => {
- const source = byId.get(id);
- return source ? [source] : [];
+ const { stdout } = await exec(
+ "powershell.exe",
+ ["-NoProfile", "-NonInteractive", "-Command", WINDOWS_SCRIPT],
+ { timeout: 10000, maxBuffer: 4 * 1024 * 1024 },
+ );
+ const entries: unknown = JSON.parse(stdout);
+ if (!Array.isArray(entries)) throw new Error("Unable to read window positions.");
+ return entries.flatMap((entry) => {
+ const source = byId.get(entry.id);
+ if (
+ !source ||
+ ![entry.x, entry.y, entry.width, entry.height].every(Number.isFinite) ||
+ entry.width <= 0 ||
+ entry.height <= 0
+ )
+ return [];
+ const bounds = getScreen().screenToDipRect(null, entry);
+ return [
+ {
+ ...bounds,
+ id: source.id,
+ appName: "",
+ title: source.name,
+ display_id: source.display_id,
+ },
+ ];
});
- const windows: CapturePickerWindow[] = [];
- // Bound the number of simultaneous X11 helper processes.
- for (let offset = 0; offset < ordered.length; offset += 8) {
- const batch = await Promise.all(
- ordered.slice(offset, offset + 8).map(async (source) => {
- const bounds = await resolveLinuxWindowBounds(source);
- if (!bounds)
- throw new Error("Unable to detect a window position. Try the picker again.");
- return {
- ...bounds,
- id: source.id,
- appName: "",
- title: source.name,
- display_id: source.display_id,
- };
- }),
- );
- windows.push(...batch);
- }
- return windows;
}
diff --git a/electron/ipc/captureSelection.test.ts b/electron/ipc/captureSelection.test.ts
index 7f905bd7..235f77ea 100644
--- a/electron/ipc/captureSelection.test.ts
+++ b/electron/ipc/captureSelection.test.ts
@@ -40,6 +40,7 @@ beforeEach(() => {
});
afterEach(() => {
Object.defineProperty(process, "platform", { value: platform });
+ vi.unstubAllEnvs();
});
describe("remembered capture selection", () => {
it("restores only the same available window", async () => {
@@ -96,3 +97,54 @@ describe("remembered capture selection", () => {
expect(stored.platform).toBe("darwin");
});
});
+
+describe("Linux selection", () => {
+ beforeEach(() => {
+ Object.defineProperty(process, "platform", { value: "linux" });
+ vi.stubEnv("XDG_SESSION_TYPE", "x11");
+ mocks.sources.mockResolvedValue([{ ...source, display_id: "1" }]);
+ });
+ it("validates X11 windows using live sources without geometry helpers", async () => {
+ expect(await validateCaptureSource(source)).toMatchObject({
+ id: source.id,
+ name: source.name,
+ windowTitle: source.windowTitle,
+ display_id: "1",
+ sourceType: "window",
+ });
+ expect(mocks.windows).not.toHaveBeenCalled();
+ expect(mocks.sources).toHaveBeenCalledWith(
+ { types: ["window"], thumbnailSize: { width: 0, height: 0 } },
+ { strict: true },
+ );
+ });
+ it("rejects missing and recycled X11 windows without substitution", async () => {
+ mocks.sources.mockResolvedValue([{ id: source.id, name: "Different document" }]);
+ expect(await validateCaptureSource(source)).toBeNull();
+ mocks.sources.mockResolvedValue([{ ...source, id: "window:102:0" }]);
+ expect(await validateCaptureSource(source)).toBeNull();
+ });
+ for (const saved of [null, { platform: "linux", source }]) {
+ it(`prepares Wayland recording without opening a startup portal (${saved ? "saved X11 window" : "fresh session"})`, async () => {
+ vi.stubEnv("XDG_SESSION_TYPE", "wayland");
+ mocks.read.mockReturnValue(saved);
+ expect(await restoreLastCaptureSource()).toEqual({
+ id: "screen:linux-portal",
+ name: "System picker",
+ sourceType: "screen",
+ });
+ expect(mocks.read).not.toHaveBeenCalled();
+ expect(mocks.sources).not.toHaveBeenCalled();
+ expect(mocks.windows).not.toHaveBeenCalled();
+ });
+ }
+ it("rejects old X11 IDs on Wayland without enumerating portal sources", async () => {
+ vi.stubEnv("XDG_SESSION_TYPE", "wayland");
+ expect(await validateCaptureSource(source)).toBeNull();
+ expect(
+ await validateCaptureSource({ id: "screen:1:0", name: "Screen", display_id: "1" }),
+ ).toBeNull();
+ expect(mocks.sources).not.toHaveBeenCalled();
+ expect(mocks.windows).not.toHaveBeenCalled();
+ });
+});
diff --git a/electron/ipc/captureSelection.ts b/electron/ipc/captureSelection.ts
index 6a7a24d3..4b459660 100644
--- a/electron/ipc/captureSelection.ts
+++ b/electron/ipc/captureSelection.ts
@@ -26,6 +26,27 @@ export async function validateCaptureSource(candidate: unknown): Promise<Selecte
return process.platform === "linux" && isLikelyLinuxWaylandSession(process.env)
? { id: source.id, name: "System picker", sourceType: "screen" }
: null;
+ if (process.platform === "linux" && isLikelyLinuxWaylandSession(process.env)) return null;
+ if (source.id.startsWith("window:") && process.platform === "linux") {
+ const windows = await getDesktopSources(
+ { types: ["window"], thumbnailSize: { width: 0, height: 0 } },
+ { strict: true },
+ );
+ const match = windows.find(
+ (entry) =>
+ entry.id === source.id &&
+ (entry.windowTitle ?? entry.name) === (source.windowTitle ?? source.name),
+ );
+ return match
+ ? {
+ id: match.id,
+ name: match.name,
+ windowTitle: match.windowTitle ?? match.name,
+ display_id: match.display_id,
+ sourceType: "window",
+ }
+ : null;
+ }
if (source.id.startsWith("window:")) {
const windows = await listCapturePickerWindows();
const match = windows.find(
@@ -95,6 +116,15 @@ export function rememberCaptureSource(source: SelectedSource) {
let restoring: Promise<SelectedSource | null> | null = null;
export async function restoreLastCaptureSource(): Promise<SelectedSource | null> {
+ if (process.platform === "linux" && isLikelyLinuxWaylandSession(process.env)) {
+ const source: SelectedSource = {
+ id: LINUX_PORTAL_SCREEN_SOURCE_ID,
+ name: "System picker",
+ sourceType: "screen",
+ };
+ setSelectedSource(source);
+ return source;
+ }
if (selectedSource) return selectedSource;
if (!restoring)
restoring = (async () => {
diff --git a/electron/ipc/cursor/bounds.test.ts b/electron/ipc/cursor/bounds.test.ts
new file mode 100644
index 00000000..4e2da061
--- /dev/null
+++ b/electron/ipc/cursor/bounds.test.ts
@@ -0,0 +1,29 @@
+import { expect, it, vi } from "vitest";
+const exec = vi.hoisted(() => vi.fn());
+vi.mock("node:child_process", () => ({ execFile: exec }));
+vi.mock("node:util", () => ({ promisify: () => exec }));
+vi.mock("../paths/binaries", () => ({ ensureNativeWindowListBinary: vi.fn() }));
+vi.mock("../state", () => ({}));
+vi.mock("../utils", () => ({
+ parseWindowId: (id: string) =>
+ id.startsWith("window:") ? Number(id.split(":")[1]) || null : null,
+}));
+vi.mock("../windowsWindowControl", () => ({ resolveWindowsWindowBounds: vi.fn() }));
+import { resolveLinuxWindowBounds } from "./bounds";
+
+it("does not track a different same-title X11 window after the selected window disappears", async () => {
+ exec.mockReset().mockRejectedValue(new Error("No such window"));
+ expect(await resolveLinuxWindowBounds({ id: "window:101:0", name: "Document" })).toBeNull();
+ expect(exec).toHaveBeenCalledExactlyOnceWith("xwininfo", ["-id", "101"], { timeout: 1500 });
+});
+it("returns live X11 bounds by ID", async () => {
+ exec.mockReset().mockResolvedValue({
+ stdout: "Absolute upper-left X: -100\nAbsolute upper-left Y: 50\nWidth: 640\nHeight: 480",
+ });
+ expect(await resolveLinuxWindowBounds({ id: "window:101:0", name: "Document" })).toEqual({
+ x: -100,
+ y: 50,
+ width: 640,
+ height: 480,
+ });
+});
diff --git a/electron/ipc/cursor/bounds.ts b/electron/ipc/cursor/bounds.ts
index 19311eb5..bb5da7a6 100644
--- a/electron/ipc/cursor/bounds.ts
+++ b/electron/ipc/cursor/bounds.ts
@@ -170,8 +170,10 @@ export async function resolveLinuxWindowBounds(
return bounds;
}
} catch {
- // fall back to title lookup below
+ return null;
}
+ // Do not track a different same-title window after the selected ID disappears.
+ return null;
}
const windowTitle =
diff --git a/electron/ipc/handlers.ts b/electron/ipc/handlers.ts
index 3208f8a2..c5c8667e 100644
--- a/electron/ipc/handlers.ts
+++ b/electron/ipc/handlers.ts
@@ -60,12 +60,12 @@ export function registerIpcHandlers(
getSourceSelectorWindow: () => BrowserWindow | null,
onRecordingStateChange?: (recording: boolean, sourceName: string) => void,
) {
- registerSourceHandlers({
+ const { pickSourceList } = registerSourceHandlers({
createEditorWindow,
createSourceSelectorWindow,
getSourceSelectorWindow,
});
- registerCapturePickerHandlers();
+ registerCapturePickerHandlers({ pickSourceList });
registerRecordingHandlers(onRecordingStateChange);
registerPermissionHandlers();
registerAnnouncementHandlers();
diff --git a/electron/ipc/register/capturePicker.test.ts b/electron/ipc/register/capturePicker.test.ts
index e00a15d4..3733e7b9 100644
--- a/electron/ipc/register/capturePicker.test.ts
+++ b/electron/ipc/register/capturePicker.test.ts
@@ -2,6 +2,7 @@ import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
const mocks = vi.hoisted(() => ({
handlers: new Map<string, (...args: unknown[]) => unknown>(),
list: vi.fn(),
+ pickSourceList: vi.fn(),
validate: vi.fn(),
remember: vi.fn(),
selected: vi.fn(),
@@ -67,7 +68,7 @@ beforeEach(() => {
Object.defineProperty(process, "platform", { value: "darwin" });
mocks.list.mockResolvedValue([]);
mocks.validate.mockImplementation(async (source) => source);
- registerCapturePickerHandlers();
+ registerCapturePickerHandlers({ pickSourceList: mocks.pickSourceList });
});
const call = (name: string, sender: object, input?: unknown) =>
mocks.handlers.get(name)!({ sender }, input);
@@ -192,3 +193,32 @@ it("does not open overlays if recording starts while listing windows", async ()
});
expect(mocks.create).not.toHaveBeenCalled();
});
+
+it("keeps X11 on the source list and coalesces concurrent opens", async () => {
+ Object.defineProperty(process, "platform", { value: "linux" });
+ vi.stubEnv("XDG_SESSION_TYPE", "x11");
+ let finish!: (result: unknown) => void;
+ mocks.pickSourceList.mockReturnValue(
+ new Promise((resolve) => {
+ finish = resolve;
+ }),
+ );
+ const first = call("pick-capture-target", mocks.outsider);
+ const second = call("pick-capture-target", mocks.outsider);
+ expect(mocks.pickSourceList).toHaveBeenCalledOnce();
+ expect(mocks.list).not.toHaveBeenCalled();
+ expect(mocks.create).not.toHaveBeenCalled();
+ finish({ success: false, canceled: true });
+ expect(await first).toEqual({ success: false, canceled: true });
+ expect(await second).toEqual({ success: false, canceled: true });
+});
+it("keeps the X11 source list closed during recording", async () => {
+ Object.defineProperty(process, "platform", { value: "linux" });
+ vi.stubEnv("XDG_SESSION_TYPE", "x11");
+ mocks.recording = true;
+ expect(await call("pick-capture-target", mocks.outsider)).toEqual({
+ success: false,
+ canceled: true,
+ });
+ expect(mocks.pickSourceList).not.toHaveBeenCalled();
+});
diff --git a/electron/ipc/register/capturePicker.ts b/electron/ipc/register/capturePicker.ts
index ab2b1be4..8c26ae39 100644
--- a/electron/ipc/register/capturePicker.ts
+++ b/electron/ipc/register/capturePicker.ts
@@ -1,6 +1,7 @@
import { rememberCaptureSource, validateCaptureSource } from "../captureSelection";
import { listCapturePickerWindows } from "../capturePickerSources";
import { BrowserWindow, ipcMain } from "electron";
+import type { SourceListPickResult } from "../../sourceListPicker";
import {
closeCapturePickerWindows,
createCapturePickerWindows,
@@ -52,7 +53,11 @@ async function createScreenSource(displayId: number): Promise<SelectedSource | n
* the cursor, a click picks that window or the whole screen, and a drag draws an
* area. The pick becomes the selected source.
*/
-export function registerCapturePickerHandlers() {
+export function registerCapturePickerHandlers({
+ pickSourceList,
+}: {
+ pickSourceList: () => Promise<SourceListPickResult>;
+}) {
let resolvePendingPick: ((pick: CapturePick | null) => void) | null = null;
let pickableWindows: Promise<CapturePickerWindow[]> = Promise.resolve([]);
@@ -83,6 +88,8 @@ export function registerCapturePickerHandlers() {
};
}
+ if (process.platform === "linux") return pickSourceList();
+
finishPick(null);
// List windows before the overlays cover them.
pickableWindows = Promise.resolve(await listCapturePickerWindows());
diff --git a/electron/ipc/register/sourceMapping.test.ts b/electron/ipc/register/sourceMapping.test.ts
index 84351a50..ce7ff4fa 100644
--- a/electron/ipc/register/sourceMapping.test.ts
+++ b/electron/ipc/register/sourceMapping.test.ts
@@ -1,6 +1,10 @@
-import { describe, expect, it } from "vitest";
+import { describe, expect, it, vi } from "vitest";
-import { getScreenSourceIdForDisplay, LINUX_PORTAL_SCREEN_SOURCE_ID } from "./sourceMapping";
+import {
+ getScreenSourceIdForDisplay,
+ LINUX_PORTAL_SCREEN_SOURCE_ID,
+ resolveDisplayMediaSource,
+} from "./sourceMapping";
describe("getScreenSourceIdForDisplay", () => {
it("keeps the live Electron screen source when one is available", () => {
@@ -45,3 +49,59 @@ describe("getScreenSourceIdForDisplay", () => {
).toBe("screen:fallback:42");
});
});
+
+describe("display media source resolution", () => {
+ for (const selectedSourceId of [null, "window:101:0", LINUX_PORTAL_SCREEN_SOURCE_ID]) {
+ it(`opens Wayland through Chromium without pre-enumeration (${selectedSourceId})`, async () => {
+ const getSources = vi.fn();
+ expect(
+ await resolveDisplayMediaSource({
+ platform: "linux",
+ env: { XDG_SESSION_TYPE: "wayland" },
+ selectedSourceId,
+ getSources,
+ }),
+ ).toEqual({ id: "screen:0:0", name: "Entire screen" });
+ expect(getSources).not.toHaveBeenCalled();
+ });
+ }
+ it("returns only the requested X11 source and excludes preview pixels", async () => {
+ const getSources = vi.fn().mockResolvedValue([
+ { id: "screen:1:0", name: "Screen" },
+ { id: "window:101:0", name: "Document", thumbnail: "pixels" },
+ ]);
+ expect(
+ await resolveDisplayMediaSource({
+ platform: "linux",
+ env: { XDG_SESSION_TYPE: "x11" },
+ selectedSourceId: "window:101:0",
+ getSources,
+ }),
+ ).toEqual({ id: "window:101:0", name: "Document" });
+ });
+ it("does not record a different source if the selected window closes", async () => {
+ const getSources = vi.fn().mockResolvedValue([{ id: "screen:1:0", name: "Screen" }]);
+ expect(
+ await resolveDisplayMediaSource({
+ platform: "linux",
+ env: { XDG_SESSION_TYPE: "x11" },
+ selectedSourceId: "window:101:0",
+ getSources,
+ }),
+ ).toBeNull();
+ });
+ for (const selectedSourceId of [null, LINUX_PORTAL_SCREEN_SOURCE_ID]) {
+ it(`does not open a portal or pick a default on X11 (${selectedSourceId})`, async () => {
+ const getSources = vi.fn();
+ expect(
+ await resolveDisplayMediaSource({
+ platform: "linux",
+ env: { XDG_SESSION_TYPE: "x11", WAYLAND_DISPLAY: "wayland-0" },
+ selectedSourceId,
+ getSources,
+ }),
+ ).toBeNull();
+ expect(getSources).not.toHaveBeenCalled();
+ });
+ }
+});
diff --git a/electron/ipc/register/sourceMapping.ts b/electron/ipc/register/sourceMapping.ts
index 8b13501a..9ae9372b 100644
--- a/electron/ipc/register/sourceMapping.ts
+++ b/electron/ipc/register/sourceMapping.ts
@@ -33,3 +33,24 @@ export function getScreenSourceIdForDisplay({
return `screen:fallback:${displayId}`;
}
+
+export async function resolveDisplayMediaSource({
+ platform,
+ env,
+ selectedSourceId,
+ getSources,
+}: {
+ platform: string;
+ env: NodeJS.ProcessEnv;
+ selectedSourceId: string | null | undefined;
+ getSources: () => Promise<Array<{ id: string; name: string }>>;
+}): Promise<{ id: string; name: string } | null> {
+ if (platform === "linux" && isLikelyLinuxWaylandSession(env)) {
+ // Chromium opens the portal once when it resolves this source. Enumerating first opens it twice.
+ return { id: "screen:0:0", name: "Entire screen" };
+ }
+ if (!selectedSourceId || selectedSourceId === LINUX_PORTAL_SCREEN_SOURCE_ID) return null;
+ const source = (await getSources()).find((source) => source.id === selectedSourceId);
+ // A vanished source must never silently become a different window or the whole screen.
+ return source ? { id: source.id, name: source.name } : null;
+}
diff --git a/electron/ipc/register/sources.test.ts b/electron/ipc/register/sources.test.ts
new file mode 100644
index 00000000..08fcb4d2
--- /dev/null
+++ b/electron/ipc/register/sources.test.ts
@@ -0,0 +1,154 @@
+import { EventEmitter } from "node:events";
+import type { BrowserWindow } from "electron";
+import { afterEach, beforeEach, expect, it, vi } from "vitest";
+import type { SelectedSource } from "../types";
+const mocks = vi.hoisted(() => ({
+ handlers: new Map<string, (...args: unknown[]) => unknown>(),
+ sources: vi.fn(),
+ validate: vi.fn(),
+ remember: vi.fn(),
+ recording: false,
+ selected: null as SelectedSource | null,
+ exec: vi.fn(),
+}));
+vi.mock("electron", () => ({
+ ipcMain: {
+ handle: (name: string, handler: (...args: unknown[]) => unknown) =>
+ mocks.handlers.set(name, handler),
+ },
+ app: { getName: () => "Recordly", focus: vi.fn() },
+ BrowserWindow: { getAllWindows: () => [] },
+ desktopCapturer: { getSources: mocks.sources },
+}));
+vi.mock("node:child_process", () => ({ execFile: mocks.exec }));
+vi.mock("node:util", () => ({ promisify: () => mocks.exec }));
+vi.mock("../../appSettingsStore", () => ({ writeAppSetting: vi.fn() }));
+vi.mock("../../windows", () => ({}));
+vi.mock("../constants", () => ({ ALLOW_RECORDLY_WINDOW_CAPTURE: false }));
+vi.mock("../cursor/bounds", () => ({ stopWindowBoundsCapture: vi.fn() }));
+vi.mock("../recording/ffmpeg", () => ({}));
+vi.mock("../windowsWindowControl", () => ({}));
+vi.mock("../captureSelection", () => ({
+ validateCaptureSource: mocks.validate,
+ rememberCaptureSource: mocks.remember,
+ restoreLastCaptureSource: vi.fn(),
+}));
+vi.mock("../state", () => ({
+ get isCursorCaptureActive() {
+ return mocks.recording;
+ },
+ get selectedSource() {
+ return mocks.selected;
+ },
+ setSelectedSource: (source: SelectedSource) => {
+ mocks.selected = source;
+ },
+}));
+vi.mock("../utils", () => ({
+ parseWindowId: (id: string) => Number(id.split(":")[1]) || null,
+ getScreen: () => ({
+ getAllDisplays: () => [{ id: 1, bounds: { x: 0, y: 0 } }],
+ getPrimaryDisplay: () => ({ id: 1 }),
+ }),
+}));
+import { getDesktopSources, registerSourceHandlers } from "./sources";
+const platform = process.platform;
+beforeEach(() => {
+ vi.clearAllMocks();
+ mocks.handlers.clear();
+ mocks.recording = false;
+ mocks.selected = null;
+ mocks.validate.mockImplementation(async (source) => source);
+ mocks.exec.mockRejectedValue(new Error("wmctrl is not installed"));
+ Object.defineProperty(process, "platform", { value: "linux" });
+ vi.stubEnv("XDG_SESSION_TYPE", "x11");
+});
+afterEach(() => {
+ Object.defineProperty(process, "platform", { value: platform });
+ vi.unstubAllEnvs();
+});
+function pickerFixture() {
+ let current: BrowserWindow | null = null;
+ const win = Object.assign(new EventEmitter(), {
+ webContents: {},
+ close: () => {
+ current = null;
+ win.emit("closed");
+ },
+ });
+ const create = vi.fn(() => {
+ current = win as unknown as BrowserWindow;
+ return current;
+ });
+ const { pickSourceList } = registerSourceHandlers({
+ createEditorWindow: vi.fn(),
+ createSourceSelectorWindow: create,
+ getSourceSelectorWindow: () => current,
+ });
+ return {
+ win,
+ create,
+ pickSourceList,
+ select: (source: SelectedSource) =>
+ mocks.handlers.get("select-source")!({ sender: win.webContents }, source),
+ };
+}
+it("never enumerates or previews Wayland sources before recording", async () => {
+ vi.stubEnv("XDG_SESSION_TYPE", "wayland");
+ expect(await getDesktopSources({ types: ["screen", "window"] })).toEqual([
+ { id: "screen:linux-portal", name: "System picker", sourceType: "screen" },
+ ]);
+ expect(await getDesktopSources({ types: ["window"] })).toEqual([]);
+ expect(mocks.sources).not.toHaveBeenCalled();
+});
+it("completes X11 selection even without optional window raising tools", async () => {
+ const picker = pickerFixture();
+ const pending = picker.pickSourceList();
+ const source = { id: "window:101:0", name: "Document" };
+ expect(await picker.select(source)).toEqual(source);
+ expect(await pending).toEqual({ success: true, source });
+ expect(mocks.remember).toHaveBeenCalledWith(source);
+});
+it("leaves the source list pending when a selected window no longer exists", async () => {
+ const picker = pickerFixture();
+ const pending = picker.pickSourceList();
+ mocks.validate.mockResolvedValue(null);
+ await expect(picker.select({ id: "window:101:0", name: "Document" })).rejects.toThrow(
+ "no longer available",
+ );
+ expect(mocks.selected).toBeNull();
+ expect(mocks.remember).not.toHaveBeenCalled();
+ picker.win.close();
+ expect(await pending).toEqual({ success: false, canceled: true });
+});
+it("does not apply a selection after the source list is dismissed during validation", async () => {
+ const picker = pickerFixture();
+ const pending = picker.pickSourceList();
+ let finish!: (value: SelectedSource) => void;
+ mocks.validate.mockReturnValue(
+ new Promise((resolve) => {
+ finish = resolve;
+ }),
+ );
+ const source = { id: "screen:1:0", name: "Screen" };
+ const selection = picker.select(source);
+ picker.win.close();
+ finish(source);
+ await selection;
+ expect(await pending).toEqual({ success: false, canceled: true });
+ expect(mocks.selected).toBeNull();
+ expect(mocks.remember).not.toHaveBeenCalled();
+});
+it("does not change sources if recording starts during validation", async () => {
+ const picker = pickerFixture();
+ const pending = picker.pickSourceList();
+ mocks.validate.mockImplementation(async (source) => {
+ mocks.recording = true;
+ return source;
+ });
+ await picker.select({ id: "screen:1:0", name: "Screen" });
+ expect(mocks.selected).toBeNull();
+ expect(mocks.remember).not.toHaveBeenCalled();
+ picker.win.close();
+ expect(await pending).toEqual({ success: false, canceled: true });
+});
diff --git a/electron/ipc/register/sources.ts b/electron/ipc/register/sources.ts
index 6f52a208..5a2f704b 100644
--- a/electron/ipc/register/sources.ts
+++ b/electron/ipc/register/sources.ts
@@ -1,5 +1,10 @@
+import { createSourceListPicker } from "../../sourceListPicker";
import { writeAppSetting } from "../../appSettingsStore";
-import { restoreLastCaptureSource } from "../captureSelection";
+import {
+ rememberCaptureSource,
+ restoreLastCaptureSource,
+ validateCaptureSource,
+} from "../captureSelection";
import { createRecordingEditorNavigation } from "../../recordingEditorNavigation";
import { execFile } from "node:child_process";
import { promisify } from "node:util";
@@ -23,7 +28,11 @@ import type { SelectedSource, WindowBounds } from "../types";
import { getSourceArea } from "../sourceArea";
import { getScreen, parseWindowId } from "../utils";
import { bringWindowsWindowForward, resolveWindowsWindowBounds } from "../windowsWindowControl";
-import { getScreenSourceIdForDisplay } from "./sourceMapping";
+import {
+ getScreenSourceIdForDisplay,
+ isLikelyLinuxWaylandSession,
+ LINUX_PORTAL_SCREEN_SOURCE_ID,
+} from "./sourceMapping";
const execFileAsync = promisify(execFile);
const SOURCE_LIST_CACHE_TTL_MS = 1200;
@@ -123,6 +132,11 @@ export async function getDesktopSources(
opts?: Electron.SourcesOptions,
options?: { strict?: boolean },
): Promise<SelectedSource[]> {
+ if (process.platform === "linux" && isLikelyLinuxWaylandSession(process.env)) {
+ return opts?.types && !opts.types.includes("screen")
+ ? []
+ : [{ id: LINUX_PORTAL_SCREEN_SOURCE_ID, name: "System picker", sourceType: "screen" }];
+ }
const cacheKey = JSON.stringify({
types: opts?.types,
thumbnailSize: opts?.thumbnailSize,
@@ -398,16 +412,32 @@ export function registerSourceHandlers({
getSourceSelectorWindow: () => BrowserWindow | null;
}) {
const recordingNavigation = createRecordingEditorNavigation(createEditorWindow);
+ const sourceListPicker = createSourceListPicker(
+ () => getSourceSelectorWindow() ?? createSourceSelectorWindow(),
+ );
ipcMain.handle("get-sources", (_, opts) => getDesktopSources(opts));
- ipcMain.handle("select-source", async (_, source: SelectedSource) => {
+ ipcMain.handle("select-source", async (event, source: SelectedSource) => {
if (isCursorCaptureActive) return selectedSource;
+ const fromSelector = getSourceSelectorWindow()?.webContents === event.sender;
+ if (process.platform === "linux") {
+ const validated = await validateCaptureSource(source);
+ if (!validated)
+ throw new Error(
+ "That window or screen is no longer available. Refresh the source list.",
+ );
+ source = validated;
+ }
if (source.id?.startsWith("window:")) {
await bringSelectedWindowForward(source);
}
if (isCursorCaptureActive) return selectedSource;
+ if (fromSelector && getSourceSelectorWindow()?.webContents !== event.sender)
+ return selectedSource;
setSelectedSource(source);
+ rememberCaptureSource(source);
broadcastSelectedSourceChange();
+ if (sourceListPicker.isSender(event.sender)) sourceListPicker.complete(source);
stopWindowBoundsCapture();
const sourceSelectorWin = getSourceSelectorWindow();
if (sourceSelectorWin) {
@@ -605,8 +635,13 @@ body{background:transparent;overflow:hidden;width:100vw;height:100vh}
return restoreLastCaptureSource();
});
- ipcMain.handle("open-source-selector", () => {
+ ipcMain.handle("open-source-selector", async () => {
if (isCursorCaptureActive) return;
+ if (process.platform === "linux" && isLikelyLinuxWaylandSession(process.env)) {
+ await restoreLastCaptureSource();
+ broadcastSelectedSourceChange();
+ return;
+ }
const sourceSelectorWin = getSourceSelectorWindow();
if (sourceSelectorWin) {
sourceSelectorWin.focus();
@@ -647,4 +682,5 @@ body{background:transparent;overflow:hidden;width:100vw;height:100vh}
}
recordingNavigation.open();
});
+ return { pickSourceList: () => sourceListPicker.open() };
}
diff --git a/electron/main.ts b/electron/main.ts
index 70e45d66..076aa42d 100644
--- a/electron/main.ts
+++ b/electron/main.ts
@@ -1,3 +1,4 @@
+import { resolveDisplayMediaSource } from "./ipc/register/sourceMapping";
import { createSaveBeforeCloseController } from "./saveBeforeClose";
import { clearRecordingTrashUndo } from "./ipc/recording/library";
import fs from "node:fs/promises";
@@ -1115,36 +1116,17 @@ app.whenReady().then(async () => {
// resolves, before recording-state-changed is emitted.
beginHudCaptureProtection();
- const sourceId = getSelectedSourceId();
- // On Linux/Wayland, calling desktopCapturer.getSources() itself
- // invokes the xdg-desktop-portal picker. If we then return one of
- // those sources, Chromium triggers a SECOND portal because the
- // pre-enumerated source IDs are stale on Wayland. To collapse this
- // into a single portal invocation, when the Linux portal sentinel
- // is set we skip getSources entirely and hand back a synthetic
- // source id; Chromium then opens the portal once to actually
- // resolve the capture.
- // Default to the sentinel on Linux when no source has been
- // pre-selected (e.g. fresh session where the renderer skipped the
- // source picker entirely). This avoids calling getSources() which
- // would itself trigger an extra portal dialog.
- const isLinuxPortalSentinel =
- process.platform === "linux" && (sourceId === "screen:linux-portal" || !sourceId);
- if (isLinuxPortalSentinel) {
- callback({ video: { id: "screen:0:0", name: "Entire screen" } });
- return;
- }
- const sources = await desktopCapturer.getSources({ types: ["screen", "window"] });
- const source = sourceId
- ? (sources.find((s) => s.id === sourceId) ?? sources[0])
- : sources[0];
- if (source) {
- callback({
- video: { id: source.id, name: source.name },
- });
- } else {
- callback({});
- }
+ const video = await resolveDisplayMediaSource({
+ platform: process.platform,
+ env: process.env,
+ selectedSourceId: getSelectedSourceId(),
+ getSources: () =>
+ desktopCapturer.getSources({
+ types: ["screen", "window"],
+ thumbnailSize: { width: 0, height: 0 },
+ }),
+ });
+ callback(video ? { video } : {});
} catch (error) {
console.error("setDisplayMediaRequestHandler error:", error);
callback({});
diff --git a/electron/sourceListPicker.test.ts b/electron/sourceListPicker.test.ts
new file mode 100644
index 00000000..d6dcfddc
--- /dev/null
+++ b/electron/sourceListPicker.test.ts
@@ -0,0 +1,35 @@
+import { EventEmitter } from "node:events";
+import type { BrowserWindow, WebContents } from "electron";
+import { describe, expect, it, vi } from "vitest";
+import { createSourceListPicker } from "./sourceListPicker";
+
+function fixture() {
+ const win = Object.assign(new EventEmitter(), { webContents: {} as WebContents });
+ const create = vi.fn(() => win as unknown as BrowserWindow);
+ return { win, create, picker: createSourceListPicker(create) };
+}
+describe("source list picker lifecycle", () => {
+ it("coalesces opens, accepts its own sender, and waits for a selection", async () => {
+ const { win, create, picker } = fixture();
+ const first = picker.open();
+ expect(picker.open()).toBe(first);
+ expect(create).toHaveBeenCalledOnce();
+ expect(picker.isSender(win.webContents)).toBe(true);
+ expect(picker.isSender({} as WebContents)).toBe(false);
+ const source = { id: "window:101:0", name: "Document" };
+ picker.complete(source);
+ win.emit("closed");
+ expect(await first).toEqual({ success: true, source });
+ expect(picker.isSender(win.webContents)).toBe(false);
+ });
+ it("resolves dismissal and allows another picker afterwards", async () => {
+ const { win, create, picker } = fixture();
+ const first = picker.open();
+ win.emit("closed");
+ expect(await first).toEqual({ success: false, canceled: true });
+ const second = picker.open();
+ expect(create).toHaveBeenCalledTimes(2);
+ win.emit("closed");
+ expect(await second).toEqual({ success: false, canceled: true });
+ });
+});
diff --git a/electron/sourceListPicker.ts b/electron/sourceListPicker.ts
new file mode 100644
index 00000000..29e74781
--- /dev/null
+++ b/electron/sourceListPicker.ts
@@ -0,0 +1,38 @@
+import type { BrowserWindow, WebContents } from "electron";
+import type { SelectedSource } from "./ipc/types";
+
+export type SourceListPickResult = {
+ success: boolean;
+ canceled?: boolean;
+ source?: SelectedSource;
+};
+
+/** Keeps the existing Linux source-list window open until selection or dismissal. */
+export function createSourceListPicker(createWindow: () => BrowserWindow) {
+ let activeWindow: BrowserWindow | null = null;
+ let pending: Promise<SourceListPickResult> | null = null;
+ let finish: ((result: SourceListPickResult) => void) | null = null;
+ return {
+ open() {
+ if (pending) return pending;
+ activeWindow = createWindow();
+ pending = new Promise<SourceListPickResult>((resolve) => {
+ finish = resolve;
+ });
+ activeWindow.once("closed", () => {
+ finish?.({ success: false, canceled: true });
+ finish = null;
+ pending = null;
+ activeWindow = null;
+ });
+ return pending;
+ },
+ isSender(sender: WebContents) {
+ return activeWindow?.webContents === sender;
+ },
+ complete(source: SelectedSource) {
+ finish?.({ success: true, source });
+ finish = null;
+ },
+ };
+}
diff --git a/src/components/launch/SourceSelector.tsx b/src/components/launch/SourceSelector.tsx
index ad7f100b..c34b6501 100644
--- a/src/components/launch/SourceSelector.tsx
+++ b/src/components/launch/SourceSelector.tsx
@@ -1,7 +1,9 @@
-import { useEffect, useRef } from "react";
+import { useCallback, useEffect, useRef, useState } from "react";
+import { Button } from "@/components/ui/button";
import { toast } from "@/components/ui/toast";
+import styles from "./LaunchWindow.module.css";
-export function SourceSelector() {
+function OverlaySourceSelector() {
const started = useRef(false);
useEffect(() => {
if (started.current) return;
@@ -19,3 +21,146 @@ export function SourceSelector() {
}, []);
return null;
}
+
+function LinuxSourceList() {
+ const [sources, setSources] = useState<ProcessedDesktopSource[]>([]);
+ const [loading, setLoading] = useState(true);
+ const [selecting, setSelecting] = useState(false);
+ const [error, setError] = useState<string>();
+ const refresh = useCallback(async () => {
+ setLoading(true);
+ setError(undefined);
+ try {
+ setSources(
+ await window.electronAPI.getSources({
+ types: ["screen", "window"],
+ thumbnailSize: { width: 160, height: 90 },
+ fetchWindowIcons: false,
+ }),
+ );
+ } catch {
+ setError("Could not load recording sources. Try refreshing the list.");
+ } finally {
+ setLoading(false);
+ }
+ }, []);
+ useEffect(() => {
+ void refresh();
+ }, [refresh]);
+ useEffect(() => {
+ const key = (event: KeyboardEvent) => {
+ if (event.key === "Escape") window.close();
+ };
+ window.addEventListener("keydown", key);
+ const unsubscribe = window.electronAPI.onRecordingStateChanged((state) => {
+ if (state.recording) window.close();
+ });
+ return () => {
+ window.removeEventListener("keydown", key);
+ unsubscribe();
+ };
+ }, []);
+ const select = async (source: ProcessedDesktopSource) => {
+ if (selecting) return;
+ setSelecting(true);
+ setError(undefined);
+ try {
+ const selected = await window.electronAPI.selectSource(source);
+ if (selected?.id !== source.id)
+ throw new Error("Source selection is unavailable during recording.");
+ } catch (error) {
+ setError(error instanceof Error ? error.message : "Could not select that source.");
+ } finally {
+ setSelecting(false);
+ }
+ };
+ return (
+ <div className="flex h-screen flex-col overflow-hidden rounded-2xl border border-separator bg-surface text-foreground">
+ <header className="flex shrink-0 items-center justify-between border-b border-separator p-4">
+ <div className={styles.electronDrag}>
+ <h1 className="text-lg font-semibold">Choose recording source</h1>
+ <p className="mt-1 text-xs text-muted">
+ Choose a screen or window. Recording starts from the recording controls.
+ </p>
+ </div>
+ <Button variant="ghost" onClick={() => window.close()}>
+ Cancel
+ </Button>
+ </header>
+ <div className="min-h-0 flex-1 overflow-y-auto p-3">
+ {error && (
+ <p
+ role="alert"
+ className="mb-3 rounded-lg bg-danger/10 p-3 text-sm text-danger"
+ >
+ {error}
+ </p>
+ )}
+ {loading ? (
+ <p role="status" className="py-6 text-center text-sm text-muted">
+ Loading sources…
+ </p>
+ ) : sources.length === 0 ? (
+ <p className="py-6 text-center text-sm text-muted">
+ No recording sources found.
+ </p>
+ ) : (
+ ["screen", "window"].map((kind) => {
+ const entries = sources.filter((source) =>
+ source.id.startsWith(`${kind}:`),
+ );
+ return (
+ entries.length > 0 && (
+ <section key={kind} className="mb-3">
+ <h2 className="px-2 py-2 text-xs font-semibold text-muted">
+ {kind === "screen" ? "Screens" : "Windows"}
+ </h2>
+ <div className="space-y-1">
+ {entries.map((source) => (
+ <Button
+ key={source.id}
+ variant="ghost"
+ disabled={selecting}
+ className="h-auto w-full justify-start gap-3 rounded-xl px-3 py-2 text-left"
+ onClick={() => void select(source)}
+ >
+ {source.thumbnail && (
+ <img
+ src={source.thumbnail}
+ alt=""
+ className="h-12 w-20 shrink-0 rounded-lg object-cover"
+ />
+ )}
+ <span className="min-w-0 truncate">
+ {source.name}
+ </span>
+ </Button>
+ ))}
+ </div>
+ </section>
+ )
+ );
+ })
+ )}
+ </div>
+ <footer className="flex shrink-0 justify-end border-t border-separator p-3">
+ <Button
+ variant="ghost"
+ disabled={loading || selecting}
+ onClick={() => void refresh()}
+ >
+ Refresh
+ </Button>
+ </footer>
+ </div>
+ );
+}
+
+export function SourceSelector() {
+ const [platform, setPlatform] = useState<string>();
+ useEffect(() => {
+ void window.electronAPI.getPlatform().then(setPlatform);
+ }, []);
+ if (!platform) return null;
+ return platform === "linux" ? <LinuxSourceList /> : <OverlaySourceSelector />;
+}
diff --git a/src/hooks/browserScreenCapture.test.ts b/src/hooks/browserScreenCapture.test.ts
new file mode 100644
index 00000000..955a2c5b
--- /dev/null
+++ b/src/hooks/browserScreenCapture.test.ts
@@ -0,0 +1,71 @@
+import { describe, expect, it, vi } from "vitest";
+import { acquireBrowserScreenCapture } from "./browserScreenCapture";
+
+describe("browser screen capture fallback", () => {
+ for (const name of ["NotAllowedError", "AbortError"]) {
+ it(`does not reopen a dismissed Wayland portal (${name})`, async () => {
+ const error = new DOMException("Cancelled", name);
+ const request = vi.fn().mockRejectedValue(error);
+ const onAudioFallback = vi.fn();
+ await expect(
+ acquireBrowserScreenCapture({
+ request,
+ audio: true,
+ usePortal: true,
+ onAudioFallback,
+ }),
+ ).rejects.toBe(error);
+ expect(request).toHaveBeenCalledExactlyOnceWith(true);
+ expect(onAudioFallback).not.toHaveBeenCalled();
+ });
+ }
+ it("retries without audio when audio capture is unsupported", async () => {
+ const stream = {} as MediaStream;
+ const request = vi
+ .fn()
+ .mockRejectedValueOnce(new DOMException("Audio unavailable", "NotSupportedError"))
+ .mockResolvedValueOnce(stream);
+ const onAudioFallback = vi.fn();
+ expect(
+ await acquireBrowserScreenCapture({
+ request,
+ audio: true,
+ usePortal: true,
+ onAudioFallback,
+ }),
+ ).toBe(stream);
+ expect(request.mock.calls).toEqual([[true], [false]]);
+ expect(onAudioFallback).toHaveBeenCalledOnce();
+ });
+ it("does not retry video-only capture failures", async () => {
+ const error = new Error("Closed window");
+ const request = vi.fn().mockRejectedValue(error);
+ const onAudioFallback = vi.fn();
+ await expect(
+ acquireBrowserScreenCapture({
+ request,
+ audio: false,
+ usePortal: false,
+ onAudioFallback,
+ }),
+ ).rejects.toBe(error);
+ expect(request).toHaveBeenCalledOnce();
+ expect(onAudioFallback).not.toHaveBeenCalled();
+ });
+ it("preserves X11 audio fallback", async () => {
+ const stream = {} as MediaStream;
+ const request = vi
+ .fn()
+ .mockRejectedValueOnce(new DOMException("Audio unavailable", "NotAllowedError"))
+ .mockResolvedValueOnce(stream);
+ expect(
+ await acquireBrowserScreenCapture({
+ request,
+ audio: true,
+ usePortal: false,
+ onAudioFallback: vi.fn(),
+ }),
+ ).toBe(stream);
+ expect(request.mock.calls).toEqual([[true], [false]]);
+ });
+});
diff --git a/src/hooks/browserScreenCapture.ts b/src/hooks/browserScreenCapture.ts
new file mode 100644
index 00000000..42eaca61
--- /dev/null
+++ b/src/hooks/browserScreenCapture.ts
@@ -0,0 +1,26 @@
+/** A dismissed portal is terminal: audio fallback must not reopen the chooser. */
+export function isCapturePermissionDismissed(error: unknown): boolean {
+ return (
+ error instanceof Error && (error.name === "NotAllowedError" || error.name === "AbortError")
+ );
+}
+
+export async function acquireBrowserScreenCapture({
+ request,
+ audio,
+ usePortal,
+ onAudioFallback,
+}: {
+ request: (audio: boolean) => Promise<MediaStream>;
+ audio: boolean;
+ usePortal: boolean;
+ onAudioFallback: () => void;
+}): Promise<MediaStream> {
+ try {
+ return await request(audio);
+ } catch (error) {
+ if (!audio || (usePortal && isCapturePermissionDismissed(error))) throw error;
+ onAudioFallback();
+ return request(false);
+ }
+}
diff --git a/src/hooks/useScreenRecorder.ts b/src/hooks/useScreenRecorder.ts
index 2afb6921..8387fd8b 100644
--- a/src/hooks/useScreenRecorder.ts
+++ b/src/hooks/useScreenRecorder.ts
@@ -1,3 +1,4 @@
+import { acquireBrowserScreenCapture, isCapturePermissionDismissed } from "./browserScreenCapture";
import { fixWebmDuration } from "@fix-webm-duration/fix";
import { useCallback, useEffect, useRef, useState } from "react";
import { toast } from "@/components/ui/toast";
@@ -112,14 +113,6 @@ type MicrophoneSidecarOptions = {
chunkEvents?: MicrophoneFallbackChunkEvent[];
pauseIntervals?: MicrophoneFallbackPauseInterval[];
};
-const LINUX_PORTAL_SOURCE: ProcessedDesktopSource = {
- id: "screen:linux-portal",
- name: "Linux Portal",
- display_id: "",
- thumbnail: null,
- appIcon: null,
- sourceType: "screen",
-};
type DesktopCaptureMediaDevices = {
getUserMedia: (constraints: unknown) => Promise<MediaStream>;
@@ -1111,22 +1104,12 @@ export function useScreenRecorder(): UseScreenRecorderReturn {
const prepareRecordingStart = useCallback(async () => {
const platform = await window.electronAPI.getPlatform();
hideEditorOverlayCursorByDefault.current = false;
- const existingSource = await window.electronAPI.getSelectedSource();
- const selectedSource =
- existingSource ?? (platform === "linux" ? LINUX_PORTAL_SOURCE : null);
+ const selectedSource = await window.electronAPI.getSelectedSource();
if (!selectedSource) {
alert("Please select a source to record");
return null;
}
- if (!existingSource && selectedSource.id === "screen:linux-portal") {
- try {
- await window.electronAPI.selectSource(selectedSource);
- } catch (err) {
- console.warn("Failed to persist Linux portal sentinel source:", err);
- }
- }
-
const permissionsReady = await preparePermissions();
if (!permissionsReady) {
return null;
@@ -1654,6 +1637,7 @@ export function useScreenRecorder(): UseScreenRecorderReturn {
const startGeneration = recordingStartGeneration.current + 1;
recordingStartGeneration.current = startGeneration;
const startWasCancelled = () => recordingStartGeneration.current !== startGeneration;
+ let usingLinuxPortal = false;
let hudSourceSelectionActive = false;
const setHudSourceSelectionActive = (active: boolean) => {
@@ -1953,6 +1937,7 @@ export function useScreenRecorder(): UseScreenRecorderReturn {
let systemAudioIncluded = false;
const mediaDevices = navigator.mediaDevices as DesktopCaptureMediaDevices;
const useLinuxPortal = selectedSource.id === "screen:linux-portal";
+ usingLinuxPortal = useLinuxPortal;
const browserScreenVideoConstraints = {
mandatory: {
chromeMediaSource: CHROME_MEDIA_SOURCE,
@@ -1982,42 +1967,29 @@ export function useScreenRecorder(): UseScreenRecorderReturn {
surfaceSwitching: "exclude",
});
- if (systemAudioEnabled) {
- try {
- screenMediaStream = useLinuxPortal
- ? await acquireLinuxPortalStream(true)
- : await mediaDevices.getUserMedia({
- audio: {
- mandatory: {
- chromeMediaSource: CHROME_MEDIA_SOURCE,
- chromeMediaSourceId: browserCaptureSource.id,
- },
- },
+ screenMediaStream = await acquireBrowserScreenCapture({
+ audio: systemAudioEnabled,
+ usePortal: useLinuxPortal,
+ request: (audio) =>
+ useLinuxPortal
+ ? acquireLinuxPortalStream(audio)
+ : mediaDevices.getUserMedia({
+ audio: audio
+ ? {
+ mandatory: {
+ chromeMediaSource: CHROME_MEDIA_SOURCE,
+ chromeMediaSourceId: browserCaptureSource.id,
+ },
+ }
+ : false,
video: browserScreenVideoConstraints,
- });
- } catch (audioError) {
- console.warn(
- "System audio capture failed, falling back to video-only:",
- audioError,
- );
+ }),
+ onAudioFallback: () => {
alert(
"System audio is not available for this source. Recording will continue without system audio.",
);
- screenMediaStream = useLinuxPortal
- ? await acquireLinuxPortalStream(false)
- : await mediaDevices.getUserMedia({
- audio: false,
- video: browserScreenVideoConstraints,
- });
- }
- } else {
- screenMediaStream = useLinuxPortal
- ? await acquireLinuxPortalStream(false)
- : await mediaDevices.getUserMedia({
- audio: false,
- video: browserScreenVideoConstraints,
- });
- }
+ },
+ });
screenStream.current = screenMediaStream;
stream.current = new MediaStream();
@@ -2251,12 +2223,17 @@ export function useScreenRecorder(): UseScreenRecorderReturn {
console.warn("Failed to notify main process that recording started:", stateError);
}
} catch (error) {
- console.error("Failed to start recording:", error);
- alert(
- error instanceof Error
- ? `Failed to start recording: ${error.message}`
- : "Failed to start recording",
- );
+ if (
+ !startWasCancelled() &&
+ !(usingLinuxPortal && isCapturePermissionDismissed(error))
+ ) {
+ console.error("Failed to start recording:", error);
+ alert(
+ error instanceof Error
+ ? `Failed to start recording: ${error.message}`
+ : "Failed to start recording",
+ );
+ }
setRecording(false);
if (nativeScreenRecording.current) {
await discardActiveNativeCapture();
diff --git a/tests/ui/linux-capture.spec.ts b/tests/ui/linux-capture.spec.ts
new file mode 100644
index 00000000..0e685e70
--- /dev/null
+++ b/tests/ui/linux-capture.spec.ts
@@ -0,0 +1,132 @@
+import { expect, type Page, test } from "@playwright/test";
+import { installDesktopBridge, installDesktopBridgeOverrides } from "./bridge";
+
+async function openLinuxList(page: Page, stale = false) {
+ await page.setViewportSize({ width: 620, height: 420 });
+ await installDesktopBridge(page);
+ await installDesktopBridgeOverrides(
+ page,
+ (stale) => {
+ const sources = [
+ { id: "screen:1:0", name: "Screen 1 (Primary)", display_id: "1" },
+ { id: "window:101:0", name: "Document" },
+ ];
+ Object.defineProperty(window, "close", {
+ value: () => {
+ document.documentElement.dataset.closed = "true";
+ },
+ });
+ Object.assign(window.electronAPI, {
+ getPlatform: async () => "linux",
+ getSources: async () => {
+ const html = document.documentElement;
+ html.dataset.refreshes = String(Number(html.dataset.refreshes ?? 0) + 1);
+ return sources;
+ },
+ pickCaptureTarget: async () => {
+ throw new Error("Linux must use the list");
+ },
+ selectSource: async (source) => {
+ if (stale)
+ throw new Error(
+ "That window or screen is no longer available. Refresh the source list.",
+ );
+ document.documentElement.dataset.selected = source.id;
+ return source;
+ },
+ onRecordingStateChanged: (callback) => {
+ const listener = () => callback({ recording: true });
+ window.addEventListener("test-recording-start", listener);
+ return () => window.removeEventListener("test-recording-start", listener);
+ },
+ });
+ },
+ stale,
+ );
+ await page.goto("/?windowType=source-selector");
+ await expect(page.getByRole("heading", { name: "Choose recording source" })).toBeVisible({
+ timeout: 15000,
+ });
+ await expect(page.getByRole("button", { name: "Document", exact: true })).toBeVisible();
+}
+
+test("Linux lists screens and windows and selects the requested window", async ({
+ page,
+}, testInfo) => {
+ await openLinuxList(page);
+ await expect(page.getByRole("button", { name: "Refresh", exact: true })).toBeInViewport();
+ await page.screenshot({ path: testInfo.outputPath("linux-source-list.png") });
+ await expect(page.getByRole("heading", { name: "Screens", exact: true })).toBeVisible();
+ await expect(page.getByRole("heading", { name: "Windows", exact: true })).toBeVisible();
+ await page.getByRole("button", { name: "Document", exact: true }).click();
+ await expect(page.locator("html")).toHaveAttribute("data-selected", "window:101:0");
+});
+
+test("a closed Linux window leaves the picker open and allows refresh", async ({ page }) => {
+ await openLinuxList(page, true);
+ await page.getByRole("button", { name: "Document", exact: true }).click();
+ await expect(page.getByRole("alert")).toContainText("no longer available");
+ await expect(page.locator("html")).not.toHaveAttribute("data-closed");
+ await expect(page.locator("html")).not.toHaveAttribute("data-selected");
+ const before = Number(await page.locator("html").getAttribute("data-refreshes"));
+ await page.getByRole("button", { name: "Refresh", exact: true }).click();
+ await expect
+ .poll(async () => Number(await page.locator("html").getAttribute("data-refreshes")))
+ .toBeGreaterThan(before);
+ await expect(page.getByRole("alert")).toHaveCount(0);
+});
+
+for (const trigger of ["Escape", "Cancel", "recording"]) {
+ test(`Linux source list closes on ${trigger} without selecting a source`, async ({ page }) => {
+ await openLinuxList(page);
+ if (trigger === "Escape") await page.keyboard.press("Escape");
+ else if (trigger === "Cancel")
+ await page.getByRole("button", { name: "Cancel", exact: true }).click();
+ else await page.evaluate(() => window.dispatchEvent(new Event("test-recording-start")));
+ await expect(page.locator("html")).toHaveAttribute("data-closed", "true");
+ await expect(page.locator("html")).not.toHaveAttribute("data-selected");
+ });
+}
+
+test("dismissing the Wayland portal cleans up without a second prompt or alert", async ({
+ page,
+}) => {
+ await installDesktopBridge(page);
+ await installDesktopBridgeOverrides(page, () => {
+ Object.assign(window.electronAPI, {
+ getPlatform: async () => "linux",
+ getSelectedSource: async () => ({ id: "screen:linux-portal", name: "System picker" }),
+ getSources: async () => {
+ throw new Error("Must not enumerate Wayland sources");
+ },
+ startCountdown: async () => ({ success: true, cancelled: false }),
+ setRecordingState: async (active: boolean) => {
+ document.documentElement.dataset.recording = String(active);
+ },
+ finishRecordingStartup: async () => {
+ document.documentElement.dataset.startupFinished = "true";
+ },
+ });
+ Object.defineProperty(navigator.mediaDevices, "getDisplayMedia", {
+ value: async () => {
+ const html = document.documentElement;
+ html.dataset.portalCalls = String(Number(html.dataset.portalCalls ?? 0) + 1);
+ throw new DOMException("Cancelled", "NotAllowedError");
+ },
+ });
+ window.alert = (message) => {
+ document.documentElement.dataset.alert = String(message);
+ };
+ });
+ await page.goto("/?windowType=hud-overlay");
+ await expect(page.getByRole("button", { name: "Choose recording source" })).toContainText(
+ "System picker",
+ { timeout: 15000 },
+ );
+ await page.getByRole("button", { name: "Record", exact: true }).click();
+ await expect(page.locator("html")).toHaveAttribute("data-startup-finished", "true");
+ await expect(page.locator("html")).toHaveAttribute("data-portal-calls", "1");
+ await expect(page.locator("html")).toHaveAttribute("data-recording", "false");
+ await expect(page.locator("html")).not.toHaveAttribute("data-alert");
+ await expect(page.getByRole("button", { name: "Record", exact: true })).toBeEnabled();
+});