Skip to content

🎥 Make videos programmatically with React

Elements: Focus Studio tab during installation (#9184)

Igor Samokhovetsd0f427a2d42c
diff --git a/packages/studio-server/src/better-opn/index.ts b/packages/studio-server/src/better-opn/index.ts
index e7b2128cf8..f4cd31230e 100644
--- a/packages/studio-server/src/better-opn/index.ts
+++ b/packages/studio-server/src/better-opn/index.ts
@@ -1,7 +1,6 @@
// Copied from https://github.com/michaellzc/better-opn#readme
-import {exec} from 'node:child_process';
-import type {Writable} from 'stream';
+import {exec, spawn} from 'node:child_process';
import open = require('open');
const supportedChromiumBrowsers = [
@@ -27,6 +26,92 @@ export const getChromiumBrowsersToTry = (processes: string) => {
);
};
+const CHILD_PROCESS_TIMEOUT_IN_MILLISECONDS = 10_000;
+
+const getRunningChromiumBrowsers = async () => {
+ const processes = await new Promise<string>((resolve, reject) => {
+ exec(
+ 'ps -cax -o comm=',
+ {timeout: CHILD_PROCESS_TIMEOUT_IN_MILLISECONDS},
+ (err, stdout) => {
+ if (err) {
+ reject(err);
+ } else {
+ resolve(stdout);
+ }
+ },
+ );
+ });
+
+ return getChromiumBrowsersToTry(processes);
+};
+
+const runAppleScript = ({
+ appleScript,
+ args,
+}: {
+ appleScript: string;
+ args: string[];
+}) => {
+ return new Promise<string>((resolve, reject) => {
+ const proc = spawn('osascript', ['-', ...args]);
+ const stdoutChunks: Uint8Array[] = [];
+ const stderrChunks: Uint8Array[] = [];
+ let settled = false;
+
+ const timeout = setTimeout(() => {
+ if (settled) {
+ return;
+ }
+
+ settled = true;
+ proc.kill();
+ reject(new Error('osascript timed out'));
+ }, CHILD_PROCESS_TIMEOUT_IN_MILLISECONDS);
+
+ const rejectOnce = (error: Error) => {
+ if (settled) {
+ return;
+ }
+
+ settled = true;
+ clearTimeout(timeout);
+ proc.kill();
+ reject(error);
+ };
+
+ proc.stdout.on('data', (chunk: Uint8Array) => stdoutChunks.push(chunk));
+ proc.stderr.on('data', (chunk: Uint8Array) => stderrChunks.push(chunk));
+ proc.stdin.on('error', rejectOnce);
+ proc.on('error', rejectOnce);
+ proc.on('close', (code) => {
+ if (settled) {
+ return;
+ }
+
+ settled = true;
+ clearTimeout(timeout);
+ const stdout = Buffer.concat(stdoutChunks).toString('utf8');
+ if (code === 0) {
+ resolve(stdout);
+ return;
+ }
+
+ const stderr = Buffer.concat(stderrChunks).toString('utf8').trim();
+ reject(new Error(stderr || `osascript exited with code ${code}`));
+ });
+ proc.stdin.end(appleScript);
+ });
+};
+
+const isAppleScriptPermissionError = (error: unknown) => {
+ const message = (error as Error).message.toLowerCase();
+ return (
+ message.includes('not authorised to send apple events') ||
+ message.includes('not authorized to send apple events')
+ );
+};
+
const normalizeURLToMatch = (target: string) => {
// We may encounter URL parse error but want to fallback to default behavior
try {
@@ -40,6 +125,90 @@ const normalizeURLToMatch = (target: string) => {
}
};
+export const getFocusBrowserTabAppleScript = (
+ chromiumBrowser: (typeof supportedChromiumBrowsers)[number],
+) => {
+ return `
+property targetTabIndex: -1
+property targetWindow: null
+property theProgram: "${chromiumBrowser}"
+
+on run argv
+ set targetURL to item 1 of argv
+
+ using terms from application "Google Chrome"
+ tell application theProgram
+ set found to my lookupTabWithUrl(targetURL)
+ if not found then
+ return false
+ end if
+
+ set targetWindow's active tab index to targetTabIndex
+ set index of targetWindow to 1
+ activate
+ return true
+ end tell
+ end using terms from
+end run
+
+on lookupTabWithUrl(lookupUrl)
+ using terms from application "Google Chrome"
+ tell application theProgram
+ set found to false
+ repeat with theWindow in every window
+ set theTabIndex to 0
+ repeat with theTab in every tab of theWindow
+ set theTabIndex to theTabIndex + 1
+ if (theTab's URL as string) is lookupUrl then
+ set targetTabIndex to theTabIndex
+ set targetWindow to theWindow
+ set found to true
+ exit repeat
+ end if
+ end repeat
+
+ if found then
+ exit repeat
+ end if
+ end repeat
+ end tell
+ end using terms from
+ return found
+end lookupTabWithUrl
+`.trim();
+};
+
+export const focusBrowserTab = async ({url}: {url: string}) => {
+ if (process.platform !== 'darwin') {
+ return false;
+ }
+
+ let browsersToTry: ReturnType<typeof getChromiumBrowsersToTry>;
+ try {
+ browsersToTry = await getRunningChromiumBrowsers();
+ } catch {
+ return false;
+ }
+
+ for (const chromiumBrowser of browsersToTry) {
+ try {
+ const result = await runAppleScript({
+ appleScript: getFocusBrowserTabAppleScript(chromiumBrowser),
+ args: [url],
+ });
+ if (result.trim() === 'true') {
+ return true;
+ }
+ } catch (error) {
+ if (isAppleScriptPermissionError(error)) {
+ return false;
+ }
+ }
+ }
+
+ return false;
+};
+
// Copy from
// https://github.com/facebook/create-react-app/blob/master/packages/react-dev-utils/openBrowser.js#L64
const startBrowserProcess = async ({
@@ -62,17 +231,7 @@ const startBrowserProcess = async ({
let appleScriptDenied = false;
// Will use the first open browser found from list
- const processes = await new Promise<string>((resolve, reject) => {
- exec('ps -cax -o comm=', (err, stdout) => {
- if (err) {
- reject(err);
- } else {
- resolve(stdout);
- }
- });
- });
-
- const browsersToTry = getChromiumBrowsersToTry(processes);
+ const browsersToTry = await getRunningChromiumBrowsers();
for (const chromiumBrowser of browsersToTry) {
if (appleScriptDenied) {
@@ -95,8 +254,8 @@ const startBrowserProcess = async ({
property theProgram: "${chromiumBrowser}"
on run argv
- set theURL to "${encodeURI(url)}"
- set matchURL to "${encodeURI(normalizeURLToMatch(url))}"
+ set theURL to item 1 of argv
+ set matchURL to item 2 of argv
using terms from application "Google Chrome"
tell application theProgram
@@ -172,28 +331,14 @@ const startBrowserProcess = async ({
return found
end lookupTabWithUrl
`.trim();
- await new Promise<void>((resolve, reject) => {
- const proc = exec(`osascript -`, (error) => {
- if (error) {
- reject(error);
- } else {
- // Ignore errors.
- // It it breaks, it will fallback to `opn` anyway
- resolve();
- }
- });
- (proc.stdin as Writable).write(appleScript);
- (proc.stdin as Writable).end();
+ await runAppleScript({
+ appleScript,
+ args: [encodeURI(url), encodeURI(normalizeURLToMatch(url))],
});
return Promise.resolve(true);
} catch (error) {
- const appleScriptError = (error as Error).message;
- if (
- appleScriptError
- .toLowerCase()
- .includes('not authorised to send apple events')
- ) {
+ if (isAppleScriptPermissionError(error)) {
appleScriptDenied = true;
}
diff --git a/packages/studio-server/src/preview-server/element-install-state.ts b/packages/studio-server/src/preview-server/element-install-state.ts
index 50f39cf19c..5750e573b4 100644
--- a/packages/studio-server/src/preview-server/element-install-state.ts
+++ b/packages/studio-server/src/preview-server/element-install-state.ts
@@ -8,6 +8,7 @@ export type ElementInstallTarget = {
canInstall: boolean;
lastFocusedAt: number | null;
readOnly: boolean;
+ studioUrl: string;
updatedAt: number;
};
diff --git a/packages/studio-server/src/preview-server/routes/update-element-install-target.ts b/packages/studio-server/src/preview-server/routes/update-element-install-target.ts
index 3106e75688..57644f9cc0 100644
--- a/packages/studio-server/src/preview-server/routes/update-element-install-target.ts
+++ b/packages/studio-server/src/preview-server/routes/update-element-install-target.ts
@@ -12,7 +12,7 @@ const isFiniteTimestamp = (value: number | null) => {
export const updateElementInstallTargetHandler: ApiHandler<
UpdateElementInstallTargetRequest,
UpdateElementInstallTargetResponse
-> = ({input}) => {
+> = ({input, request}) => {
if (typeof input.clientId !== 'string' || input.clientId.length === 0) {
throw new Error('Invalid client ID');
}
@@ -36,6 +36,24 @@ export const updateElementInstallTargetHandler: ApiHandler<
throw new Error('Invalid composition ID');
}
+ if (typeof input.studioUrl !== 'string') {
+ throw new Error('Invalid Studio URL');
+ }
+
+ let studioUrl: URL;
+ try {
+ studioUrl = new URL(input.studioUrl);
+ } catch {
+ throw new Error('Invalid Studio URL');
+ }
+
+ if (
+ typeof request.headers.origin !== 'string' ||
+ studioUrl.origin !== request.headers.origin
+ ) {
+ throw new Error('Studio URL must match the request origin');
+ }
+
updateElementInstallTarget(input);
return Promise.resolve({});
diff --git a/packages/studio-server/src/routes.ts b/packages/studio-server/src/routes.ts
index ef22fc9a69..6ae06f012f 100644
--- a/packages/studio-server/src/routes.ts
+++ b/packages/studio-server/src/routes.ts
@@ -15,6 +15,7 @@ import type {
StudioRuntimeConfig,
} from '@remotion/studio-shared';
import {getProjectName, parseElementDragData} from '@remotion/studio-shared';
+import {focusBrowserTab} from './better-opn';
import {getCompletedClientRenders} from './client-render-queue';
import {getFileSource} from './helpers/get-file-source';
import {getInstalledInstallablePackages} from './helpers/get-installed-installable-packages';
@@ -274,6 +275,8 @@ const handleRequestElementInstall = async ({
return;
}
+ focusBrowserTab({url: target.studioUrl}).catch(() => undefined);
+
response.writeHead(200);
response.end(JSON.stringify({success: true, status: 'sent'}));
} catch (err) {
diff --git a/packages/studio-server/src/test/better-opn.test.ts b/packages/studio-server/src/test/better-opn.test.ts
index ce20dd407c..7c3ef158df 100644
--- a/packages/studio-server/src/test/better-opn.test.ts
+++ b/packages/studio-server/src/test/better-opn.test.ts
@@ -1,5 +1,8 @@
import {expect, test} from 'bun:test';
-import {getChromiumBrowsersToTry} from '../better-opn';
+import {
+ getChromiumBrowsersToTry,
+ getFocusBrowserTabAppleScript,
+} from '../better-opn';
test('matches running Chromium browsers by exact process name', () => {
const processes = `
@@ -25,3 +28,17 @@ Google Chrome Helper
expect(getChromiumBrowsersToTry(processes)).toEqual([]);
});
+
+test('focuses an exact existing tab without reloading or opening one', () => {
+ const appleScript = getFocusBrowserTabAppleScript('Google Chrome');
+
+ expect(appleScript).toContain('set targetURL to item 1 of argv');
+ expect(appleScript).toContain("if (theTab's URL as string) is lookupUrl");
+ expect(appleScript).toContain(
+ "set targetWindow's active tab index to targetTabIndex",
+ );
+ expect(appleScript).toContain('activate');
+ expect(appleScript).not.toContain('reload');
+ expect(appleScript).not.toContain('make new tab');
+ expect(appleScript).not.toContain('make new window');
+});
diff --git a/packages/studio-server/src/test/element-install-state.test.ts b/packages/studio-server/src/test/element-install-state.test.ts
index aaa48b8239..c76d2a2cef 100644
--- a/packages/studio-server/src/test/element-install-state.test.ts
+++ b/packages/studio-server/src/test/element-install-state.test.ts
@@ -16,6 +16,7 @@ test('uses the most recently focused Studio target even when older tabs keep upd
canInstall: true,
lastFocusedAt: 1000,
readOnly: false,
+ studioUrl: 'http://localhost:3000/older-composition',
});
updateElementInstallTarget({
requestId: null,
@@ -25,6 +26,7 @@ test('uses the most recently focused Studio target even when older tabs keep upd
canInstall: true,
lastFocusedAt: 2000,
readOnly: false,
+ studioUrl: 'http://localhost:3000/focused-composition',
});
updateElementInstallTarget({
requestId: null,
@@ -34,9 +36,13 @@ test('uses the most recently focused Studio target even when older tabs keep upd
canInstall: true,
lastFocusedAt: 1000,
readOnly: false,
+ studioUrl: 'http://localhost:3000/older-composition',
});
expect(getElementInstallTarget(null)?.clientId).toBe('focused-tab');
+ expect(getElementInstallTarget(null)?.studioUrl).toBe(
+ 'http://localhost:3000/focused-composition',
+ );
});
test('falls back to update recency when focus timestamps match', async () => {
@@ -50,6 +56,7 @@ test('falls back to update recency when focus timestamps match', async () => {
canInstall: true,
lastFocusedAt: 1000,
readOnly: false,
+ studioUrl: 'http://localhost:3000/first-composition',
});
await new Promise((resolve) => setTimeout(resolve, 2));
@@ -62,6 +69,7 @@ test('falls back to update recency when focus timestamps match', async () => {
canInstall: true,
lastFocusedAt: 1000,
readOnly: false,
+ studioUrl: 'http://localhost:3000/second-composition',
});
expect(getElementInstallTarget(null)?.clientId).toBe('second-tab');
@@ -78,6 +86,7 @@ test('can select a target for a specific request', () => {
canInstall: true,
lastFocusedAt: 1000,
readOnly: false,
+ studioUrl: 'http://localhost:3000/first-composition',
});
updateElementInstallTarget({
requestId: 'second-request',
@@ -87,6 +96,7 @@ test('can select a target for a specific request', () => {
canInstall: true,
lastFocusedAt: 2000,
readOnly: false,
+ studioUrl: 'http://localhost:3000/second-composition',
});
expect(getElementInstallTarget('first-request')?.clientId).toBe('first-tab');
diff --git a/packages/studio-server/src/test/update-element-install-target.test.ts b/packages/studio-server/src/test/update-element-install-target.test.ts
new file mode 100644
index 0000000000..f5adeaace4
--- /dev/null
+++ b/packages/studio-server/src/test/update-element-install-target.test.ts
@@ -0,0 +1,76 @@
+import {beforeEach, expect, test} from 'bun:test';
+import type {IncomingMessage, ServerResponse} from 'node:http';
+import type {UpdateElementInstallTargetRequest} from '@remotion/studio-shared';
+import {
+ clearElementInstallStateForTests,
+ getElementInstallTarget,
+} from '../preview-server/element-install-state';
+import {updateElementInstallTargetHandler} from '../preview-server/routes/update-element-install-target';
+
+const validInput: UpdateElementInstallTargetRequest = {
+ requestId: 'request-id',
+ clientId: 'client-id',
+ compositionFile: '/project/src/composition.tsx',
+ compositionId: 'composition-id',
+ canInstall: true,
+ lastFocusedAt: 1000,
+ readOnly: false,
+ studioUrl: 'http://localhost:3000/composition-id',
+};
+
+const callHandler = ({
+ input,
+ origin,
+}: {
+ input: UpdateElementInstallTargetRequest;
+ origin: string | undefined;
+}) => {
+ return updateElementInstallTargetHandler({
+ binariesDirectory: null,
+ entryPoint: '',
+ input,
+ logLevel: 'info',
+ methods: {
+ addJob: () => undefined,
+ cancelJob: () => undefined,
+ removeJob: () => undefined,
+ },
+ publicDir: '',
+ remotionRoot: '',
+ request: {headers: {origin}} as IncomingMessage,
+ response: {} as ServerResponse,
+ });
+};
+
+beforeEach(() => {
+ clearElementInstallStateForTests();
+});
+
+test('stores a same-origin Studio URL', async () => {
+ await callHandler({
+ input: validInput,
+ origin: 'http://localhost:3000',
+ });
+
+ expect(getElementInstallTarget('request-id')?.studioUrl).toBe(
+ 'http://localhost:3000/composition-id',
+ );
+});
+
+test('rejects an invalid Studio URL', () => {
+ expect(() =>
+ callHandler({
+ input: {...validInput, studioUrl: 'not a URL'},
+ origin: 'http://localhost:3000',
+ }),
+ ).toThrow('Invalid Studio URL');
+});
+
+test('rejects a cross-origin Studio URL', () => {
+ expect(() =>
+ callHandler({
+ input: {...validInput, studioUrl: 'https://attacker.example'},
+ origin: 'http://localhost:3000',
+ }),
+ ).toThrow('Studio URL must match the request origin');
+});
diff --git a/packages/studio-shared/src/api-requests.ts b/packages/studio-shared/src/api-requests.ts
index 933fee1d32..05a346b549 100644
--- a/packages/studio-shared/src/api-requests.ts
+++ b/packages/studio-shared/src/api-requests.ts
@@ -780,6 +780,7 @@ export type UpdateElementInstallTargetRequest = {
canInstall: boolean;
lastFocusedAt: number | null;
readOnly: boolean;
+ studioUrl: string;
};
export type UpdateElementInstallTargetResponse = {};
diff --git a/packages/studio/src/components/Canvas.tsx b/packages/studio/src/components/Canvas.tsx
index 9936f937a2..69219d0847 100644
--- a/packages/studio/src/components/Canvas.tsx
+++ b/packages/studio/src/components/Canvas.tsx
@@ -840,6 +840,7 @@ export const Canvas: React.FC<{
canInstall: canInstallElements,
lastFocusedAt: lastFocusedAtRef.current,
readOnly: window.remotion_isReadOnlyStudio,
+ studioUrl: window.location.href,
}).catch(() => undefined);
},
[