🎥 Make videos programmatically with React
`@remotion/cli`: Apply Studio config changes without reloading (#10073)
Jonny Burgerb14c6b8b58e1
diff --git a/bun.lock b/bun.lockindex 67ffd228df..d58d744cac 100644--- a/bun.lock+++ b/bun.lock@@ -225,6 +225,7 @@"remotiond": "remotiond-cli.js",},"dependencies": {+ "@babel/parser": "7.24.1","@remotion/bundler": "workspace:*","@remotion/media-utils": "workspace:*","@remotion/player": "workspace:*",diff --git a/packages/cli/package.json b/packages/cli/package.jsonindex b87059f2b1..3830616dc2 100644--- a/packages/cli/package.json+++ b/packages/cli/package.json@@ -36,6 +36,7 @@"author": "Jonny Burger <[email protected]>","license": "SEE LICENSE IN LICENSE.md","dependencies": {+ "@babel/parser": "7.24.1","@remotion/bundler": "workspace:*","@remotion/media-utils": "workspace:*","@remotion/player": "workspace:*",diff --git a/packages/cli/src/config-file-change.ts b/packages/cli/src/config-file-change.tsnew file mode 100644index 0000000000..b0ff63d51c--- /dev/null+++ b/packages/cli/src/config-file-change.ts@@ -0,0 +1,327 @@+import {parse} from '@babel/parser';+import type {ConfigFileChangeType} from '@remotion/studio-shared';+import type {Config} from './config';++type ConfigMethodName = {+ [Key in keyof typeof Config]: (typeof Config)[Key] extends (+ ...args: never[]+ ) => unknown+ ? Key+ : never;+}[keyof typeof Config] &+ string;++// Keep this exhaustive so every new Config method must declare its Studio lifecycle.+const configMethodLifecycles = {+ overrideBundlerConfig: 'restart',+ overrideDuration: 'runtime',+ overrideFfmpegCommand: 'runtime',+ overrideFps: 'runtime',+ overrideHeight: 'runtime',+ overrideRspackConfig: 'restart',+ overrideWebpackConfig: 'restart',+ overrideWidth: 'runtime',+ setAllowHtmlInCanvasEnabled: 'runtime',+ setAskAIEnabled: 'runtime',+ setAudioBitrate: 'runtime',+ setAudioCodec: 'runtime',+ setAudioLatencyHint: 'reload',+ setBeepOnFinish: 'runtime',+ setBenchmarkConcurrencies: 'runtime',+ setBenchmarkRuns: 'runtime',+ setBinariesDirectory: 'restart',+ setBrowserExecutable: 'runtime',+ setBufferStateDelayInMilliseconds: 'runtime',+ setBundleOutDir: 'runtime',+ setCachingEnabled: 'runtime',+ setChromeMode: 'runtime',+ setChromiumDarkMode: 'runtime',+ setChromiumDisableWebSecurity: 'runtime',+ setChromiumHeadlessMode: 'runtime',+ setChromiumIgnoreCertificateErrors: 'runtime',+ setChromiumMultiProcessOnLinux: 'runtime',+ setChromiumOpenGlRenderer: 'runtime',+ setChromiumUserAgent: 'runtime',+ setCodec: 'runtime',+ setColorSpace: 'runtime',+ setConcurrency: 'runtime',+ setCrf: 'runtime',+ setDefaultEditor: 'runtime',+ setDelayRenderTimeoutInMilliseconds: 'runtime',+ setDeleteAfter: 'runtime',+ setDisallowParallelEncoding: 'runtime',+ setDotEnvLocation: 'restart',+ setEnableCrossSiteIsolation: 'restart',+ setEnableFolderExpiry: 'runtime',+ setEncodingBufferSize: 'runtime',+ setEncodingMaxRate: 'runtime',+ setEnforceAudioTrack: 'runtime',+ setEntryPoint: 'restart',+ setEveryNthFrame: 'runtime',+ setExperimentalRspackEnabled: 'restart',+ setForSeamlessAacConcatenation: 'runtime',+ setForceNewStudioEnabled: 'restart',+ setFrameRange: 'runtime',+ setGopSize: 'runtime',+ setHardwareAcceleration: 'runtime',+ setIPv4: 'restart',+ setImageFormat: 'runtime',+ setImageSequence: 'runtime',+ setImageSequencePattern: 'runtime',+ setInteractivityEnabled: 'runtime',+ setJpegQuality: 'runtime',+ setKeyboardShortcutsEnabled: 'runtime',+ setLambdaInsights: 'runtime',+ setLevel: 'restart',+ setLogLevel: 'restart',+ setMaxTimelineTracks: 'runtime',+ setMetadata: 'runtime',+ setMuted: 'runtime',+ setNumberOfGifLoops: 'runtime',+ setNumberOfSharedAudioTags: 'reload',+ setOffthreadVideoCacheSizeInBytes: 'runtime',+ setOutputLocation: 'runtime',+ setOverwriteOutput: 'runtime',+ setPixelFormat: 'runtime',+ setPort: 'restart',+ setPreferLosslessAudio: 'runtime',+ setPreviewSampleRate: 'reload',+ setProResProfile: 'runtime',+ setPublicDir: 'restart',+ setPublicLicenseKey: 'runtime',+ setPublicPath: 'runtime',+ setQuality: 'runtime',+ setRendererPort: 'restart',+ setRepro: 'runtime',+ setRspack: 'restart',+ setSampleRate: 'runtime',+ setScale: 'runtime',+ setShouldOpenBrowser: 'restart',+ setStillImageFormat: 'runtime',+ setStudioPort: 'restart',+ setTimeoutInMilliseconds: 'runtime',+ setVideoBitrate: 'runtime',+ setVideoImageFormat: 'runtime',+ setWebpackPollingInMilliseconds: 'restart',+ setX264Preset: 'runtime',+} satisfies Record<ConfigMethodName, ConfigFileChangeType>;++const getConfigMethodsWithLifecycle = (lifecycle: ConfigFileChangeType) => {+ return new Set(+ Object.entries(configMethodLifecycles)+ .filter(([, value]) => value === lifecycle)+ .map(([methodName]) => methodName),+ );+};++const runtimeConfigMethods = getConfigMethodsWithLifecycle('runtime');+const reloadConfigMethods = getConfigMethodsWithLifecycle('reload');++const ignoredAstProperties = new Set([+ 'comments',+ 'end',+ 'errors',+ 'extra',+ 'loc',+ 'start',+]);++const getStaticPropertyName = (node: unknown): string | null => {+ if (!node || typeof node !== 'object') {+ return null;+ }++ const candidate = node as {type?: string; name?: string; value?: unknown};+ if (candidate.type === 'Identifier') {+ return candidate.name ?? null;+ }++ if (candidate.type === 'StringLiteral') {+ return typeof candidate.value === 'string' ? candidate.value : null;+ }++ return null;+};++const getConfigMethodName = (node: unknown): string | null => {+ if (!node || typeof node !== 'object') {+ return null;+ }++ const callExpression = node as {+ type?: string;+ callee?: unknown;+ };+ if (+ callExpression.type !== 'CallExpression' ||+ !callExpression.callee ||+ typeof callExpression.callee !== 'object'+ ) {+ return null;+ }++ const callee = callExpression.callee as {+ type?: string;+ object?: unknown;+ property?: unknown;+ };+ if (callee.type !== 'MemberExpression') {+ return null;+ }++ const methodName = getStaticPropertyName(callee.property);+ if (!methodName || !callee.object || typeof callee.object !== 'object') {+ return null;+ }++ const configObject = callee.object as {+ type?: string;+ property?: unknown;+ name?: string;+ };+ if (+ (configObject.type === 'Identifier' && configObject.name === 'Config') ||+ (configObject.type === 'MemberExpression' &&+ getStaticPropertyName(configObject.property) === 'Config')+ ) {+ return methodName;+ }++ return null;+};++const isConfigRequire = (node: unknown) => {+ if (!node || typeof node !== 'object') {+ return false;+ }++ const declarator = node as {type?: string; init?: unknown};+ if (+ declarator.type !== 'VariableDeclarator' ||+ !declarator.init ||+ typeof declarator.init !== 'object'+ ) {+ return false;+ }++ const init = declarator.init as {+ type?: string;+ callee?: unknown;+ arguments?: unknown[];+ };+ if (+ init.type !== 'CallExpression' ||+ !init.callee ||+ typeof init.callee !== 'object' ||+ (init.callee as {type?: string; name?: string}).type !== 'Identifier' ||+ (init.callee as {type?: string; name?: string}).name !== 'require' ||+ init.arguments?.length !== 1+ ) {+ return false;+ }++ const source = init.arguments[0] as {type?: string; value?: unknown};+ return (+ source?.type === 'StringLiteral' && source.value === '@remotion/cli/config'+ );+};++const makeConfigFingerprint = ({+ code,+ ignoredConfigMethods,+}: {+ code: string;+ ignoredConfigMethods: Set<string>;+}) => {+ const ast = parse(code, {sourceType: 'unambiguous'});+ const omit = Symbol('omit');++ const normalize = (value: unknown): unknown => {+ if (Array.isArray(value)) {+ return value+ .map(normalize)+ .filter((normalizedValue) => normalizedValue !== omit);+ }++ if (!value || typeof value !== 'object') {+ return value;+ }++ const node = value as {+ type?: string;+ declarations?: unknown[];+ expression?: unknown;+ };+ const expressionConfigMethodName = getConfigMethodName(node.expression);+ if (+ node.type === 'ExpressionStatement' &&+ expressionConfigMethodName &&+ ignoredConfigMethods.has(expressionConfigMethodName)+ ) {+ return omit;+ }++ if (+ node.type === 'VariableDeclaration' &&+ node.declarations?.length &&+ node.declarations.every(isConfigRequire)+ ) {+ return omit;+ }++ const configMethodName = getConfigMethodName(value);+ if (configMethodName && ignoredConfigMethods.has(configMethodName)) {+ return {type: 'IgnoredConfigCall'};+ }++ return Object.fromEntries(+ Object.entries(value)+ .filter(([key]) => !ignoredAstProperties.has(key))+ .map(([key, child]) => [key, normalize(child)]),+ );+ };++ return JSON.stringify(normalize(ast));+};++export type ConfigFileFingerprints = {+ reload: string;+ restart: string;+};++export const makeConfigFileFingerprints = (+ code: string,+): ConfigFileFingerprints => {+ return {+ reload: makeConfigFingerprint({+ code,+ ignoredConfigMethods: runtimeConfigMethods,+ }),+ restart: makeConfigFingerprint({+ code,+ ignoredConfigMethods: new Set([+ ...runtimeConfigMethods,+ ...reloadConfigMethods,+ ]),+ }),+ };+};++export const classifyConfigFileChange = ({+ currentCode,+ startupFingerprints,+}: {+ currentCode: string;+ startupFingerprints: ConfigFileFingerprints;+}): ConfigFileChangeType => {+ const currentFingerprints = makeConfigFileFingerprints(currentCode);+ if (currentFingerprints.restart !== startupFingerprints.restart) {+ return 'restart';+ }++ if (currentFingerprints.reload !== startupFingerprints.reload) {+ return 'reload';+ }++ return 'runtime';+};diff --git a/packages/cli/src/get-config-file-name.ts b/packages/cli/src/get-config-file-name.tsindex 77279a5140..5efda0c38c 100644--- a/packages/cli/src/get-config-file-name.ts+++ b/packages/cli/src/get-config-file-name.ts@@ -18,6 +18,7 @@ const defaultConfigFileTypescript = 'remotion.config.ts';let loadedConfigFile: PreparedConfigFile | null = null;export const getLoadedConfigFile = () => loadedConfigFile?.resolved ?? null;+export const getLoadedConfigFileCode = () => loadedConfigFile?.code ?? null;const warnAboutBundlerOverride = () => {const useRspack = rspackOption.getValue({commandLine: parsedCli}).value;@@ -122,13 +123,28 @@ export const loadConfig = async (return null;};-export const reloadConfig = async ({+type ReloadConfigResult<T> =+ | {type: 'success'; value: T}+ | {type: 'error'; errorMessage: string}+ | {type: 'no-config'};++const logConfigReloadError = (errorMessage: string) => {+ Log.error(+ {indent: false, logLevel: 'error'},+ 'Could not reload the Remotion config. Keeping the previous configuration.',+ errorMessage,+ );+};++export const reloadConfig = async <T>({resetConfigOptions,+ getConfigSnapshot,}: {resetConfigOptions: () => void;-}): Promise<boolean> => {+ getConfigSnapshot: (configFileCode: string) => T | Promise<T>;+}): Promise<ReloadConfigResult<T>> => {if (!loadedConfigFile) {- return false;+ return {type: 'no-config'};}const previousConfigFile = loadedConfigFile;@@ -141,28 +157,23 @@ export const reloadConfig = async ({previousConfigFile.resolved.endsWith('.js'),);} catch (error) {- Log.error(- {indent: false, logLevel: 'error'},- 'Could not reload the Remotion config. Keeping the previous configuration.',- error instanceof Error ? error.message : String(error),- );- return false;+ const errorMessage = error instanceof Error ? error.message : String(error);+ logConfigReloadError(errorMessage);+ return {type: 'error', errorMessage};}resetConfigOptions();try {executeConfigFile(nextConfigFile);- loadedConfigFile = nextConfigFile;+ const configSnapshot = await getConfigSnapshot(nextConfigFile.code);warnAboutBundlerOverride();- return true;+ loadedConfigFile = nextConfigFile;+ return {type: 'success', value: configSnapshot};} catch (error) {resetConfigOptions();executeConfigFile(previousConfigFile);- Log.error(- {indent: false, logLevel: 'error'},- 'Could not reload the Remotion config. Keeping the previous configuration.',- error instanceof Error ? error.message : String(error),- );- return false;+ const errorMessage = error instanceof Error ? error.message : String(error);+ logConfigReloadError(errorMessage);+ return {type: 'error', errorMessage};}};diff --git a/packages/cli/src/studio.ts b/packages/cli/src/studio.tsindex 24b6f9ae7f..20b04e8f30 100644--- a/packages/cli/src/studio.ts+++ b/packages/cli/src/studio.ts@@ -1,11 +1,21 @@import type {LogLevel} from '@remotion/renderer';import {BrowserSafeApis} from '@remotion/renderer/client';import {StudioServerInternals} from '@remotion/studio-server';+import {getConfigFileChangeMessage} from '@remotion/studio-shared';import {chalk} from './chalk';import {ConfigInternals} from './config';+import {+ classifyConfigFileChange,+ makeConfigFileFingerprints,+ type ConfigFileFingerprints,+} from './config-file-change';import {convertEntryPointToServeUrl} from './convert-entry-point-to-serve-url';import {findEntryPoint} from './entry-point';-import {getLoadedConfigFile, reloadConfig} from './get-config-file-name';+import {+ getLoadedConfigFile,+ getLoadedConfigFileCode,+ reloadConfig,+} from './get-config-file-name';import {getEnvironmentVariables} from './get-env';import {getGitSource} from './get-github-repository';import {getInputProps} from './get-input-props';@@ -85,41 +95,6 @@ export const studioCommand = async ();const configFile = getLoadedConfigFile();- if (configFile) {- let isReloadingConfig = false;- StudioServerInternals.installFileWatcher({- file: configFile,- existenceOnly: false,- onChange: async () => {- if (isReloadingConfig) {- return;- }-- isReloadingConfig = true;- try {- const configWasReloaded = await reloadConfig({- resetConfigOptions: ConfigInternals.resetConfigOptions,- });- if (!configWasReloaded) {- return;- }-- Log.info(- {indent: false, logLevel},- chalk.blue('Config file changed. Reloading Studio'),- );- StudioServerInternals.waitForLiveEventsListener().then((listener) => {- listener.sendEventToClient({- type: 'config-file-changed',- });- });- } finally {- isReloadingConfig = false;- }- },- });- }-let inputProps = getInputProps((newProps) => {StudioServerInternals.waitForLiveEventsListener().then((listener) => {inputProps = newProps;@@ -195,6 +170,85 @@ export const studioCommand = async (const getDefaultEditor = () =>defaultEditorOption.getValue({commandLine: parsedCli}).value;+ const startupConfigCode = getLoadedConfigFileCode();+ if (configFile && startupConfigCode) {+ let isReloadingConfig = false;+ let startupConfigFingerprints: ConfigFileFingerprints | null = null;+ const sendConfigFileReloadError = (errorMessage: string) => {+ StudioServerInternals.waitForLiveEventsListener().then((listener) => {+ listener.sendEventToClient({+ type: 'config-file-reload-failed',+ errorMessage,+ });+ });+ };++ StudioServerInternals.installFileWatcher({+ file: configFile,+ existenceOnly: false,+ onChange: async () => {+ if (isReloadingConfig) {+ return;+ }++ isReloadingConfig = true;+ try {+ const reloadResult = await reloadConfig({+ resetConfigOptions: ConfigInternals.resetConfigOptions,+ getConfigSnapshot: async (currentConfigCode) => {+ startupConfigFingerprints ??=+ makeConfigFileFingerprints(startupConfigCode);+ const configFileChangeType = classifyConfigFileChange({+ currentCode: currentConfigCode,+ startupFingerprints: startupConfigFingerprints,+ });++ return {+ changeType: configFileChangeType,+ renderDefaults: getRenderDefaults(logLevel),+ studioRuntimeConfig: getStudioRuntimeConfig(),+ editorName: await StudioServerInternals.getEditorName({+ getDefaultEditor,+ logLevel,+ }),+ };+ },+ });+ if (reloadResult.type === 'no-config') {+ return;+ }++ if (reloadResult.type === 'error') {+ sendConfigFileReloadError(reloadResult.errorMessage);+ return;+ }++ const {changeType, renderDefaults, studioRuntimeConfig, editorName} =+ reloadResult.value;+ const message = getConfigFileChangeMessage(changeType);++ Log.info({indent: false, logLevel}, chalk.blue(message));+ StudioServerInternals.waitForLiveEventsListener().then((listener) => {+ listener.sendEventToClient({+ type: 'config-file-changed',+ changeType,+ renderDefaults,+ studioRuntimeConfig,+ editorName,+ });+ });+ } catch (error) {+ const errorMessage =+ error instanceof Error ? error.message : String(error);+ Log.error({indent: false, logLevel: 'error'}, errorMessage);+ sendConfigFileReloadError(errorMessage);+ } finally {+ isReloadingConfig = false;+ }+ },+ });+ }+const result = await StudioServerInternals.startStudio({previewEntry: require.resolve('@remotion/studio/previewEntry'),browserArgs: parsedCli['browser-args'],diff --git a/packages/cli/src/test/config-file-change.test.ts b/packages/cli/src/test/config-file-change.test.tsnew file mode 100644index 0000000000..7f1248ed60--- /dev/null+++ b/packages/cli/src/test/config-file-change.test.ts@@ -0,0 +1,129 @@+import {expect, test} from 'bun:test';+import {mkdtempSync, rmSync, writeFileSync} from 'node:fs';+import {tmpdir} from 'node:os';+import path from 'node:path';+import {+ classifyConfigFileChange,+ makeConfigFileFingerprints,+} from '../config-file-change';+import {prepareConfigFile} from '../load-config';++const prepare = (body: string) => `+"use strict";+var import_config = require("@remotion/cli/config");+${body}+`;++const classify = (startupCode: string, currentCode: string) => {+ return classifyConfigFileChange({+ currentCode,+ startupFingerprints: makeConfigFileFingerprints(startupCode),+ });+};++test('classifies runtime config changes', () => {+ expect(+ classify(+ prepare('import_config.Config.setCodec("h264");'),+ prepare('import_config.Config.setCodec("h265");'),+ ),+ ).toBe('runtime');+ expect(+ classify(+ '"use strict";',+ prepare('import_config.Config.setPublicLicenseKey("license-key");'),+ ),+ ).toBe('runtime');+ expect(+ classify(+ prepare('Config.setInteractivityEnabled(true);'),+ prepare('Config.setInteractivityEnabled(false);'),+ ),+ ).toBe('runtime');+});++test('classifies changes that require a page reload', () => {+ expect(+ classify(+ prepare('import_config.Config.setAudioLatencyHint("playback");'),+ prepare('import_config.Config.setAudioLatencyHint("interactive");'),+ ),+ ).toBe('reload');+});++test('classifies changes that require a Studio restart', () => {+ expect(+ classify(+ prepare('import_config.Config.setRspack(false);'),+ prepare('import_config.Config.setRspack(true);'),+ ),+ ).toBe('restart');+ expect(+ classify('"use strict";\nvar value = 1;', '"use strict";\nvar value = 2;'),+ ).toBe('restart');+ expect(+ classify(+ prepare('import_config.Config.setNumberOfSharedAudioTags(0);'),+ prepare(+ 'import_config.Config.setNumberOfSharedAudioTags(5); import_config.Config.setRspack(true);',+ ),+ ),+ ).toBe('restart');+});++test('compares changes to the original startup config', () => {+ const startup = prepare(+ 'import_config.Config.setNumberOfSharedAudioTags(0);',+ );+ const startupFingerprints = makeConfigFileFingerprints(startup);++ expect(+ classifyConfigFileChange({+ currentCode: prepare(+ 'import_config.Config.setNumberOfSharedAudioTags(5);',+ ),+ startupFingerprints,+ }),+ ).toBe('reload');+ expect(+ classifyConfigFileChange({+ currentCode: startup,+ startupFingerprints,+ }),+ ).toBe('runtime');+});++test('classifies prepared config code', async () => {+ const directory = mkdtempSync(path.join(tmpdir(), 'remotion-config-change-'));+ const configFile = path.join(directory, 'remotion.config.js');+ try {+ writeFileSync(+ configFile,+ `const {Config} = require('@remotion/cli/config'); Config.setCodec('h264');`,+ );+ const startup = await prepareConfigFile(+ directory,+ 'remotion.config.js',+ true,+ );++ writeFileSync(+ configFile,+ `const {Config} = require('@remotion/cli/config'); Config.setCodec('h265');`,+ );+ const current = await prepareConfigFile(+ directory,+ 'remotion.config.js',+ true,+ );++ expect(+ classifyConfigFileChange({+ currentCode: current.code,+ startupFingerprints: makeConfigFileFingerprints(startup.code),+ }),+ ).toBe('runtime');+ } finally {+ rmSync(directory, {recursive: true});+ }+});diff --git a/packages/cli/src/test/config-reload.test.ts b/packages/cli/src/test/config-reload.test.tsindex 5ea14719a4..f99a0dfbf5 100644--- a/packages/cli/src/test/config-reload.test.ts+++ b/packages/cli/src/test/config-reload.test.ts@@ -27,6 +27,12 @@ const writeConfig = (contents: string) => {writeFileSync(path.join(temporaryDirectory, 'remotion.config.js'), contents);};+const reloadTestConfig = () =>+ reloadConfig({+ resetConfigOptions: ConfigInternals.resetConfigOptions,+ getConfigSnapshot: () => null,+ });+test('an invalid config reload keeps the previous configuration', async () => {process.env.PATCH_BUN_DEVELOPMENT = '1';Object.assign(globalThis, {@@ -47,11 +53,25 @@ test('an invalid config reload keeps the previous configuration', async () => {writeConfig(`const {Config} = require('@remotion/cli/config'); Config.setStudioPort(5678); Config.setDefaultEditor('windsurf'); throw new Error('Invalid config');`,);+ expect((await reloadTestConfig()).type).toBe('error');+ expect(ConfigInternals.getStudioPort()).toBe(4321);+ expect(+ BrowserSafeApis.options.defaultEditorOption.getValue({commandLine: {}})+ .value,+ ).toBe('cursor');++ writeConfig(+ `const {Config} = require('@remotion/cli/config'); Config.setStudioPort(5678); Config.setDefaultEditor('windsurf');`,+ );+ const snapshotErrorMessage = 'The derived config snapshot was rejected';expect(await reloadConfig({resetConfigOptions: ConfigInternals.resetConfigOptions,+ getConfigSnapshot: () => {+ throw new Error(snapshotErrorMessage);+ },}),- ).toBe(false);+ ).toEqual({type: 'error', errorMessage: snapshotErrorMessage});expect(ConfigInternals.getStudioPort()).toBe(4321);expect(BrowserSafeApis.options.defaultEditorOption.getValue({commandLine: {}})@@ -59,21 +79,13 @@ test('an invalid config reload keeps the previous configuration', async () => {).toBe('cursor');writeConfig('this is not valid JavaScript }');- expect(- await reloadConfig({- resetConfigOptions: ConfigInternals.resetConfigOptions,- }),- ).toBe(false);+ expect((await reloadTestConfig()).type).toBe('error');expect(ConfigInternals.getStudioPort()).toBe(4321);writeConfig(`const {Config} = require('@remotion/cli/config'); Config.setStudioPort(6789); Config.setDefaultEditor({type: 'custom', name: 'Acme Editor', executable: '/opt/acme/editor', arguments: ['--goto', '%TARGET_PATH%:%LINE_NUMBER%:%COLUMN_NUMBER%']});`,);- expect(- await reloadConfig({- resetConfigOptions: ConfigInternals.resetConfigOptions,- }),- ).toBe(true);+ expect((await reloadTestConfig()).type).toBe('success');expect(ConfigInternals.getStudioPort()).toBe(6789);expect(BrowserSafeApis.options.defaultEditorOption.getValue({commandLine: {}})@@ -88,11 +100,7 @@ test('an invalid config reload keeps the previous configuration', async () => {writeConfig(`const {Config} = require('@remotion/cli/config'); Config.setStudioPort(7890);`,);- expect(- await reloadConfig({- resetConfigOptions: ConfigInternals.resetConfigOptions,- }),- ).toBe(true);+ expect((await reloadTestConfig()).type).toBe('success');expect(BrowserSafeApis.options.defaultEditorOption.getValue({commandLine: {}}).value,@@ -120,11 +128,7 @@ test('warns when the bundler-specific override does not match the selected bundlwriteConfig(`const {Config} = require('@remotion/cli/config'); Config.setRspack(false); Config.overrideRspackConfig((config) => config);`,);- expect(- await reloadConfig({- resetConfigOptions: ConfigInternals.resetConfigOptions,- }),- ).toBe(true);+ expect((await reloadTestConfig()).type).toBe('success');expect(warn.mock.calls.flat().join(' ')).toContain('You have selected Webpack as the bundler, but Config.overrideRspackConfig() was called. The Rspack override will be ignored. Use Config.overrideWebpackConfig() or Config.overrideBundlerConfig() instead.',);@@ -133,22 +137,14 @@ test('warns when the bundler-specific override does not match the selected bundlwriteConfig(`const {Config} = require('@remotion/cli/config'); Config.setRspack(true); Config.overrideRspackConfig((config) => config); Config.overrideBundlerConfig((config) => config);`,);- expect(- await reloadConfig({- resetConfigOptions: ConfigInternals.resetConfigOptions,- }),- ).toBe(true);+ expect((await reloadTestConfig()).type).toBe('success');expect(warn.mock.calls.length).toBe(0);warn.mockClear();writeConfig(`const {Config} = require('@remotion/cli/config'); Config.setRspack(false); Config.overrideWebpackConfig((config) => config); Config.overrideBundlerConfig((config) => config);`,);- expect(- await reloadConfig({- resetConfigOptions: ConfigInternals.resetConfigOptions,- }),- ).toBe(true);+ expect((await reloadTestConfig()).type).toBe('success');expect(warn.mock.calls.length).toBe(0);} finally {warn.mockRestore();diff --git a/packages/studio-server/src/index.ts b/packages/studio-server/src/index.tsindex 0cb9c61ab2..765f8d0f3d 100644--- a/packages/studio-server/src/index.ts+++ b/packages/studio-server/src/index.ts@@ -62,6 +62,7 @@ import {lockFilePaths,} from './preview-server/get-package-manager';import {waitForLiveEventsListener} from './preview-server/live-events';+import {getEditorName} from './preview-server/routes/open-in-editor';import {getRemotionVersion} from './preview-server/update-available';import {remotionSkillNames} from './remotion-skill-names';import {startStudio} from './start-studio';@@ -107,4 +108,5 @@ export const StudioServerInternals = {detectOutdatedRemotionSkills,parseRemotionSkillVersion,remotionSkillNames,+ getEditorName,};diff --git a/packages/studio-shared/src/config-file-change.ts b/packages/studio-shared/src/config-file-change.tsnew file mode 100644index 0000000000..93ca8dbedc--- /dev/null+++ b/packages/studio-shared/src/config-file-change.ts@@ -0,0 +1,15 @@+export type ConfigFileChangeType = 'runtime' | 'reload' | 'restart';++export const getConfigFileChangeMessage = (+ changeType: ConfigFileChangeType,+): string => {+ if (changeType === 'restart') {+ return 'Restart Studio to apply config file changes';+ }++ if (changeType === 'reload') {+ return 'Reload page to apply config file changes';+ }++ return 'Config file changed';+};diff --git a/packages/studio-shared/src/event-source-event.ts b/packages/studio-shared/src/event-source-event.tsindex 15d4e021c8..e0c55acc03 100644--- a/packages/studio-shared/src/event-source-event.ts+++ b/packages/studio-shared/src/event-source-event.ts@@ -7,8 +7,11 @@ import type {CanUpdateDefaultPropsResponse,ElementInstallRequest,} from './api-requests';+import type {ConfigFileChangeType} from './config-file-change';import type {HotMiddlewareMessage} from './hot-middleware';+import type {RenderDefaults} from './render-defaults';import type {CompletedClientRender, RenderJob} from './render-job';+import type {StudioRuntimeConfig} from './studio-runtime-config';export type EventSourceEvent =| {@@ -27,6 +30,14 @@ export type EventSourceEvent =}| {type: 'config-file-changed';+ changeType: ConfigFileChangeType;+ renderDefaults: RenderDefaults;+ studioRuntimeConfig: StudioRuntimeConfig;+ editorName: string | null;+ }+ | {+ type: 'config-file-reload-failed';+ errorMessage: string;}| {type: 'root-file-changed';diff --git a/packages/studio-shared/src/index.ts b/packages/studio-shared/src/index.tsindex 0eef3344ac..9c768432a7 100644--- a/packages/studio-shared/src/index.ts+++ b/packages/studio-shared/src/index.ts@@ -185,6 +185,10 @@ export {type EffectPropClipboardDataParseResult,} from './effect-clipboard-data';export {EventSourceEvent} from './event-source-event';+export {+ getConfigFileChangeMessage,+ type ConfigFileChangeType,+} from './config-file-change';export {formatBytes} from './format-bytes';export {getAllSchemaKeys, getAssetSchemaKeys} from './get-all-keys';export {getDefaultOutLocation} from './get-default-out-name';diff --git a/packages/studio-shared/src/test/config-file-change.test.ts b/packages/studio-shared/src/test/config-file-change.test.tsnew file mode 100644index 0000000000..1569dbe538--- /dev/null+++ b/packages/studio-shared/src/test/config-file-change.test.ts@@ -0,0 +1,12 @@+import {expect, test} from 'bun:test';+import {getConfigFileChangeMessage} from '../config-file-change';++test('returns the config file change messages', () => {+ expect(getConfigFileChangeMessage('runtime')).toBe('Config file changed');+ expect(getConfigFileChangeMessage('reload')).toBe(+ 'Reload page to apply config file changes',+ );+ expect(getConfigFileChangeMessage('restart')).toBe(+ 'Restart Studio to apply config file changes',+ );+});diff --git a/packages/studio/src/components/Editor.tsx b/packages/studio/src/components/Editor.tsxindex 0b35a1483e..6c21000afb 100644--- a/packages/studio/src/components/Editor.tsx+++ b/packages/studio/src/components/Editor.tsx@@ -1,6 +1,7 @@import {PlayerInternals} from '@remotion/player';import React, {useCallback, useMemo, useState} from 'react';import {Internals} from 'remotion';+import {useStudioConfigRevision} from '../helpers/client-id';import {BACKGROUND} from '../helpers/colors';import {noop} from '../helpers/noop';import {getStudioCurrentScaleContext} from '../helpers/studio-fit-padding';@@ -30,6 +31,7 @@ export const Editor: React.FC<{readonly Root: React.FC;readonly readOnlyStudio: boolean;}> = ({Root, readOnlyStudio}) => {+ useStudioConfigRevision();const [drawElement, setDrawElement] = useState<HTMLDivElement | null>(null);const size = PlayerInternals.useElementSize(drawElement, {triggerOnWindowResize: false,diff --git a/packages/studio/src/components/PreviewToolbarOverflowButton.tsx b/packages/studio/src/components/PreviewToolbarOverflowButton.tsxindex 2fbf28a22d..154bd867d1 100644--- a/packages/studio/src/components/PreviewToolbarOverflowButton.tsx+++ b/packages/studio/src/components/PreviewToolbarOverflowButton.tsx@@ -36,6 +36,7 @@ export const PreviewToolbarOverflowButton: React.FC<{loop,setLoop,}) => {+ const keyboardShortcutsDisabled = areKeyboardShortcutsDisabled();const {checkerboard, setCheckerboard} = useContext(CheckerboardContext);const {editorShowOutlines, setEditorShowOutlines} = useContext(EditorShowOutlinesContext,@@ -127,7 +128,7 @@ export const PreviewToolbarOverflowButton: React.FC<{label: 'Transparency as checkerboard',value: 'checkerboard',onClick: () => setCheckerboard((current) => !current),- keyHint: areKeyboardShortcutsDisabled() ? null : 'T',+ keyHint: keyboardShortcutsDisabled ? null : 'T',leftItem: checkerboard ? <Checkmark /> : null,subMenu: null,quickSwitcherLabel: null,@@ -152,7 +153,7 @@ export const PreviewToolbarOverflowButton: React.FC<{label: 'Fullscreen',value: 'fullscreen',onClick: () => clickButton('fullscreen-toggle'),- keyHint: areKeyboardShortcutsDisabled() ? null : 'F',+ keyHint: keyboardShortcutsDisabled ? null : 'F',leftItem: null,subMenu: null,quickSwitcherLabel: null,@@ -176,6 +177,7 @@ export const PreviewToolbarOverflowButton: React.FC<{setEditorShowOutlines,setLoop,zoomable,+ keyboardShortcutsDisabled,]);if (values.length === 0) {diff --git a/packages/studio/src/helpers/client-id.tsx b/packages/studio/src/helpers/client-id.tsxindex 026c0616c3..9ac92c0b2b 100644--- a/packages/studio/src/helpers/client-id.tsx+++ b/packages/studio/src/helpers/client-id.tsx@@ -1,4 +1,7 @@-import type {EventSourceEvent} from '@remotion/studio-shared';+import {+ getConfigFileChangeMessage,+ type EventSourceEvent,+} from '@remotion/studio-shared';import React, {useCallback, useEffect, useMemo, useRef} from 'react';import type {WatchRemotionStaticFilesPayload} from 'remotion';import {Internals} from 'remotion';@@ -14,6 +17,7 @@ import {reloadUrl} from './url-state';type Context = {previewServerState: PreviewServerConnectionState;+ configFileChangeRevision: number;subscribeToEvent: (type: EventSourceEvent['type'],listener: (event: EventSourceEvent) => void,@@ -24,6 +28,7 @@ export const StudioServerConnectionCtx = React.createContext<Context>({previewServerState: {type: 'init',},+ configFileChangeRevision: 0,subscribeToEvent: () => {throw new Error('Context not initalized');},@@ -64,17 +69,30 @@ export const PreviewServerConnection: React.FC<{const [state, setState] = React.useState<PreviewServerConnectionState>({type: 'init',});+ const [configFileChangeRevision, setConfigFileChangeRevision] =+ React.useState(0);useEffect(() => {const handleEvent = (newEvent: EventSourceEvent) => {if (newEvent.type === 'new-input-props' ||- newEvent.type === 'new-env-variables' ||- newEvent.type === 'config-file-changed'+ newEvent.type === 'new-env-variables') {reloadUrl();}+ if (newEvent.type === 'config-file-changed') {+ window.remotion_renderDefaults = newEvent.renderDefaults;+ window.remotion_studioConfig = newEvent.studioRuntimeConfig;+ window.remotion_editorName = newEvent.editorName;+ setConfigFileChangeRevision((revision) => revision + 1);+ showNotification(getConfigFileChangeMessage(newEvent.changeType), 4000);+ }++ if (newEvent.type === 'config-file-reload-failed') {+ showNotification(newEvent.errorMessage, 4000);+ }+if (newEvent.type === 'init') {latestUndoRedoEvent.current = {type: 'undo-redo-stack-changed',@@ -144,9 +162,10 @@ export const PreviewServerConnection: React.FC<{const context: Context = useMemo(() => {return {previewServerState: state,+ configFileChangeRevision,subscribeToEvent,};- }, [state, subscribeToEvent]);+ }, [configFileChangeRevision, state, subscribeToEvent]);return (<StudioServerConnectionCtx.Provider value={context}>@@ -154,3 +173,7 @@ export const PreviewServerConnection: React.FC<{</StudioServerConnectionCtx.Provider>);};++export const useStudioConfigRevision = () => {+ return React.useContext(StudioServerConnectionCtx).configFileChangeRevision;+};diff --git a/packages/studio/src/helpers/use-menu-structure.tsx b/packages/studio/src/helpers/use-menu-structure.tsxindex 04ba4adaaf..bd0f7c34b4 100644--- a/packages/studio/src/helpers/use-menu-structure.tsx+++ b/packages/studio/src/helpers/use-menu-structure.tsx@@ -55,11 +55,13 @@ const ICON_SIZE = 14;const getFileMenu = ({readOnlyStudio,closeMenu,+ editorName,previewServerState,setSelectedModal,}: {readOnlyStudio: boolean;closeMenu: () => void;+ editorName: string | null;previewServerState: 'connected' | 'init' | 'disconnected';setSelectedModal: (value: React.SetStateAction<ModalState | null>) => void;}) => {@@ -176,11 +178,11 @@ const getFileMenu = ({id: 'open-project-divider',}: null,- window.remotion_editorName && !readOnlyStudio+ editorName && !readOnlyStudio? {id: 'open-in-editor',value: 'open-in-editor',- label: `Open in ${window.remotion_editorName}`,+ label: `Open in ${editorName}`,onClick: async () => {await openInEditor({@@ -194,19 +196,13 @@ const getFileMenu = ({).then(({success}) => {if (!success) {- showNotification(- `Could not open ${window.remotion_editorName}`,- 2000,- );+ showNotification(`Could not open ${editorName}`, 2000);}}).catch((err) => {// eslint-disable-next-line no-consoleconsole.error(err);- showNotification(- `Could not open ${window.remotion_editorName}`,- 2000,- );+ showNotification(`Could not open ${editorName}`, 2000);});},type: 'item' as const,@@ -339,6 +335,9 @@ export const useMenuStructure = (Internals.CompositionManager,);const {type} = useContext(StudioServerConnectionCtx).previewServerState;+ const editorName = window.remotion_editorName;+ const keyboardShortcutsDisabled = areKeyboardShortcutsDisabled();+ const studioAskAIEnabled = getStudioAskAIEnabled();const canConfigureDefaultEditor =!readOnlyStudio &&type === 'connected' &&@@ -515,6 +514,7 @@ export const useMenuStructure = (getFileMenu({readOnlyStudio,closeMenu,+ editorName,previewServerState: type,setSelectedModal,}),@@ -605,7 +605,7 @@ export const useMenuStructure = (},{id: 'enable-snapping',- keyHint: areKeyboardShortcutsDisabled() ? null : 'Shift+M',+ keyHint: keyboardShortcutsDisabled ? null : 'Shift+M',label: 'Enable Snapping',onClick: () => {closeMenu();@@ -902,7 +902,7 @@ export const useMenuStructure = (label: 'Tools',leaveLeftPadding: false,items: [- getStudioAskAIEnabled()+ studioAskAIEnabled? {id: 'ask-ai',value: 'ask-ai',@@ -964,7 +964,7 @@ export const useMenuStructure = ({id: 'shortcuts',value: 'shortcuts',- label: areKeyboardShortcutsDisabled()+ label: keyboardShortcutsDisabled? 'Shortcuts (disabled)': 'Shortcuts',onClick: () => {@@ -982,7 +982,7 @@ export const useMenuStructure = (leftItem: null,subMenu: null,type: 'item' as const,- quickSwitcherLabel: areKeyboardShortcutsDisabled()+ quickSwitcherLabel: keyboardShortcutsDisabled? 'Show all Keyboard Shortcuts (disabled)': 'Show all Keyboard Shortcuts',},@@ -1154,6 +1154,9 @@ export const useMenuStructure = (isFullscreenSupported,remotion_packageManager,mobileLayout,+ editorName,+ keyboardShortcutsDisabled,+ studioAskAIEnabled,size.size,setSize,setEditorZoomGestures,