Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

browserRecording.test.ts

265 lines9.2 KB

1import {
2 DESKTOP_PREVIEW_RECORDING_CAPTURE_TRIGGER,
3 EnvironmentId,
4 ThreadId,
5 type DesktopPreviewBridge,
6} from "@t3tools/contracts";
7import { afterEach, beforeEach, describe, expect, it, vi } from "vite-plus/test";
8​
9const {
10 captureScreenshot,
11 clientSettings,
12 events,
13 getDisplayMedia,
14 registrySet,
15 requestDisplayMediaCapture,
16 save,
17 startScreencast,
18 stopScreencast,
19} = vi.hoisted(() => {
20 const events: string[] = [];
21 return {
22 captureScreenshot: vi.fn<DesktopPreviewBridge["captureScreenshot"]>(),
23 clientSettings: { browserRecordingFrameRate: 30 as 30 | 60 },
24 events,
25 getDisplayMedia: vi.fn(),
26 requestDisplayMediaCapture: vi.fn((_tabId: string) => undefined),
27 registrySet: vi.fn((_atom: unknown, value: { readonly tabIds: ReadonlySet<string> }) => {
28 events.push(
29 value.tabIds.size === 0 ? "clear" : `publish:${Array.from(value.tabIds).join(",")}`,
30 );
31 }),
32 save: vi.fn(async (tabId: string) => ({
33 id: "recording-test",
34 tabId,
35 path: "/tmp/recording-test.webm",
36 mimeType: "video/webm" as const,
37 sizeBytes: 0,
38 createdAt: "2026-06-26T00:00:00.000Z",
39 })),
40 startScreencast: vi.fn<DesktopPreviewBridge["recording"]["startScreencast"]>(async (_tabId) => {
41 events.push("start-screencast");
42 }),
43 stopScreencast: vi.fn(async () => undefined),
44 };
45});
46​
47vi.mock(import("~/components/preview/previewBridge"), async (original) => {
48 vi.stubGlobal("window", {
49 desktopBridge: {
50 preview: {
51 captureScreenshot,
52 recording: {
53 onFrame: vi.fn(),
54 save,
55 startScreencast: async (tabId: string) => {
56 const result = await startScreencast(tabId);
57 if (result === undefined) requestDisplayMediaCapture(tabId);
58 return result;
59 },
60 stopScreencast,
61 },
62 },
63 },
64 });
65 try {
66 return await original();
67 } finally {
68 vi.unstubAllGlobals();
69 }
70});
71​
72vi.mock("./recordingCompositor", () => ({
73 createRecordingCompositor: async (stream: MediaStream) => ({ stream, dispose: () => {} }),
74}));
75​
76vi.mock("~/rpc/atomRegistry", () => ({
77 appAtomRegistry: { set: registrySet },
78}));
79​
80vi.mock("~/hooks/useSettings", () => ({
81 ensureClientSettingsHydrated: vi.fn(async () => undefined),
82 getClientSettings: () => clientSettings,
83}));
84​
85import {
86 BrowserRecordingConflictError,
87 findActiveBrowserRecordingRuntimeTabId,
88 readActiveBrowserRecordingTabIds,
89 readActiveBrowserRecordingTargets,
90 startBrowserRecording,
91 stopBrowserRecording,
92} from "./browserRecording";
93import { useBrowserSurfaceStore } from "./browserSurfaceStore";
94import { previewRuntimeTabId } from "./previewRuntimeTabId";
95​
96class FakeMediaRecorder {
97 static readonly instances: FakeMediaRecorder[] = [];
98 static supportedTypes = new Set(["video/webm;codecs=vp9"]);
99 static outputMimeType: string | undefined;
100 static stopError: unknown;
101 static isTypeSupported(type: string): boolean {
102 return this.supportedTypes.has(type);
103 }
104​
105 state: RecordingState = "inactive";
106 readonly mimeType: string;
107 readonly stream: MediaStream;
108 readonly options: MediaRecorderOptions | undefined;
109 private readonly listeners = new Map<string, Set<EventListenerOrEventListenerObject>>();
110​
111 constructor(stream: MediaStream, options?: MediaRecorderOptions) {
112 this.stream = stream;
113 this.options = options;
114 this.mimeType =
115 FakeMediaRecorder.outputMimeType ?? options?.mimeType ?? "video/browser-default";
116 FakeMediaRecorder.instances.push(this);
117 }
118​
119 addEventListener(type: string, listener: EventListenerOrEventListenerObject): void {
120 const listeners = this.listeners.get(type) ?? new Set();
121 listeners.add(listener);
122 this.listeners.set(type, listeners);
123 }
124​
125 start(): void {
126 this.state = "recording";
127 }
128​
129 stop(): void {
130 if (FakeMediaRecorder.stopError !== undefined) throw FakeMediaRecorder.stopError;
131 this.state = "inactive";
132 for (const listener of this.listeners.get("stop") ?? []) {
133 if (typeof listener === "function") listener(new Event("stop"));
134 else listener.handleEvent(new Event("stop"));
135 }
136 }
138​
139describe("browser recording", () => {
140 let animationFrameCount = 0;
141​
142 beforeEach(() => {
143 events.length = 0;
144 vi.clearAllMocks();
145 FakeMediaRecorder.instances.length = 0;
146 FakeMediaRecorder.supportedTypes = new Set(["video/webm;codecs=vp9"]);
147 FakeMediaRecorder.outputMimeType = undefined;
148 FakeMediaRecorder.stopError = undefined;
149 clientSettings.browserRecordingFrameRate = 30;
150 animationFrameCount = 0;
151 vi.stubGlobal("window", globalThis);
152 vi.stubGlobal("requestAnimationFrame", (callback: FrameRequestCallback) => {
153 animationFrameCount += 1;
154 callback(animationFrameCount);
155 return animationFrameCount;
156 });
157 vi.stubGlobal("cancelAnimationFrame", vi.fn());
158 vi.stubGlobal("MediaRecorder", FakeMediaRecorder as unknown as typeof MediaRecorder);
159 getDisplayMedia.mockResolvedValue({
160 getVideoTracks: () => [],
161 getTracks: () => [{ stop: vi.fn() }],
162 });
163 requestDisplayMediaCapture.mockImplementation((tabId: string) => {
164 const trigger = Reflect.get(globalThis, DESKTOP_PREVIEW_RECORDING_CAPTURE_TRIGGER);
165 if (typeof trigger !== "function" || trigger(tabId) !== true) {
166 throw new Error(`No pending display-media capture for ${tabId}.`);
167 }
168 });
169 vi.stubGlobal("navigator", { mediaDevices: { getDisplayMedia } });
170 useBrowserSurfaceStore.setState({ activityByTabId: {}, byTabId: {} });
171 });
172​
173 afterEach(() => {
174 vi.useRealTimers();
175 vi.unstubAllGlobals();
176 });
177​
178 it("stops the native stream when MediaRecorder cleanup fails", async () => {
179 const stopTrack = vi.fn();
180 getDisplayMedia.mockResolvedValueOnce({
181 getVideoTracks: () => [],
182 getTracks: () => [{ stop: stopTrack }],
183 });
184​
185 await startBrowserRecording("recording-tab");
186 const cleanupCause = new DOMException("Could not start video source", "NotReadableError");
187 FakeMediaRecorder.stopError = cleanupCause;
188​
189 await expect(stopBrowserRecording("recording-tab")).rejects.toMatchObject({
190 operation: "cleanup",
191 tabId: "recording-tab",
192 message: "Browser recording operation cleanup failed for tab recording-tab.",
193 });
194 expect(stopTrack).toHaveBeenCalledOnce();
195 });
196​
197 it("releases the native capture lease when stream acquisition fails", async () => {
198 const cause = new Error("capture failed");
199 cause.name = "NotReadableError";
200 getDisplayMedia.mockRejectedValueOnce(cause);
201​
202 await expect(startBrowserRecording("recording-tab")).rejects.toMatchObject({
203 operation: "capture-media-stream",
204 tabId: "recording-tab",
205 cause,
206 message: "Browser recording operation capture-media-stream failed for tab recording-tab.",
207 });
208​
209 expect(stopScreencast).toHaveBeenCalledWith("recording-tab");
210 expect(events.at(-1)).toBe("clear");
211 });
212​
213 it("records separate tabs concurrently", async () => {
214 const firstThreadRef = {
215 environmentId: EnvironmentId.make("environment-recording"),
216 threadId: ThreadId.make("thread-recording-first"),
217 };
218 const secondThreadRef = {
219 environmentId: EnvironmentId.make("environment-recording"),
220 threadId: ThreadId.make("thread-recording-second"),
221 };
222 await Promise.all([
223 startBrowserRecording("recording-tab", firstThreadRef),
224 startBrowserRecording("recording-tab-2", secondThreadRef),
225 ]);
226​
227 expect(startScreencast).toHaveBeenCalledTimes(2);
228 expect(events).toContain("publish:recording-tab,recording-tab-2");
229 expect(readActiveBrowserRecordingTabIds()).toEqual(
230 new Set(["recording-tab", "recording-tab-2"]),
231 );
232 expect(readActiveBrowserRecordingTabIds(firstThreadRef)).toEqual(new Set(["recording-tab"]));
233 expect(readActiveBrowserRecordingTabIds(secondThreadRef)).toEqual(new Set(["recording-tab-2"]));
234​
235 await stopBrowserRecording("recording-tab");
236 expect(readActiveBrowserRecordingTabIds()).toEqual(new Set(["recording-tab-2"]));
237 await stopBrowserRecording("recording-tab-2");
238 expect(readActiveBrowserRecordingTabIds()).toEqual(new Set());
239 expect(save).toHaveBeenCalledTimes(2);
240 });
241​
242 it("keeps a recording reachable through its runtime id after a server epoch changes", async () => {
243 const threadRef = {
244 environmentId: EnvironmentId.make("environment-recording"),
245 threadId: ThreadId.make("thread-recording-scoped"),
246 };
247 const runtimeTabId = previewRuntimeTabId(threadRef, "epoch-a", "tab_1");
248 await startBrowserRecording(runtimeTabId, threadRef, "tab_1");
249​
250 expect(startScreencast).toHaveBeenCalledWith(runtimeTabId);
251 expect(readActiveBrowserRecordingTabIds(threadRef)).toEqual(new Set([runtimeTabId]));
252 expect(readActiveBrowserRecordingTargets(threadRef)).toEqual([
253 { runtimeTabId, serverTabId: "tab_1" },
254 ]);
255 expect(findActiveBrowserRecordingRuntimeTabId(threadRef, "tab_1")).toBe(runtimeTabId);
256​
257 const replacementRuntimeTabId = previewRuntimeTabId(threadRef, "epoch-b", "tab_1");
258 await expect(
259 startBrowserRecording(replacementRuntimeTabId, threadRef, "tab_1"),
260 ).rejects.toBeInstanceOf(BrowserRecordingConflictError);
261 expect(startScreencast).toHaveBeenCalledTimes(1);
262​
263 await stopBrowserRecording(runtimeTabId);
264 });
265});