Create polished demo videos without editing skills. Mac/Windows/Linux
Harden capture picker and remember valid sources
webadderall84697788e6b8
diff --git a/electron/ipc/capturePickerSources.test.ts b/electron/ipc/capturePickerSources.test.tsindex d7e0d8d5..bc7a54c9 100644--- a/electron/ipc/capturePickerSources.test.ts+++ b/electron/ipc/capturePickerSources.test.ts@@ -6,6 +6,7 @@ const mocks = vi.hoisted(() => ({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,diff --git a/electron/ipc/capturePickerSources.ts b/electron/ipc/capturePickerSources.tsindex a24bdc0b..accfb061 100644--- a/electron/ipc/capturePickerSources.ts+++ b/electron/ipc/capturePickerSources.ts@@ -1,3 +1,4 @@+import { systemPreferences } from "electron";import { execFile } from "node:child_process";import { promisify } from "node:util";import { getNativeMacWindowsFrontToBack, resolveLinuxWindowBounds } from "./cursor/bounds";@@ -45,7 +46,9 @@ ConvertTo-Json -InputObject @([RecordlyPickerWindows]::List()) -Compress`;export async function listCapturePickerWindows(): Promise<CapturePickerWindow[]> {if (process.platform === "darwin") {- const entries = await getNativeMacWindowsFrontToBack();+ if (systemPreferences.getMediaAccessStatus("screen") !== "granted")+ throw new Error("Allow screen recording in System Settings before picking a window.");+ const entries = await getNativeMacWindowsFrontToBack({ strict: true });return entries.filter((entry) =>@@ -65,11 +68,14 @@ export async function listCapturePickerWindows(): Promise<CapturePickerWindow[]>height: entry.height!,}));}- const sources = await getDesktopSources({- types: ["window"],- thumbnailSize: { width: 0, height: 0 },- fetchWindowIcons: false,- });+ const sources = await getDesktopSources(+ {+ types: ["window"],+ thumbnailSize: { width: 0, height: 0 },+ fetchWindowIcons: false,+ },+ { strict: true },+ );const capturable = sources.filter((source): source is SelectedSource & { id: string } =>typeof source.id === "string" && source.id.startsWith("window:"),@@ -107,6 +113,8 @@ export async function listCapturePickerWindows(): Promise<CapturePickerWindow[]>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] : [];@@ -117,6 +125,8 @@ export async function listCapturePickerWindows(): Promise<CapturePickerWindow[]>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? {...bounds,diff --git a/electron/ipc/captureSelection.test.ts b/electron/ipc/captureSelection.test.tsnew file mode 100644index 00000000..7f905bd7--- /dev/null+++ b/electron/ipc/captureSelection.test.ts@@ -0,0 +1,98 @@+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";+const mocks = vi.hoisted(() => ({+ read: vi.fn(),+ write: vi.fn(),+ windows: vi.fn(),+ sources: vi.fn(),+ current: null as unknown,+ displays: [{ id: 1, bounds: { x: 0, y: 0, width: 1440, height: 1000 } }],+}));+vi.mock("../appSettingsStore", () => ({+ readAppSetting: mocks.read,+ writeAppSetting: mocks.write,+}));+vi.mock("./capturePickerSources", () => ({ listCapturePickerWindows: mocks.windows }));+vi.mock("./register/sources", () => ({ getDesktopSources: mocks.sources }));+vi.mock("./state", () => ({+ get selectedSource() {+ return mocks.current;+ },+ setSelectedSource: (value: unknown) => {+ mocks.current = value;+ },+}));+vi.mock("./utils", () => ({ getScreen: () => ({ getAllDisplays: () => mocks.displays }) }));+import {+ rememberCaptureSource,+ restoreLastCaptureSource,+ validateCaptureSource,+} from "./captureSelection";+const platform = process.platform;+const source = { id: "window:101:0", name: "Document", windowTitle: "Document", appName: "Notes" };+beforeEach(() => {+ vi.clearAllMocks();+ Object.defineProperty(process, "platform", { value: "darwin" });+ mocks.current = null;+ mocks.read.mockReturnValue({ platform: "darwin", source });+ mocks.windows.mockResolvedValue([+ { id: source.id, appName: "Notes", title: "Document", x: 0, y: 0, width: 100, height: 100 },+ ]);+});+afterEach(() => {+ Object.defineProperty(process, "platform", { value: platform });+});+describe("remembered capture selection", () => {+ it("restores only the same available window", async () => {+ expect(await restoreLastCaptureSource()).toMatchObject(source);+ expect(mocks.current).toMatchObject(source);+ });+ it("rejects closed windows and clears stale saved selection", async () => {+ mocks.windows.mockResolvedValue([]);+ expect(await restoreLastCaptureSource()).toBeNull();+ expect(mocks.write).toHaveBeenCalledWith("recordly.capture.lastSource.v1", null);+ });+ it("rejects a recycled window ID with a different title", async () => {+ mocks.windows.mockResolvedValue([+ { id: source.id, title: "Another document", appName: "Notes" },+ ]);+ expect(await validateCaptureSource(source)).toBeNull();+ });+ it("rejects disconnected screens and areas that would be resized", async () => {+ expect(+ await validateCaptureSource({ id: "screen:2:0", name: "Gone", display_id: "2" }),+ ).toBeNull();+ expect(+ await validateCaptureSource({+ id: "area:1",+ name: "Area",+ display_id: "1",+ area: { x: 1300, y: 0, width: 400, height: 300 },+ }),+ ).toBeNull();+ });+ it("does not broaden window capture when detection fails", async () => {+ mocks.windows.mockRejectedValue(new Error("permission denied"));+ await expect(validateCaptureSource(source)).rejects.toThrow("permission denied");+ expect(mocks.sources).not.toHaveBeenCalled();+ });+ it("keeps a newer user selection made during restore", async () => {+ let resolve!: (value: unknown[]) => void;+ mocks.windows.mockReturnValue(+ new Promise((done) => {+ resolve = done;+ }),+ );+ const pending = restoreLastCaptureSource();+ const newer = { id: "screen:1:0", name: "Newer" };+ mocks.current = newer;+ resolve([]);+ expect(await pending).toEqual(newer);+ expect(mocks.write).not.toHaveBeenCalled();+ });+ it("saves only selection metadata, excluding thumbnails", () => {+ rememberCaptureSource({ ...source, thumbnail: "private pixels" });+ const stored = mocks.write.mock.calls[0][1];+ expect(stored.source).not.toHaveProperty("thumbnail");+ expect(stored.platform).toBe("darwin");+ });+});diff --git a/electron/ipc/captureSelection.ts b/electron/ipc/captureSelection.tsnew file mode 100644index 00000000..6a7a24d3--- /dev/null+++ b/electron/ipc/captureSelection.ts@@ -0,0 +1,120 @@+import { readAppSetting, writeAppSetting } from "../appSettingsStore";+import { listCapturePickerWindows } from "./capturePickerSources";+import {+ createAreaSource,+ createWindowSource,+ getSourceArea,+ normalizeCapturePick,+} from "./sourceArea";+import { selectedSource, setSelectedSource } from "./state";+import type { SelectedSource } from "./types";+import { getScreen } from "./utils";+import { getDesktopSources } from "./register/sources";+import {+ isLikelyLinuxWaylandSession,+ LINUX_PORTAL_SCREEN_SOURCE_ID,+} from "./register/sourceMapping";++const LAST_SOURCE_KEY = "recordly.capture.lastSource.v1";++/** Revalidate identity and geometry; never substitute a broader capture source. */+export async function validateCaptureSource(candidate: unknown): Promise<SelectedSource | null> {+ if (!candidate || typeof candidate !== "object") return null;+ const source = candidate as Partial<SelectedSource>;+ if (typeof source.id !== "string" || typeof source.name !== "string") return null;+ if (source.id === LINUX_PORTAL_SCREEN_SOURCE_ID)+ return process.platform === "linux" && isLikelyLinuxWaylandSession(process.env)+ ? { id: source.id, name: "System picker", sourceType: "screen" }+ : null;+ if (source.id.startsWith("window:")) {+ const windows = await listCapturePickerWindows();+ const match = windows.find(+ (entry) =>+ entry.id === source.id &&+ (entry.title || entry.appName || "Window") ===+ (source.windowTitle ?? source.name) &&+ (!source.appName || entry.appName === source.appName),+ );+ return match ? createWindowSource(match) : null;+ }+ const display = getScreen()+ .getAllDisplays()+ .find((entry) => String(entry.id) === source.display_id);+ if (!display) return null;+ if (source.id.startsWith("area:")) {+ if (process.platform !== "darwin") return null;+ const area = getSourceArea(source as SelectedSource);+ if (!area) return null;+ const normalized = normalizeCapturePick(+ { ...area, kind: "area", displayId: display.id, record: false },+ [{ id: display.id, bounds: display.bounds }],+ [],+ );+ // A changed display must invalidate the area rather than silently resize it.+ if (+ !normalized ||+ normalized.kind !== "area" ||+ ["x", "y", "width", "height"].some(+ (key) => normalized[key as keyof typeof area] !== area[key as keyof typeof area],+ )+ )+ return null;+ return createAreaSource(normalized);+ }+ if (!source.id.startsWith("screen:")) return null;+ const sources = await getDesktopSources(+ { types: ["screen"], thumbnailSize: { width: 0, height: 0 } },+ { strict: true },+ );+ const match = sources.find(+ (entry) => entry.id === source.id && entry.display_id === source.display_id,+ );+ return match+ ? { id: match.id, name: match.name, display_id: match.display_id, sourceType: "screen" }+ : null;+}++export function rememberCaptureSource(source: SelectedSource) {+ try {+ writeAppSetting(LAST_SOURCE_KEY, {+ platform: process.platform,+ source: {+ id: source.id,+ name: source.name,+ display_id: source.display_id,+ sourceType: source.sourceType,+ appName: source.appName,+ windowTitle: source.windowTitle,+ area: source.area,+ },+ });+ } catch (error) {+ console.warn("Unable to remember capture source:", error);+ }+}++let restoring: Promise<SelectedSource | null> | null = null;+export async function restoreLastCaptureSource(): Promise<SelectedSource | null> {+ if (selectedSource) return selectedSource;+ if (!restoring)+ restoring = (async () => {+ const saved = readAppSetting(LAST_SOURCE_KEY) as {+ platform?: unknown;+ source?: unknown;+ } | null;+ if (!saved || saved.platform !== process.platform) return null;+ try {+ const restored = await validateCaptureSource(saved.source);+ // A user selection made while validation runs takes precedence.+ if (selectedSource) return selectedSource;+ setSelectedSource(restored);+ if (!restored) writeAppSetting(LAST_SOURCE_KEY, null);+ return restored;+ } catch {+ return null;+ }+ })().finally(() => {+ restoring = null;+ });+ return restoring;+}diff --git a/electron/ipc/cursor/bounds.ts b/electron/ipc/cursor/bounds.tsindex fddbbd0e..19311eb5 100644--- a/electron/ipc/cursor/bounds.ts+++ b/electron/ipc/cursor/bounds.ts@@ -60,7 +60,9 @@ export async function getNativeMacWindowSources(options?: { maxAgeMs?: number })}/** On-screen windows ordered front to back, for finding the window under a point. */-export async function getNativeMacWindowsFrontToBack(): Promise<NativeMacWindowSource[]> {+export async function getNativeMacWindowsFrontToBack(options?: {+ strict?: boolean;+}): Promise<NativeMacWindowSource[]> {if (process.platform !== "darwin") {return [];}@@ -73,6 +75,7 @@ export async function getNativeMacWindowsFrontToBack(): Promise<NativeMacWindowS});const parsed: unknown = JSON.parse(stdout);if (!Array.isArray(parsed)) {+ if (options?.strict) throw new Error("Unable to read window positions.");return [];}return parsed.filter(@@ -82,6 +85,10 @@ export async function getNativeMacWindowsFrontToBack(): Promise<NativeMacWindowStypeof (entry as NativeMacWindowSource).id === "string",);} catch (error) {+ if (options?.strict)+ throw new Error(+ "Unable to detect windows. Check screen recording permission and try again.",+ );console.warn("Failed to list windows front to back:", error);return [];}diff --git a/electron/ipc/register/capturePicker.test.ts b/electron/ipc/register/capturePicker.test.tsindex 380037b6..70ce8892 100644--- a/electron/ipc/register/capturePicker.test.ts+++ b/electron/ipc/register/capturePicker.test.ts@@ -2,7 +2,10 @@ import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";const mocks = vi.hoisted(() => ({handlers: new Map<string, (...args: unknown[]) => unknown>(),list: vi.fn(),+ validate: vi.fn(),+ remember: vi.fn(),selected: vi.fn(),+ currentSource: null as Record<string, unknown> | null,create: vi.fn(),close: vi.fn(),overlay: {},@@ -21,9 +24,18 @@ vi.mock("../../windows", () => ({closeCapturePickerWindows: mocks.close,getCapturePickerWindows: () => mocks.windows,}));+vi.mock("../captureSelection", () => ({+ validateCaptureSource: mocks.validate,+ rememberCaptureSource: mocks.remember,+}));vi.mock("../capturePickerSources", () => ({ listCapturePickerWindows: mocks.list }));vi.mock("../cursor/bounds", () => ({ stopWindowBoundsCapture: vi.fn() }));-vi.mock("../state", () => ({ setSelectedSource: mocks.selected }));+vi.mock("../state", () => ({+ setSelectedSource: mocks.selected,+ get selectedSource() {+ return mocks.currentSource;+ },+}));vi.mock("../utils", () => ({getScreen: () => ({getAllDisplays: () => [{ id: 1, bounds: { x: 0, y: 0, width: 1440, height: 1000 } }],@@ -45,9 +57,11 @@ afterEach(() => {beforeEach(() => {vi.clearAllMocks();mocks.handlers.clear();+ mocks.currentSource = null;mocks.windows = [mocks.overlay];Object.defineProperty(process, "platform", { value: "darwin" });mocks.list.mockResolvedValue([]);+ mocks.validate.mockImplementation(async (source) => source);registerCapturePickerHandlers();});const call = (name: string, sender: object, input?: unknown) =>@@ -89,3 +103,55 @@ describe("selection-only picker IPC", () => {expect(mocks.list).not.toHaveBeenCalled();});});++it("rejects a window that disappeared while the picker was open", async () => {+ mocks.list.mockResolvedValue([+ {+ id: "window:101:0",+ title: "Document",+ appName: "Notes",+ x: 0,+ y: 0,+ width: 400,+ height: 300,+ },+ ]);+ mocks.validate.mockResolvedValue(null);+ const pending = call("pick-capture-target", mocks.outsider);+ await vi.waitFor(() => expect(mocks.create).toHaveBeenCalledOnce());+ await call("complete-capture-pick", mocks.overlay, {+ kind: "window",+ windowId: "window:101:0",+ displayId: 1,+ });+ expect(await pending).toMatchObject({+ success: false,+ message: "That window or screen is no longer available.",+ });+ expect(mocks.selected).not.toHaveBeenCalled();+ expect(mocks.remember).not.toHaveBeenCalled();+});+it("surfaces detection failures instead of opening a screen-only overlay", async () => {+ mocks.list.mockRejectedValue(new Error("Unable to detect windows"));+ expect(await call("pick-capture-target", mocks.outsider)).toMatchObject({+ success: false,+ message: "Unable to detect windows",+ });+ expect(mocks.create).not.toHaveBeenCalled();+ expect(mocks.selected).not.toHaveBeenCalled();+});++it("reopens the currently selected saved area, without reusing an old area for a window", async () => {+ mocks.currentSource = {+ id: "area:1",+ display_id: "1",+ area: { x: 100, y: 200, width: 400, height: 300 },+ };+ expect(await call("get-capture-picker-context", mocks.overlay, 1)).toMatchObject({+ lastArea: mocks.currentSource.area,+ });+ mocks.currentSource = { id: "window:101:0", display_id: "1" };+ expect(await call("get-capture-picker-context", mocks.overlay, 1)).toMatchObject({+ lastArea: null,+ });+});diff --git a/electron/ipc/register/capturePicker.ts b/electron/ipc/register/capturePicker.tsindex c541172d..af3eeef4 100644--- a/electron/ipc/register/capturePicker.ts+++ b/electron/ipc/register/capturePicker.ts@@ -1,3 +1,4 @@+import { rememberCaptureSource, validateCaptureSource } from "../captureSelection";import { listCapturePickerWindows } from "../capturePickerSources";import { BrowserWindow, ipcMain } from "electron";import {@@ -6,9 +7,14 @@ import {getCapturePickerWindows,} from "../../windows";import { stopWindowBoundsCapture } from "../cursor/bounds";-import { setSelectedSource } from "../state";-import { createAreaSource, createWindowSource, normalizeCapturePick } from "../sourceArea";-import type { AreaCapturePick, CapturePick, CapturePickerWindow, SelectedSource } from "../types";+import { selectedSource, setSelectedSource } from "../state";+import {+ createAreaSource,+ createWindowSource,+ getSourceArea,+ normalizeCapturePick,+} from "../sourceArea";+import type { CapturePick, CapturePickerWindow, SelectedSource } from "../types";import { getScreen } from "../utils";import { getScreenSourceIdForDisplay, isLikelyLinuxWaylandSession } from "./sourceMapping";import {@@ -22,10 +28,13 @@ async function createScreenSource(displayId: number): Promise<SelectedSource | nconst displays = getScreen().getAllDisplays();const index = displays.findIndex((display) => display.id === displayId);if (index < 0) return null;- const sources = await getDesktopSources({- types: ["screen"],- thumbnailSize: { width: 0, height: 0 },- });+ const sources = await getDesktopSources(+ {+ types: ["screen"],+ thumbnailSize: { width: 0, height: 0 },+ },+ { strict: true },+ );const matched =sources.find((source) => source.display_id === String(displayId)) ??(sources.length === displays.length ? sources[index] : undefined);@@ -50,7 +59,6 @@ async function createScreenSource(displayId: number): Promise<SelectedSource | nexport function registerCapturePickerHandlers() {let resolvePendingPick: ((pick: CapturePick | null) => void) | null = null;let pickableWindows: Promise<CapturePickerWindow[]> = Promise.resolve([]);- let lastArea: AreaCapturePick | null = null;const finishPick = (pick: CapturePick | null) => {const resolve = resolvePendingPick;@@ -69,6 +77,7 @@ export function registerCapturePickerHandlers() {sourceType: "screen" as const,};setSelectedSource(source);+ rememberCaptureSource(source);broadcastSelectedSourceChange();return {success: true,@@ -92,7 +101,6 @@ export function registerCapturePickerHandlers() {let source: SelectedSource | null;if (pick.kind === "area") {- lastArea = pick;source = createAreaSource(pick);} else if (pick.kind === "window") {const window = (await pickableWindows).find((entry) => entry.id === pick.windowId);@@ -100,6 +108,7 @@ export function registerCapturePickerHandlers() {} else {source = await createScreenSource(pick.displayId);}+ if (source) source = await validateCaptureSource(source);if (!source) {return { success: false, message: "That window or screen is no longer available." };}@@ -110,6 +119,7 @@ export function registerCapturePickerHandlers() {await bringSelectedWindowForward(source);}setSelectedSource(source);+ rememberCaptureSource(source);broadcastSelectedSourceChange();stopWindowBoundsCapture();return { success: true, source };@@ -184,7 +194,10 @@ export function registerCapturePickerHandlers() {window.y < y + height &&window.y + window.height > y,);- const previous = lastArea?.displayId === display.id ? lastArea : null;+ const previous =+ selectedSource?.display_id === String(display.id)+ ? getSourceArea(selectedSource)+ : null;return {displayBounds: display.bounds,allowArea: process.platform === "darwin",diff --git a/electron/ipc/register/sources.ts b/electron/ipc/register/sources.tsindex 38ec0ccd..e62d6563 100644--- a/electron/ipc/register/sources.ts+++ b/electron/ipc/register/sources.ts@@ -1,3 +1,4 @@+import { restoreLastCaptureSource } from "../captureSelection";import { createRecordingEditorNavigation } from "../../recordingEditorNavigation";import { execFile } from "node:child_process";import { promisify } from "node:util";@@ -117,13 +118,17 @@ export async function bringSelectedWindowForward(return null;}-export async function getDesktopSources(opts?: Electron.SourcesOptions): Promise<SelectedSource[]> {+export async function getDesktopSources(+ opts?: Electron.SourcesOptions,+ options?: { strict?: boolean },+): Promise<SelectedSource[]> {const cacheKey = JSON.stringify({types: opts?.types,thumbnailSize: opts?.thumbnailSize,fetchWindowIcons: opts?.fetchWindowIcons,});if (+ !options?.strict &&sourceListCache &&sourceListCache.key === cacheKey &&sourceListCache.expiresAt > Date.now()@@ -146,6 +151,10 @@ export async function getDesktopSources(opts?: Electron.SourcesOptions): Promisetypes: electronTypes,}).catch((error) => {+ if (options?.strict)+ throw new Error(+ "Unable to detect recording sources. Check capture permission and try again.",+ );console.warn("desktopCapturer.getSources failed (screen recording permission may be missing):",error,@@ -194,6 +203,8 @@ export async function getDesktopSources(opts?: Electron.SourcesOptions): Promise(electronScreenSourcesByIndex.length === displays.length? electronScreenSourcesByIndex[index]: undefined);+ if (options?.strict && !matchedSource)+ throw new Error("Unable to identify this screen. Try the picker again.");const displayName =displayId === primaryDisplayId? `Screen ${index + 1} (Primary)`@@ -588,7 +599,7 @@ body{background:transparent;overflow:hidden;width:100vw;height:100vh}});ipcMain.handle("get-selected-source", () => {- return selectedSource;+ return restoreLastCaptureSource();});ipcMain.handle("open-source-selector", () => {diff --git a/src/components/capture-picker/CapturePicker.tsx b/src/components/capture-picker/CapturePicker.tsxindex cc23f2b6..9cf3b36d 100644--- a/src/components/capture-picker/CapturePicker.tsx+++ b/src/components/capture-picker/CapturePicker.tsx@@ -1,6 +1,16 @@import { useCallback, useEffect, useRef, useState } from "react";import type { PointerEvent as ReactPointerEvent } from "react";-import { frontmostAt, MIN_AREA_SIZE, normalizeAreaRect, type AreaRect } from "./areaGeometry";+import {+ frontmostAt,+ MIN_AREA_SIZE,+ normalizeAreaRect,+ moveAreaRect,+ resizeAreaRect,+ rectContains,+ AREA_HANDLES,+ type AreaHandle,+ type AreaRect,+} from "./areaGeometry";type Target =| { kind: "window"; window: CapturePickerWindow; rect: AreaRect }@@ -19,7 +29,15 @@ export function CapturePicker() {const windows = useRef<{ window: CapturePickerWindow; rect: AreaRect }[]>([]);const origin = useRef({ x: window.screenX, y: window.screenY });const current = useRef<Target | null>(null);- const press = useRef<{ x: number; y: number; drawing: boolean } | null>(null);+ const press = useRef<{+ x: number;+ y: number;+ drawing: boolean;+ rect?: AreaRect;+ handle?: AreaHandle;+ moving?: boolean;+ } | null>(null);+ const editingArea = useRef(false);const completed = useRef(false);const targetAt = useCallback((x: number, y: number): Target => {const hit = frontmostAt(windows.current, x, y);@@ -100,6 +118,7 @@ export function CapturePicker() {): null;current.current = next;+ editingArea.current = next?.kind === "area";setTarget(next);requestAnimationFrame(() =>requestAnimationFrame(() => {@@ -130,12 +149,22 @@ export function CapturePicker() {}, [finish]);const onMove = (event: ReactPointerEvent<HTMLDivElement>) => {const start = press.current;- if (+ if (start?.rect) {+ const dx = event.clientX - start.x;+ const dy = event.clientY - start.y;+ update({+ kind: "area",+ rect: start.handle+ ? resizeAreaRect(start.rect, start.handle, dx, dy, screenRect())+ : moveAreaRect(start.rect, dx, dy, screenRect()),+ });+ } else if (start &&allowArea &&(start.drawing || Math.hypot(event.clientX - start.x, event.clientY - start.y) >= 4)) {start.drawing = true;+ editingArea.current = true;update({kind: "area",rect: normalizeAreaRect(@@ -148,7 +177,7 @@ export function CapturePicker() {screenRect(),),});- } else if (!start) update(targetAt(event.clientX, event.clientY));+ } else if (!start && !editingArea.current) update(targetAt(event.clientX, event.clientY));};const label =target?.kind === "window"@@ -163,7 +192,21 @@ export function CapturePicker() {onPointerMove={onMove}onPointerDown={(event) => {if (event.button !== 0) return;- press.current = { x: event.clientX, y: event.clientY, drawing: false };+ const area =+ editingArea.current && current.current?.kind === "area"+ ? current.current.rect+ : null;+ const handle = (event.target as HTMLElement).closest<HTMLElement>(+ "[data-area-handle]",+ )?.dataset.areaHandle as AreaHandle | undefined;+ press.current = {+ x: event.clientX,+ y: event.clientY,+ drawing: false,+ ...(area && (handle || rectContains(area, event.clientX, event.clientY))+ ? { rect: area, handle, moving: !handle }+ : {}),+ };event.currentTarget.setPointerCapture(event.pointerId);}}onPointerUp={(event) => {@@ -172,7 +215,11 @@ export function CapturePicker() {press.current = null;if (event.currentTarget.hasPointerCapture(event.pointerId))event.currentTarget.releasePointerCapture(event.pointerId);- finish(start.drawing ? current.current : targetAt(event.clientX, event.clientY));+ if (start.drawing || start.rect) return;+ if (editingArea.current) {+ editingArea.current = false;+ }+ finish(targetAt(event.clientX, event.clientY));}}onPointerCancel={() => {press.current = null;@@ -184,7 +231,11 @@ export function CapturePicker() {>{target && (<div- className="pointer-events-none absolute"+ className={+ target.kind === "area" && editingArea.current+ ? "absolute cursor-move"+ : "pointer-events-none absolute"+ }style={{left: target.rect.x,top: target.rect.y,@@ -196,8 +247,34 @@ export function CapturePicker() {outlineOffset: -2,}}>+ {target.kind === "area" &&+ AREA_HANDLES.map((handle) => {+ const left = handle.includes("w")+ ? "0%"+ : handle.includes("e")+ ? "100%"+ : "50%";+ const top = handle.includes("n")+ ? "0%"+ : handle.includes("s")+ ? "100%"+ : "50%";+ return (+ <div+ key={handle}+ data-area-handle={handle}+ className="absolute size-3 rounded-full border border-black/30 bg-white"+ style={{+ left,+ top,+ transform: "translate(-50%, -50%)",+ cursor: `${handle}-resize`,+ }}+ />+ );+ })}<div- className="absolute whitespace-nowrap rounded-md bg-blue-600 px-2 py-1 text-xs text-white"+ className="pointer-events-none absolute whitespace-nowrap rounded-md bg-blue-600 px-2 py-1 text-xs text-white"style={{ top: target.rect.y >= 30 ? -28 : 6, left: 6 }}>{label} · {Math.round(target.rect.width)} × {Math.round(target.rect.height)}@@ -206,9 +283,13 @@ export function CapturePicker() {)}<div className="pointer-events-none absolute inset-x-0 bottom-24 flex justify-center"><div className="rounded-full bg-black/80 px-4 py-2 text-sm text-white">- {allowArea- ? "Click a window or the desktop, or drag an area · Esc to cancel"- : "Click a window or the desktop · Esc to cancel"}+ {target?.kind === "area" && editingArea.current+ ? target.rect.width < MIN_AREA_SIZE || target.rect.height < MIN_AREA_SIZE+ ? "Area is too small · Drag to enlarge · Esc to cancel"+ : "Move or resize the area · Enter to select · Esc to cancel"+ : allowArea+ ? "Click a window or the desktop, or drag an area · Esc to cancel"+ : "Click a window or the desktop · Esc to cancel"}</div></div></div>diff --git a/src/components/launch/LaunchWindow.tsx b/src/components/launch/LaunchWindow.tsxindex 7ba926ff..a64d92d7 100644--- a/src/components/launch/LaunchWindow.tsx+++ b/src/components/launch/LaunchWindow.tsx@@ -12,7 +12,7 @@ import {XIcon,} from "@/components/ui/icons";import { AnimatePresence, motion } from "motion/react";-import { useCallback, useEffect, useRef } from "react";+import { useCallback, useEffect, useRef, useState } from "react";import { Separator } from "@/components/ui/separator";import { useScopedT } from "../../contexts/I18nContext";import { useMicrophoneDevices } from "../../hooks/useMicrophoneDevices";@@ -168,9 +168,12 @@ function LaunchWindowContent() {};const pickerPending = useRef(false);+ const [isPickerPending, setIsPickerPending] = useState(false);+ const [sourceReady, setSourceReady] = useState(false);const handlePickOnScreen = useCallback(async () => {- if (pickerPending.current || recording) return;+ if (pickerPending.current || recording || countdownActive || finalizing) return;pickerPending.current = true;+ setIsPickerPending(true);beginInteractiveHudAction();try {const result = await window.electronAPI.pickCaptureTarget();@@ -183,23 +186,33 @@ function LaunchWindowContent() {toast.error("Unable to open the source picker.");} finally {pickerPending.current = false;+ setIsPickerPending(false);}- }, [recording, beginInteractiveHudAction, syncSelectedSource]);+ }, [recording, countdownActive, finalizing, beginInteractiveHudAction, syncSelectedSource]);const initialSourceChecked = useRef(false);useEffect(() => {let mounted = true;let selectionEventSeen = false;- void window.electronAPI.getSelectedSource().then((source) => {- if (mounted && !selectionEventSeen) {- syncSelectedSource(source);- if (!initialSourceChecked.current) {- initialSourceChecked.current = true;- if (!source && !recording) void handlePickOnScreen();+ void window.electronAPI+ .getSelectedSource()+ .then((source) => {+ if (mounted) setSourceReady(true);+ if (mounted && !selectionEventSeen) {+ syncSelectedSource(source);+ if (!initialSourceChecked.current) {+ initialSourceChecked.current = true;+ if (!source && !recording) void handlePickOnScreen();+ }}- }- });+ })+ .catch(() => {+ if (mounted) {+ setSourceReady(true);+ toast.error("Unable to restore the previous source. Pick a source again.");+ }+ });const cleanup = window.electronAPI.onSelectedSourceChanged((source) => {selectionEventSeen = true;@@ -248,14 +261,19 @@ function LaunchWindowContent() {<Buttonvariant="ghost"size="lg"- className={`${styles.electronNoDrag} gap-2 px-3 min-w-0 max-w-[180px] shrink-0`}+ className={`${styles.electronNoDrag} group gap-2 px-3 min-w-0 max-w-[180px] shrink-0`}title={selectedSource}aria-label="Choose recording source"+ disabled={isPickerPending || !sourceReady || countdownActive}onClick={() => void handlePickOnScreen()}><MonitorIcon size={18} className="size-5 shrink-0" /><div className="flex-1 min-w-0 overflow-hidden">- <MarqueeText text={selectedSource} />+ {hasSelectedSource ? (+ <MarqueeText text={selectedSource} />+ ) : (+ <span>Pick screen</span>+ )}</div></Button><Separator orientation="vertical" className="mx-[5px] h-6 self-center" />@@ -368,7 +386,7 @@ function LaunchWindowContent() {size="icon"className={styles.electronNoDrag}onClick={hasSelectedSource ? toggleRecording : () => void handlePickOnScreen()}- disabled={countdownActive}+ disabled={countdownActive || isPickerPending || !sourceReady}title={t("recording.record")}><div className={styles.recDot} />diff --git a/src/components/launch/MarqueeText.css b/src/components/launch/MarqueeText.cssnew file mode 100644index 00000000..434b8143--- /dev/null+++ b/src/components/launch/MarqueeText.css@@ -0,0 +1,58 @@+.source-selector-marquee {+ position: relative;+ overflow: hidden;+ white-space: nowrap;+}++.source-selector-marquee-static {+ display: block;+ width: 100%;+ overflow: hidden;+ text-overflow: ellipsis;+ white-space: nowrap;+}++.source-selector-marquee-animated {+ position: absolute;+ inset: 0;+ opacity: 0;+ pointer-events: none;+}++.source-selector-marquee-track {+ display: inline-flex;+ max-width: none;+ white-space: nowrap;+ will-change: transform;+ animation: source-selector-marquee 10s linear infinite;+ animation-play-state: paused;+}++.source-selector-marquee-segment {+ display: inline-block;+}++.source-selector-marquee-duplicate {+ padding-left: 20px;+}++.group:hover .source-selector-marquee[data-overflowing="true"] .source-selector-marquee-static {+ opacity: 0;+}++.group:hover .source-selector-marquee[data-overflowing="true"] .source-selector-marquee-animated {+ opacity: 1;+}++.group:hover .source-selector-marquee[data-overflowing="true"] .source-selector-marquee-track {+ animation-play-state: running;+}++@keyframes source-selector-marquee {+ from {+ transform: translateX(0);+ }+ to {+ transform: translateX(-50%);+ }+}diff --git a/src/components/launch/MarqueeText.tsx b/src/components/launch/MarqueeText.tsxindex 8788e7c1..64716246 100644--- a/src/components/launch/MarqueeText.tsx+++ b/src/components/launch/MarqueeText.tsx@@ -1,3 +1,4 @@+import "./MarqueeText.css";import { useLayoutEffect, useRef, useState } from "react";export function MarqueeText({ text }: { text: string }) {@@ -24,7 +25,7 @@ export function MarqueeText({ text }: { text: string }) {<span ref={staticRef} className="source-selector-marquee-static">{text}</span>- <span className="source-selector-marquee-animated">+ <span aria-hidden="true" className="source-selector-marquee-animated"><span className="source-selector-marquee-track"><span className="source-selector-marquee-segment">{text}</span><span className="source-selector-marquee-segment source-selector-marquee-duplicate">diff --git a/src/components/launch/hooks/useLaunchWindowActions.ts b/src/components/launch/hooks/useLaunchWindowActions.tsindex 7dba168e..74c2529d 100644--- a/src/components/launch/hooks/useLaunchWindowActions.ts+++ b/src/components/launch/hooks/useLaunchWindowActions.ts@@ -3,7 +3,7 @@ import type { ProjectLibraryEntry } from "@/components/video-editor/ProjectBrowsimport type { DesktopSource } from "../popovers/launchPopoverTypes";export function useLaunchWindowActions() {- const [selectedSource, setSelectedSource] = useState("Screen");+ const [selectedSource, setSelectedSource] = useState("Pick screen");const [hasSelectedSource, setHasSelectedSource] = useState(false);const [projectLibraryEntries, setProjectLibraryEntries] = useState<ProjectLibraryEntry[]>([]);@@ -58,7 +58,7 @@ export function useLaunchWindowActions() {setHasSelectedSource(true);return;}- setSelectedSource("Screen");+ setSelectedSource("Pick screen");setHasSelectedSource(false);}, []);diff --git a/tests/ui/capture-picker.spec.ts b/tests/ui/capture-picker.spec.tsindex 621af051..b88fc32f 100644--- a/tests/ui/capture-picker.spec.ts+++ b/tests/ui/capture-picker.spec.ts@@ -86,7 +86,9 @@ test("a drag draws an area", async ({ page }) => {await page.mouse.down();await page.mouse.move(700, 450, { steps: 8 });await page.mouse.up();- await expect(page.getByText("400 × 250")).toBeVisible();+ await expect(page.getByText("Area · 400 × 250")).toBeVisible();+ expect(await pick(page)).toBeUndefined();+ await page.keyboard.press("Enter");expect(await pick(page)).toMatchObject({kind: "area",@@ -180,3 +182,59 @@ test("a newer selected-source event wins over the startup response", async ({ pa);await expect(page.locator("html")).not.toHaveAttribute("data-picker-calls");});++test("areas can be moved and resized before Enter confirms them", async ({ page }) => {+ await openPicker(page);+ await page.mouse.move(300, 200);+ await page.mouse.down();+ await page.mouse.move(700, 450, { steps: 8 });+ await page.mouse.up();+ await expect(page.getByText("Area · 400 × 250")).toBeVisible();+ await page.mouse.move(400, 300);+ await page.mouse.down();+ await page.mouse.move(450, 350, { steps: 5 });+ await page.mouse.up();+ expect(await pick(page)).toBeUndefined();+ const corner = page.locator('[data-area-handle="se"]');+ const bounds = await corner.boundingBox();+ if (!bounds) throw new Error("Missing area resize handle");+ await page.mouse.move(bounds.x + bounds.width / 2, bounds.y + bounds.height / 2);+ await page.mouse.down();+ await page.mouse.move(850, 600, { steps: 5 });+ await page.mouse.up();+ await expect(page.getByText("Area · 500 × 350")).toBeVisible();+ await page.keyboard.press("Enter");+ expect(await pick(page)).toMatchObject({+ kind: "area",+ x: 350,+ y: 250,+ width: 500,+ height: 350,+ record: false,+ });+});++test("unselected source reads Pick screen once and Record stays disabled while picking", async ({+ page,+}) => {+ await installDesktopBridge(page);+ await page.addInitScript(() => {+ Object.assign(window.electronAPI, {+ getSelectedSource: async () => null,+ pickCaptureTarget: async () =>+ new Promise((resolve) => {+ (window as unknown as { finishPicker: () => void }).finishPicker = () =>+ resolve({ success: false, canceled: true });+ document.documentElement.dataset.pickerPending = "true";+ }),+ });+ });+ await page.goto("/?windowType=hud-overlay");+ await expect(page.locator("html")).toHaveAttribute("data-picker-pending", "true");+ const source = page.getByRole("button", { name: "Choose recording source" });+ await expect(source).toHaveText("Pick screen");+ await expect(page.getByRole("button", { name: "Record", exact: true })).toBeDisabled();+ await page.evaluate(() => (window as unknown as { finishPicker: () => void }).finishPicker());+ await expect(page.getByRole("button", { name: "Record", exact: true })).toBeEnabled();+ await expect(source).toHaveText("Pick screen");+});