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 screen source selection recovery flow
seungryk6ba9f1e94809
diff --git a/src/components/launch/LaunchWindow.tsx b/src/components/launch/LaunchWindow.tsxindex 570ec2809..2b350df48 100644--- a/src/components/launch/LaunchWindow.tsx+++ b/src/components/launch/LaunchWindow.tsx@@ -32,6 +32,7 @@ import { AudioLevelMeter } from "../ui/audio-level-meter";import { Button } from "../ui/button";import { Tooltip } from "../ui/tooltip";import styles from "./LaunchWindow.module.css";+import { openSourceSelectorWithPermissionRetry } from "./openSourceSelectorFlow";const ICON_SIZE = 20;@@ -326,9 +327,12 @@ export function LaunchWindow() {return () => clearInterval(interval);}, []);- const openSourceSelector = () => {+ const openSourceSelector = async () => {if (window.electronAPI) {- window.electronAPI.openSourceSelector();+ await openSourceSelectorWithPermissionRetry({+ openSourceSelector: () => window.electronAPI.openSourceSelector(),+ requestScreenAccess: () => window.electronAPI.requestScreenAccess(),+ });}};diff --git a/src/components/launch/SourceSelector.test.tsx b/src/components/launch/SourceSelector.test.tsxnew file mode 100644index 000000000..b40c46db1--- /dev/null+++ b/src/components/launch/SourceSelector.test.tsx@@ -0,0 +1,77 @@+import { fireEvent, render, screen, waitFor } from "@testing-library/react";+import { beforeEach, describe, expect, it, vi } from "vitest";+import { SourceSelector } from "./SourceSelector";++vi.mock("@/contexts/I18nContext", () => ({+ useScopedT: (namespace: string) => {+ if (namespace === "common") {+ return (key: string) => {+ if (key === "actions.cancel") return "Cancel";+ if (key === "actions.share") return "Share";+ if (key === "actions.reload") return "Reload";+ return key;+ };+ }++ return (key: string, vars?: Record<string, string>) => {+ if (key === "sourceSelector.loading") return "Loading sources...";+ if (key === "sourceSelector.emptyTitle") return "No screens or windows found";+ if (key === "sourceSelector.emptyDescription") {+ return "If you just granted screen recording permission, reload this picker. On macOS you may need to reopen OpenScreen.";+ }+ if (key === "sourceSelector.loadFailedDescription") {+ return "OpenScreen could not load capture sources. Reload this picker and try again.";+ }+ if (key === "sourceSelector.screens") return `Screens (${vars?.count ?? "0"})`;+ if (key === "sourceSelector.windows") return `Windows (${vars?.count ?? "0"})`;+ return key;+ };+ },+}));++describe("SourceSelector", () => {+ beforeEach(() => {+ window.electronAPI = {+ ...window.electronAPI,+ getSources: vi.fn().mockResolvedValue([]),+ selectSource: vi.fn(),+ } as typeof window.electronAPI;+ });++ it("shows a retry state when no capture sources are available", async () => {+ render(<SourceSelector />);++ await screen.findByText("No screens or windows found");+ expect(screen.getByRole("button", { name: "Reload" })).toBeInTheDocument();+ });++ it("reloads capture sources from the empty state", async () => {+ const getSources = vi+ .fn()+ .mockResolvedValueOnce([])+ .mockResolvedValueOnce([+ {+ id: "screen:1:0",+ name: "Display 1",+ thumbnail: "data:image/png;base64,abc",+ display_id: "1",+ appIcon: null,+ },+ ]);+ window.electronAPI = {+ ...window.electronAPI,+ getSources,+ selectSource: vi.fn(),+ } as typeof window.electronAPI;++ render(<SourceSelector />);++ await screen.findByText("No screens or windows found");+ fireEvent.click(screen.getByRole("button", { name: "Reload" }));++ await waitFor(() => {+ expect(screen.getByText("Display 1")).toBeInTheDocument();+ });+ expect(getSources).toHaveBeenCalledTimes(2);+ });+});diff --git a/src/components/launch/SourceSelector.tsx b/src/components/launch/SourceSelector.tsxindex f3ae98908..17e7444cb 100644--- a/src/components/launch/SourceSelector.tsx+++ b/src/components/launch/SourceSelector.tsx@@ -1,4 +1,4 @@-import { useEffect, useState } from "react";+import { useCallback, useEffect, useState } from "react";import { MdCheck } from "react-icons/md";import { useScopedT } from "@/contexts/I18nContext";import { Button } from "../ui/button";@@ -19,39 +19,49 @@ export function SourceSelector() {const [sources, setSources] = useState<DesktopSource[]>([]);const [selectedSource, setSelectedSource] = useState<DesktopSource | null>(null);const [loading, setLoading] = useState(true);+ const [loadFailed, setLoadFailed] = useState(false);- useEffect(() => {- async function fetchSources() {- setLoading(true);- try {- const rawSources = await window.electronAPI.getSources({- types: ["screen", "window"],- thumbnailSize: { width: 320, height: 180 },- fetchWindowIcons: true,- });- setSources(- rawSources.map((source) => ({- id: source.id,- name:- source.id.startsWith("window:") && source.name.includes(" — ")- ? source.name.split(" — ")[1] || source.name- : source.name,- thumbnail: source.thumbnail,- display_id: source.display_id,- appIcon: source.appIcon,- })),- );- } catch (error) {- console.error("Error loading sources:", error);- } finally {- setLoading(false);- }+ const fetchSources = useCallback(async () => {+ setLoading(true);+ setLoadFailed(false);+ try {+ const rawSources = await window.electronAPI.getSources({+ types: ["screen", "window"],+ thumbnailSize: { width: 320, height: 180 },+ fetchWindowIcons: true,+ });+ setSources(+ rawSources.map((source) => ({+ id: source.id,+ name:+ source.id.startsWith("window:") && source.name.includes(" — ")+ ? source.name.split(" — ")[1] || source.name+ : source.name,+ thumbnail: source.thumbnail,+ display_id: source.display_id,+ appIcon: source.appIcon,+ })),+ );+ setSelectedSource((current) =>+ current && rawSources.some((source) => source.id === current.id) ? current : null,+ );+ } catch (error) {+ console.error("Error loading sources:", error);+ setSources([]);+ setSelectedSource(null);+ setLoadFailed(true);+ } finally {+ setLoading(false);}- fetchSources();}, []);+ useEffect(() => {+ void fetchSources();+ }, [fetchSources]);+const screenSources = sources.filter((s) => s.id.startsWith("screen:"));const windowSources = sources.filter((s) => s.id.startsWith("window:"));+ const hasNoSources = !loading && sources.length === 0;const handleSourceSelect = (source: DesktopSource) => setSelectedSource(source);const handleShare = async () => {@@ -72,6 +82,30 @@ export function SourceSelector() {);}+ if (hasNoSources) {+ return (+ <div+ className={`h-full flex items-center justify-center ${styles.glassContainer}`}+ style={{ minHeight: "100vh" }}+ >+ <div className="max-w-[320px] px-6 text-center">+ <h2 className="text-sm font-semibold text-white">{t("sourceSelector.emptyTitle")}</h2>+ <p className="mt-2 text-xs leading-5 text-zinc-400">+ {loadFailed+ ? t("sourceSelector.loadFailedDescription")+ : t("sourceSelector.emptyDescription")}+ </p>+ <Button+ onClick={() => void fetchSources()}+ className="mt-4 h-8 rounded-lg bg-[#34B27B] px-5 text-[11px] font-semibold text-white transition-transform duration-150 hover:bg-[#34B27B]/85 active:scale-95"+ >+ {tc("actions.reload")}+ </Button>+ </div>+ </div>+ );+ }+const renderSourceCard = (source: DesktopSource) => {const isSelected = selectedSource?.id === source.id;return (diff --git a/src/components/launch/openSourceSelectorFlow.test.ts b/src/components/launch/openSourceSelectorFlow.test.tsnew file mode 100644index 000000000..ac80f1adc--- /dev/null+++ b/src/components/launch/openSourceSelectorFlow.test.ts@@ -0,0 +1,73 @@+import { describe, expect, it, vi } from "vitest";+import { openSourceSelectorWithPermissionRetry } from "./openSourceSelectorFlow";++describe("openSourceSelectorWithPermissionRetry", () => {+ it("returns immediately when the source selector opens on the first attempt", async () => {+ const openSourceSelector = vi.fn().mockResolvedValue({ opened: true });+ const requestScreenAccess = vi.fn();++ const result = await openSourceSelectorWithPermissionRetry({+ openSourceSelector,+ requestScreenAccess,+ wait: vi.fn(),+ });++ expect(result).toEqual({ opened: true });+ expect(openSourceSelector).toHaveBeenCalledTimes(1);+ expect(requestScreenAccess).not.toHaveBeenCalled();+ });++ it("retries opening after macOS screen permission becomes granted", async () => {+ const openSourceSelector = vi+ .fn()+ .mockResolvedValueOnce({+ opened: false,+ reason: "screen-access-required",+ access: { success: true, granted: false, status: "not-determined" },+ })+ .mockResolvedValueOnce({ opened: true });+ const requestScreenAccess = vi+ .fn()+ .mockResolvedValueOnce({ success: true, granted: false, status: "not-determined" })+ .mockResolvedValueOnce({ success: true, granted: true, status: "granted" });+ const wait = vi.fn().mockResolvedValue(undefined);++ const result = await openSourceSelectorWithPermissionRetry({+ openSourceSelector,+ requestScreenAccess,+ wait,+ maxAttempts: 4,+ });++ expect(result).toEqual({ opened: true });+ expect(wait).toHaveBeenCalledTimes(2);+ expect(requestScreenAccess).toHaveBeenCalledTimes(2);+ expect(openSourceSelector).toHaveBeenCalledTimes(2);+ });++ it("stops retrying once macOS permission is explicitly denied", async () => {+ const openSourceSelector = vi.fn().mockResolvedValue({+ opened: false,+ reason: "screen-access-required",+ access: { success: true, granted: false, status: "not-determined" },+ });+ const requestScreenAccess = vi+ .fn()+ .mockResolvedValueOnce({ success: true, granted: false, status: "denied" });++ const result = await openSourceSelectorWithPermissionRetry({+ openSourceSelector,+ requestScreenAccess,+ wait: vi.fn(),+ maxAttempts: 4,+ });++ expect(result).toEqual({+ opened: false,+ reason: "screen-access-required",+ access: { success: true, granted: false, status: "denied" },+ });+ expect(requestScreenAccess).toHaveBeenCalledTimes(1);+ expect(openSourceSelector).toHaveBeenCalledTimes(1);+ });+});diff --git a/src/components/launch/openSourceSelectorFlow.ts b/src/components/launch/openSourceSelectorFlow.tsnew file mode 100644index 000000000..540f1fcef--- /dev/null+++ b/src/components/launch/openSourceSelectorFlow.ts@@ -0,0 +1,62 @@+export type ScreenAccessResult = {+ success: boolean;+ granted: boolean;+ status: string;+ error?: string;+};++export type OpenSourceSelectorResult = {+ opened: boolean;+ reason?: string;+ access?: ScreenAccessResult;+};++type OpenSourceSelectorFlowOptions = {+ openSourceSelector: () => Promise<OpenSourceSelectorResult>;+ requestScreenAccess: () => Promise<ScreenAccessResult>;+ wait?: (ms: number) => Promise<void>;+ retryDelayMs?: number;+ maxAttempts?: number;+};++const defaultWait = (ms: number) => new Promise<void>((resolve) => window.setTimeout(resolve, ms));++function shouldRetryAfterPermissionPrompt(result: OpenSourceSelectorResult): boolean {+ return (+ result.opened === false &&+ result.reason === "screen-access-required" &&+ result.access?.status === "not-determined"+ );+}++export async function openSourceSelectorWithPermissionRetry({+ openSourceSelector,+ requestScreenAccess,+ wait = defaultWait,+ retryDelayMs = 750,+ maxAttempts = 8,+}: OpenSourceSelectorFlowOptions): Promise<OpenSourceSelectorResult> {+ const initialResult = await openSourceSelector();+ if (!shouldRetryAfterPermissionPrompt(initialResult)) {+ return initialResult;+ }++ for (let attempt = 0; attempt < maxAttempts; attempt += 1) {+ await wait(retryDelayMs);+ const access = await requestScreenAccess();++ if (access.granted) {+ return openSourceSelector();+ }++ if (access.status !== "not-determined") {+ return {+ opened: false,+ reason: "screen-access-required",+ access,+ };+ }+ }++ return initialResult;+}diff --git a/src/i18n/locales/en/launch.json b/src/i18n/locales/en/launch.jsonindex 133a96127..979deb6bf 100644--- a/src/i18n/locales/en/launch.json+++ b/src/i18n/locales/en/launch.json@@ -32,6 +32,9 @@"loading": "Loading sources...","screens": "Screens ({{count}})","windows": "Windows ({{count}})",+ "emptyTitle": "No screens or windows found",+ "emptyDescription": "If you just granted screen recording permission, reload this picker. On macOS you may need to reopen OpenScreen.",+ "loadFailedDescription": "OpenScreen could not load capture sources. Reload this picker and try again.","defaultSourceName": "Screen"},"recording": {