diff --git a/electron/mcp/media-tools.test.ts b/electron/mcp/media-tools.test.ts index 4f07f8548..126a5cfd2 100644 --- a/electron/mcp/media-tools.test.ts +++ b/electron/mcp/media-tools.test.ts @@ -33,6 +33,8 @@ import { RecordingCompletion } from "./recording-completion"; class FakeRunners { readonly started: CliRequest[] = []; recordStarts = true; + /** The `run.done` error a failed record start reports, when `recordStarts` is false. */ + recordStartError: string | undefined; /** The webcam the next take records beside the screen, if any. */ webcam: { path: string; offsetMs: number } | null = null; results: Partial> = {}; @@ -92,7 +94,10 @@ class FakeRunners { } else if (this.recordStarts) { queueMicrotask(() => handlers.onLog?.("info", "Recording started")); } else { - finish({ success: false, error: "Recording did not start within 30s" }); + finish({ + success: false, + error: this.recordStartError ?? "Recording did not start within 30s", + }); } return { window, done, close }; } @@ -407,6 +412,17 @@ describe("recording", () => { expect((await call("stopRecording")).isError).toBe(true); }); + it("carries the recorder's own failure reason to the client", async () => { + runners.recordStarts = false; + const reason = + 'The ScreenCast portal does not advertise METADATA cursor mode, so real cursor positions cannot be obtained on this session. Retry with "cursor": "system" to record with the system cursor baked in.'; + runners.recordStartError = reason; + const started = await call("startRecording", { display: 1 }); + expect(started.isError).toBe(true); + expect(textOf(started)).toContain(reason); + expect((await call("stopRecording")).isError).toBe(true); + }); + it("saves a take once when two stops arrive together", async () => { await call("startRecording", { window: "My App" }); const [first, second] = await Promise.all([call("stopRecording"), call("stopRecording")]); diff --git a/src/cli/CliRecordRunner.test.tsx b/src/cli/CliRecordRunner.test.tsx index 8018b743a..cb7c687f8 100644 --- a/src/cli/CliRecordRunner.test.tsx +++ b/src/cli/CliRecordRunner.test.tsx @@ -1,12 +1,17 @@ // @vitest-environment jsdom import { render, waitFor } from "@testing-library/react"; import { beforeEach, describe, expect, it, vi } from "vitest"; +import type { RecordingStartOutcome } from "@/hooks/useScreenRecorder"; import { CliRecordRunner } from "./CliRecordRunner"; const recorder = vi.hoisted(() => ({ recording: false, saving: false, - startRecordingImmediately: vi.fn(async () => undefined), + startRecordingImmediately: vi.fn( + async (): Promise => ({ + kind: "started", + }), + ), toggleRecording: vi.fn(), setMicrophoneEnabled: vi.fn(), setMicrophoneDeviceId: vi.fn(), @@ -217,4 +222,111 @@ describe("CliRecordRunner", () => { expect.stringContaining("--window do not apply"), ); }); + + describe("the start outcome", () => { + const METADATA_FAILURE = + "The ScreenCast portal does not advertise METADATA cursor mode, so real cursor positions cannot be obtained on this session."; + + it("fails a cursor-metadata start immediately, with the retry advice", async () => { + recorder.startRecordingImmediately.mockResolvedValueOnce({ + kind: "failed", + message: METADATA_FAILURE, + }); + render(); + await waitFor(() => + expect(window.electronAPI.cliDone).toHaveBeenCalledWith( + expect.objectContaining({ + success: false, + error: expect.stringContaining(`${METADATA_FAILURE} Retry with "cursor": "system"`), + }), + ), + ); + }); + + it("reports another failure without the cursor advice", async () => { + recorder.startRecordingImmediately.mockResolvedValueOnce({ + kind: "failed", + message: "Native Linux capture failed.", + }); + render(); + await waitFor(() => + expect(window.electronAPI.cliDone).toHaveBeenCalledWith( + expect.objectContaining({ + success: false, + error: expect.not.stringContaining("Retry with"), + }), + ), + ); + }); + + it("fails immediately when the picker was dismissed", async () => { + recorder.startRecordingImmediately.mockResolvedValueOnce({ kind: "cancelled" }); + render(); + await waitFor(() => + expect(window.electronAPI.cliDone).toHaveBeenCalledWith( + expect.objectContaining({ + success: false, + error: expect.stringContaining("picker was dismissed"), + }), + ), + ); + }); + + it("lets the camera failure win when both it and the start fail", async () => { + vi.mocked(window.electronAPI.cliGetRequest).mockResolvedValueOnce({ + ...request, + camera: true, + }); + recorder.setWebcamEnabled.mockImplementationOnce(async () => { + recorder.webcamEnabled = true; + return true; + }); + let answerStart: (outcome: RecordingStartOutcome) => void = () => undefined; + recorder.startRecordingImmediately.mockImplementationOnce( + () => + new Promise((resolve) => { + answerStart = resolve; + }), + ); + try { + const { rerender } = render(); + await waitFor(() => expect(recorder.startRecordingImmediately).toHaveBeenCalledTimes(1)); + // The camera turns back off before the start answers: its error wins, one cliDone. + recorder.webcamEnabled = false; + rerender(); + await waitFor(() => + expect(window.electronAPI.cliDone).toHaveBeenCalledWith( + expect.objectContaining({ + success: false, + error: expect.stringContaining("camera could not be opened"), + }), + ), + ); + answerStart({ kind: "failed", message: "Native Linux capture failed." }); + await new Promise((resolve) => setTimeout(resolve, 25)); + expect(window.electronAPI.cliDone).toHaveBeenCalledTimes(1); + } finally { + recorder.webcamEnabled = false; + recorder.recording = false; + } + }); + + it("keeps a backstop for a start that reports success but never confirms", async () => { + vi.useFakeTimers(); + try { + render(); + await vi.waitFor(() => expect(recorder.startRecordingImmediately).toHaveBeenCalledTimes(1)); + // `recording` never flips: only the backstop can say so. + await vi.advanceTimersByTimeAsync(30_000); + expect(window.electronAPI.cliDone).toHaveBeenCalledWith( + expect.objectContaining({ + success: false, + error: expect.stringContaining("never confirmed"), + }), + ); + } finally { + vi.useRealTimers(); + } + }); + }); }); diff --git a/src/cli/CliRecordRunner.tsx b/src/cli/CliRecordRunner.tsx index 65fc455ed..4d9f63d42 100644 --- a/src/cli/CliRecordRunner.tsx +++ b/src/cli/CliRecordRunner.tsx @@ -111,6 +111,14 @@ function buildDefaultProject(session: { }; } +/** Advice the caller can act on, for the one failure that names a cursor limitation. The + * matched wording is the PipeWire helper's, typed and stable, so it cannot misfire. */ +function withCursorRetryHint(message: string): string { + return /advertise METADATA cursor mode/.test(message) + ? `${message} Retry with "cursor": "system" to record with the system cursor baked in.` + : message; +} + export function CliRecordRunner() { const recorder = useScreenRecorder(); const startedRef = useRef(false); @@ -255,15 +263,25 @@ export function CliRecordRunner() { phaseRef.current = "recording"; void (async () => { try { - await startRecordingImmediately(); - // The hook reports start failures via toast/console, not by - // rejecting — without a deadline a failed start would hang the - // CLI forever. + const outcome = await startRecordingImmediately(); + // The recorder already knows why: report its reason now, not a guessing deadline. + if (outcome.kind !== "started") { + // The camera effect may have failed the run already (#1303); its error won. + if (phaseRef.current !== "recording") return; + await fail( + outcome.kind === "cancelled" + ? new Error("The screen-share picker was dismissed") + : new Error(withCursorRetryHint(outcome.message)), + ); + return; + } + // Started, but `recording` may not have reached this render yet; if it never + // does, that is a wiring defect, not a slow capture. setTimeout(() => { if (recordingStartedAtRef.current === null && phaseRef.current === "recording") { void fail( new Error( - "Recording did not start within 30s — see stderr for the underlying capture error", + "The recording start reported success but the recording state never confirmed it", ), ); } diff --git a/src/hooks/useScreenRecorder.startCancel.test.tsx b/src/hooks/useScreenRecorder.startCancel.test.tsx index e5d714bbc..993881c38 100644 --- a/src/hooks/useScreenRecorder.startCancel.test.tsx +++ b/src/hooks/useScreenRecorder.startCancel.test.tsx @@ -35,6 +35,7 @@ vi.mock("./recorderHandle", () => ({ import { toast } from "sonner"; import { createRecorderHandle } from "./recorderHandle"; +import type { RecordingStartOutcome } from "./useScreenRecorder"; import { useScreenRecorder } from "./useScreenRecorder"; type ElectronAPI = Window["electronAPI"]; @@ -208,3 +209,50 @@ describe("a failed native start never leaves the webcam recording", () => { expect(handle.discard).not.toHaveBeenCalled(); }); }); + +describe("the immediate start reports its outcome", () => { + const METADATA_FAILURE = + "The ScreenCast portal does not advertise METADATA cursor mode, so real cursor positions cannot be obtained on this session."; + + async function startImmediately() { + const view = renderHook(() => useScreenRecorder()); + await settle(); + let outcome: RecordingStartOutcome | undefined; + await act(async () => { + outcome = await view.result.current.startRecordingImmediately(); + }); + await settle(); + return { view, outcome }; + } + + it("returns the recorder's own reason when the native start fails", async () => { + stubElectronAPI("linux"); + api.startNativeLinuxRecording.mockResolvedValue({ success: false, error: METADATA_FAILURE }); + + const { view, outcome } = await startImmediately(); + + expect(outcome).toEqual({ kind: "failed", message: METADATA_FAILURE }); + expect(toast.error).toHaveBeenCalledWith(METADATA_FAILURE); + expect(view.result.current.recording).toBe(false); + }); + + it("returns cancelled, without a toast, when the picker is dismissed", async () => { + stubElectronAPI("linux"); + api.startNativeLinuxRecording.mockResolvedValue({ success: false, cancelled: true }); + + const { view, outcome } = await startImmediately(); + + expect(outcome).toEqual({ kind: "cancelled" }); + expect(toast.error).not.toHaveBeenCalled(); + expect(view.result.current.recording).toBe(false); + }); + + it("returns started when the take comes up", async () => { + stubElectronAPI("linux"); + + const { view, outcome } = await startImmediately(); + + expect(outcome).toEqual({ kind: "started" }); + expect(view.result.current.recording).toBe(true); + }); +}); diff --git a/src/hooks/useScreenRecorder.ts b/src/hooks/useScreenRecorder.ts index f4ef51391..20a08dbf4 100644 --- a/src/hooks/useScreenRecorder.ts +++ b/src/hooks/useScreenRecorder.ts @@ -96,7 +96,7 @@ type UseScreenRecorderReturn = { elapsedSeconds: number; toggleRecording: () => void; /** Starts recording with no countdown overlay. Used by the headless CLI runner. */ - startRecordingImmediately: () => Promise; + startRecordingImmediately: () => Promise; togglePaused: () => void; canPauseRecording: boolean; restartRecording: () => void; @@ -251,6 +251,12 @@ async function reportUnfinishedRecording(recordingId: number, cancelled: boolean } } +/** What became of an immediate start; a failed one flips no state a caller could watch. */ +export type RecordingStartOutcome = + | { kind: "started" } + | { kind: "cancelled" } + | { kind: "failed"; message: string }; + /** The user dismissed the system's source picker: the start stops, without an error. */ class RecordingStartCancelled extends Error {} @@ -1956,7 +1962,7 @@ export function useScreenRecorder(): UseScreenRecorderReturn { const startRecording = async ( countdownRunToken?: number, preparedRecordingId?: number | null, - ) => { + ): Promise => { const platform = window.electronAPI.getPlatform(); const browserCursorCaptureMode = effectiveBrowserCursorMode(platform, cursorCaptureMode); let browserStartClaimed = false; @@ -1966,7 +1972,7 @@ export function useScreenRecorder(): UseScreenRecorderReturn { try { if (!isCountdownRunActive(countdownRunToken)) { teardownMedia(); - return; + return { kind: "cancelled" }; } // Every path below records into the same folder, so one check covers them all. A // take that fills the disk is otherwise lost only when it is saved. A countdown @@ -1997,13 +2003,13 @@ export function useScreenRecorder(): UseScreenRecorderReturn { preparedRecordingId, ) ) { - return; + return { kind: "started" }; } const selectedSource = await window.electronAPI.getSelectedSource(); if (!selectedSource) { alert(t("recording.selectSource")); - return; + return { kind: "failed", message: "No screen or window was selected" }; } if ( @@ -2013,7 +2019,7 @@ export function useScreenRecorder(): UseScreenRecorderReturn { countdownRunToken, ) ) { - return; + return { kind: "started" }; } if ( await startNativeMacRecordingIfAvailable( @@ -2022,7 +2028,7 @@ export function useScreenRecorder(): UseScreenRecorderReturn { countdownRunToken, ) ) { - return; + return { kind: "started" }; } // The browser fallback cannot exclude a Linux preview from a monitor stream. @@ -2137,7 +2143,7 @@ export function useScreenRecorder(): UseScreenRecorderReturn { if (!isCountdownRunActive(countdownRunToken)) { teardownMedia(); - return; + return { kind: "cancelled" }; } if (webcamEnabled) { @@ -2163,7 +2169,7 @@ export function useScreenRecorder(): UseScreenRecorderReturn { if (!isCountdownRunActive(countdownRunToken)) { teardownMedia(); - return; + return { kind: "cancelled" }; } stream.current = new MediaStream(); @@ -2202,7 +2208,7 @@ export function useScreenRecorder(): UseScreenRecorderReturn { if (!isCountdownRunActive(countdownRunToken)) { teardownMedia(); - return; + return { kind: "cancelled" }; } let { @@ -2226,7 +2232,7 @@ export function useScreenRecorder(): UseScreenRecorderReturn { const hasAudio = stream.current.getAudioTracks().length > 0; if (!isCountdownRunActive(countdownRunToken)) { teardownMedia(); - return; + return { kind: "cancelled" }; } // Reserve the take before constructing MediaRecorder. Start cursor sampling below @@ -2241,7 +2247,7 @@ export function useScreenRecorder(): UseScreenRecorderReturn { browserStartClaimed = true; if (!isCountdownRunActive(countdownRunToken)) { teardownMedia(); - return; + return { kind: "cancelled" }; } recordingId.current = Date.now(); const activeRecordingId = recordingId.current; @@ -2303,12 +2309,13 @@ export function useScreenRecorder(): UseScreenRecorderReturn { { once: true }, ); } + return { kind: "started" }; } catch (error) { const startCancelled = error instanceof RecordingStartCancelled; window.electronAPI?.setRecordingState?.(false); + const errorMsg = error instanceof Error ? error.message : "Failed to start recording"; if (!startCancelled) { console.error("Failed to start recording:", error); - const errorMsg = error instanceof Error ? error.message : "Failed to start recording"; if (errorMsg.includes("Permission denied") || errorMsg.includes("NotAllowedError")) { toast.error(t("recording.permissionDenied")); } else { @@ -2328,6 +2335,7 @@ export function useScreenRecorder(): UseScreenRecorderReturn { if (failed) discardUnstartedRecorder(failed); } teardownMedia(); + return startCancelled ? { kind: "cancelled" } : { kind: "failed", message: errorMsg }; } finally { if (browserStartClaimed && !browserRecorderStarted) { await window.electronAPI.setRecordingState(false).catch((error) => {