diff --git a/.agents/skills/add-cli-option/SKILL.md b/.agents/skills/add-cli-option/SKILL.md index 7ab390f5a29..1b25c4b4ad0 100644 --- a/.agents/skills/add-cli-option/SKILL.md +++ b/.agents/skills/add-cli-option/SKILL.md @@ -72,6 +72,8 @@ const myFlag = myFlagOption.getValue({commandLine: parsedCli}).value; For Studio options, this is typically in `packages/cli/src/studio.ts`. For render options, in the relevant render command file. +If the option is consumed by Studio, read [`../studio-config-option-lifecycle/SKILL.md`](../studio-config-option-lifecycle/SKILL.md) completely before wiring it. Classify the option as startup-fixed or reloadable across all Studio consumers; mixed behavior is not allowed. If any consumer requires startup-fixed behavior, pass the startup snapshot to every consumer. Add lifecycle tests that prove the classification. + ## 5. Add to Config **`packages/cli/src/config/index.ts`**: diff --git a/.agents/skills/studio-config-option-lifecycle/SKILL.md b/.agents/skills/studio-config-option-lifecycle/SKILL.md new file mode 100644 index 00000000000..709cc40eddb --- /dev/null +++ b/.agents/skills/studio-config-option-lifecycle/SKILL.md @@ -0,0 +1,91 @@ +--- +name: studio-config-option-lifecycle +description: Classify and wire Remotion Studio config options as either startup-fixed or reloadable while preventing mixed lifecycle behavior across consumers. Use when adding, changing, or reviewing a Config setter or CLI option consumed by Studio, its preview server, compiler, HTML bootstrap, public-folder watcher, or render queue. +--- + +# Studio Config Option Lifecycle + +Make reload behavior explicit for every Studio-facing option. A config file is reset and re-executed when it changes, but a consumer only observes the new value if its code reads the option again. + +## Classify the whole option + +Inspect every Studio consumer, then assign one lifecycle to the whole option: + +- **Startup-fixed:** Changing the value requires recreating a server, compiler, watcher, directory mapping, or other initialized resource. +- **Reloadable:** Every Studio consumer can safely use the new value after the browser reload or at another deliberate request boundary. + +If any consumer must be startup-fixed, make the option startup-fixed for all Studio consumers. Do not implement mixed lifecycle behavior. + +Do not infer reloadability from `Config.set*()` state being updated. Config re-execution updates module state regardless of whether an already-created consumer observes it. + +## Wire startup-fixed values + +Resolve the option once in `packages/cli/src/studio.ts` before calling `startStudio()`: + +```ts +const fixedValue = option.getValue({commandLine: parsedCli}).value; + +await StudioServerInternals.startStudio({ + fixedValue, +}); +``` + +Pass the value, not a getter, through `startStudio()`, `startServer()`, and the consumer. Keep new internal parameters required; use `T | null` when absence is valid. + +Capture startup-fixed render settings in `StudioRenderJobFixedConfig` at the Studio queue boundary and thread that object into the job processor. Do not call `option.getValue()` from the processor, because config state may have changed since Studio startup. + +Typical startup-fixed consumers include the Studio port, entry point, active compiler choice and override, polling mode, public directory and watcher, network binding, and cross-site-isolation headers. + +## Wire reloadable values + +Read reloadable options through a getter that retains CLI precedence: + +```ts +const getValue = () => + option.getValue({commandLine: parsedCli}).value; + +await StudioServerInternals.startStudio({ + getValue, +}); +``` + +Pass the getter as a required internal callback and invoke it only at the boundary that should observe config changes, such as generating Studio HTML after the `config-file-changed` browser reload. Do not evaluate the getter earlier and pass its result onward. + +Use the existing `getStudioRuntimeConfig()` path for values already represented by `StudioRuntimeConfig`. Be careful when extending that exported type: adding a required property can be a public API break. For independent HTML bootstrap values, pass a dedicated getter through the internal Studio server layers. + +Only use this pattern when all Studio consumers are reloadable. Typical examples include UI behavior and HTML bootstrap defaults that do not require rebuilding initialized resources. + +## Resolve lifecycle conflicts + +Search all reads of the option and decide each one independently: + +```sh +rg -n "myOption|setMyOption|my-cli-flag" packages +``` + +If the consumers do not all support reloading, capture the option once at Studio startup and pass that same value to every consumer. For example, if the active preview compiler cannot change bundlers, future render jobs must retain the startup bundler choice as well. + +Treat aliases as one option. If a deprecated setter updates multiple underlying values, make every affected Studio consumer follow the stricter startup-fixed lifecycle. + +## Reset and rollback + +Ensure config reload resets the option before executing the changed file, so deleting a setter restores the default. Options registered through `BrowserSafeApis.options` and exposed directly through `Config` are reset by `resetBrowserSafeConfigOptions()`. Add an explicit reset in `ConfigInternals.resetConfigOptions()` for custom module state. + +Preserve transactional reload behavior: an invalid changed config must leave the previous valid configuration active. + +## Test the lifecycle + +Add tests that prove the classification: + +- Reloadable: change the option after the initial read, cross the intended reload/request boundary, and assert the new value is observed. +- Startup-fixed: capture the initial value, change config state, and assert the initialized consumer still receives the original value. +- Cross-consumer: assert every Studio consumer receives the same startup snapshot when any one consumer requires it. +- Reset: omit a previously set option on reload and assert its default is restored. +- Nullable internal inputs: pass `null` explicitly in fixtures and call sites. + +Run focused builds and checks for the affected packages: + +```sh +bunx turbo run make lint formatting --filter='@remotion/cli' --filter='@remotion/studio-server' +bun test packages/cli/src/test/config-reload.test.ts packages/cli/src/test/config-reset.test.ts +``` diff --git a/.agents/skills/studio-config-option-lifecycle/agents/openai.yaml b/.agents/skills/studio-config-option-lifecycle/agents/openai.yaml new file mode 100644 index 00000000000..1654cf8e970 --- /dev/null +++ b/.agents/skills/studio-config-option-lifecycle/agents/openai.yaml @@ -0,0 +1,4 @@ +interface: + display_name: "Studio Config Option Lifecycle" + short_description: "Classify Studio options by reload behavior" + default_prompt: "Use $studio-config-option-lifecycle to wire a Studio config option with explicit reload behavior." diff --git a/packages/cli/src/config/buffer-state-delay-in-milliseconds.ts b/packages/cli/src/config/buffer-state-delay-in-milliseconds.ts index e71a04d8bb1..1a62b7242b0 100644 --- a/packages/cli/src/config/buffer-state-delay-in-milliseconds.ts +++ b/packages/cli/src/config/buffer-state-delay-in-milliseconds.ts @@ -7,3 +7,7 @@ export const getBufferStateDelayInMilliseconds = () => { export const setBufferStateDelayInMilliseconds = (val: number | null) => { value = val; }; + +export const resetBufferStateDelayInMilliseconds = () => { + value = null; +}; diff --git a/packages/cli/src/config/entry-point.ts b/packages/cli/src/config/entry-point.ts index 371b098cc65..748a1e3a65c 100644 --- a/packages/cli/src/config/entry-point.ts +++ b/packages/cli/src/config/entry-point.ts @@ -7,3 +7,7 @@ export const setEntryPoint = (ep: string) => { export const getEntryPoint = () => { return entryPoint; }; + +export const resetEntryPoint = () => { + entryPoint = null; +}; diff --git a/packages/cli/src/config/ffmpeg-override.ts b/packages/cli/src/config/ffmpeg-override.ts index 8bd070f8673..f437290b8f0 100644 --- a/packages/cli/src/config/ffmpeg-override.ts +++ b/packages/cli/src/config/ffmpeg-override.ts @@ -1,6 +1,8 @@ import type {FfmpegOverrideFn} from '@remotion/renderer'; -let ffmpegOverrideFn: FfmpegOverrideFn = ({args}) => args; +const defaultFfmpegOverrideFn: FfmpegOverrideFn = ({args}) => args; + +let ffmpegOverrideFn: FfmpegOverrideFn = defaultFfmpegOverrideFn; export const setFfmpegOverrideFunction = (fn: FfmpegOverrideFn) => { ffmpegOverrideFn = fn; @@ -9,3 +11,7 @@ export const setFfmpegOverrideFunction = (fn: FfmpegOverrideFn) => { export const getFfmpegOverrideFunction = () => { return ffmpegOverrideFn; }; + +export const resetFfmpegOverrideFunction = () => { + ffmpegOverrideFn = defaultFfmpegOverrideFn; +}; diff --git a/packages/cli/src/config/index.ts b/packages/cli/src/config/index.ts index 0bcb1c56b01..1ebed5aff02 100644 --- a/packages/cli/src/config/index.ts +++ b/packages/cli/src/config/index.ts @@ -18,33 +18,42 @@ import {Log} from '../log'; import {getBrowser} from './browser'; import { getBufferStateDelayInMilliseconds, + resetBufferStateDelayInMilliseconds, setBufferStateDelayInMilliseconds, } from './buffer-state-delay-in-milliseconds'; -import {getConcurrency} from './concurrency'; import type {Concurrency} from './concurrency'; -import {getEntryPoint, setEntryPoint} from './entry-point'; +import {getConcurrency} from './concurrency'; +import {getEntryPoint, resetEntryPoint, setEntryPoint} from './entry-point'; import {getDotEnvLocation} from './env-file'; import { getFfmpegOverrideFunction, + resetFfmpegOverrideFunction, setFfmpegOverrideFunction, } from './ffmpeg-override'; import {getShouldOutputImageSequence} from './image-sequence'; -import {getMetadata, setMetadata} from './metadata'; -import {getOutputLocation} from './output-location'; -import {setOutputLocation} from './output-location'; +import {getMetadata, resetMetadata, setMetadata} from './metadata'; +import { + getOutputLocation, + resetOutputLocation, + setOutputLocation, +} from './output-location'; +import type {WebpackOverrideFn} from './override-webpack'; import { defaultOverrideFunction, getWebpackOverrideFn, + overrideWebpackConfig, + resetWebpackOverride, } from './override-webpack'; -import type {WebpackOverrideFn} from './override-webpack'; -import {overrideWebpackConfig} from './override-webpack'; import { getRendererPortFromConfigFile, getRendererPortFromConfigFileAndCliFlag, getStudioPort, + resetPreviewServerPorts, + setPort, + setRendererPort, + setStudioPort, } from './preview-server'; -import {setPort, setRendererPort, setStudioPort} from './preview-server'; -import {getStillFrame, setStillFrame} from './still-frame'; +import {getStillFrame, resetStillFrame, setStillFrame} from './still-frame'; import {getWebpackCaching} from './webpack-caching'; import {getWebpackPolling} from './webpack-poll'; @@ -804,6 +813,69 @@ export const Config: FlatConfig = { setPreviewSampleRate: previewSampleRateOption.setConfig, }; +type BrowserSafeConfigOption = { + cliFlag: string; + getValue: (values: {commandLine: Record}) => { + value: unknown; + source: string; + }; + setConfig: (value: never) => void; + reset?: () => void; +}; + +const getDefaultConfigValue = (option: BrowserSafeConfigOption) => { + for (const cliValue of [undefined, null]) { + const result = option.getValue({ + commandLine: {[option.cliFlag]: cliValue}, + }); + if (result.source !== 'cli') { + return result.value; + } + } + + throw new Error(`Could not determine the default for --${option.cliFlag}`); +}; + +const configSetters = new Set( + Object.values(Object.getOwnPropertyDescriptors(Config)) + .map((descriptor) => descriptor.value) + .filter( + (value): value is (...args: never[]) => unknown => + typeof value === 'function', + ), +); + +const browserSafeConfigOptionResets = Object.values(BrowserSafeApis.options) + .filter((option) => configSetters.has(option.setConfig)) + .map((untypedOption): (() => void) => { + const option = untypedOption as unknown as BrowserSafeConfigOption; + if (option.reset) { + return option.reset; + } + + const defaultValue = getDefaultConfigValue(option); + return () => option.setConfig(defaultValue as never); + }); + +const resetBrowserSafeConfigOptions = () => { + for (const reset of browserSafeConfigOptionResets) { + reset(); + } +}; + +const resetConfigOptions = () => { + resetBrowserSafeConfigOptions(); + StudioServerInternals.resetMaxTimelineTracks(); + resetBufferStateDelayInMilliseconds(); + resetEntryPoint(); + resetFfmpegOverrideFunction(); + resetMetadata(); + resetOutputLocation(); + resetWebpackOverride(); + resetPreviewServerPorts(); + resetStillFrame(); +}; + export const ConfigInternals = { getBrowser, getStudioPort, @@ -825,4 +897,5 @@ export const ConfigInternals = { getWebpackPolling, getBufferStateDelayInMilliseconds, getOutputCodecOrUndefined: BrowserSafeApis.getOutputCodecOrUndefined, + resetConfigOptions, }; diff --git a/packages/cli/src/config/metadata.ts b/packages/cli/src/config/metadata.ts index 55a273a1d43..958a7542ace 100644 --- a/packages/cli/src/config/metadata.ts +++ b/packages/cli/src/config/metadata.ts @@ -7,3 +7,7 @@ export const setMetadata = (metadata: Record): void => { export const getMetadata = (): Record => { return specifiedMetadata; }; + +export const resetMetadata = (): void => { + specifiedMetadata = undefined as unknown as Record; +}; diff --git a/packages/cli/src/config/output-location.ts b/packages/cli/src/config/output-location.ts index 862aa9f1a62..8ce38487b60 100644 --- a/packages/cli/src/config/output-location.ts +++ b/packages/cli/src/config/output-location.ts @@ -17,3 +17,7 @@ export const setOutputLocation = (newOutputLocation: string) => { }; export const getOutputLocation = () => currentOutputLocation; + +export const resetOutputLocation = () => { + currentOutputLocation = null; +}; diff --git a/packages/cli/src/config/override-webpack.ts b/packages/cli/src/config/override-webpack.ts index 95ba6727e3e..e808b8dc3da 100644 --- a/packages/cli/src/config/override-webpack.ts +++ b/packages/cli/src/config/override-webpack.ts @@ -15,3 +15,7 @@ export const overrideWebpackConfig = (fn: WebpackOverrideFn) => { const prevOverride = overrideFn; overrideFn = async (c) => fn(await prevOverride(c)); }; + +export const resetWebpackOverride = () => { + overrideFn = defaultOverrideFunction; +}; diff --git a/packages/cli/src/config/preview-server.ts b/packages/cli/src/config/preview-server.ts index 6b0c42e00bf..bed3214abce 100644 --- a/packages/cli/src/config/preview-server.ts +++ b/packages/cli/src/config/preview-server.ts @@ -60,3 +60,8 @@ export const getRendererPortFromConfigFileAndCliFlag = (): number | null => { portOption.getValue({commandLine: parsedCli}).value ?? rendererPort ?? null ); }; + +export const resetPreviewServerPorts = () => { + studioPort = undefined; + rendererPort = undefined; +}; diff --git a/packages/cli/src/config/still-frame.ts b/packages/cli/src/config/still-frame.ts index b035d374102..9d07fd79ef0 100644 --- a/packages/cli/src/config/still-frame.ts +++ b/packages/cli/src/config/still-frame.ts @@ -12,3 +12,7 @@ export const setStillFrame = (frame: number) => { }; export const getStillFrame = () => stillFrame; + +export const resetStillFrame = () => { + stillFrame = 0; +}; diff --git a/packages/cli/src/get-config-file-name.ts b/packages/cli/src/get-config-file-name.ts index 84278972ae7..07ae7f149ea 100644 --- a/packages/cli/src/get-config-file-name.ts +++ b/packages/cli/src/get-config-file-name.ts @@ -1,7 +1,12 @@ import {existsSync} from 'node:fs'; import path from 'node:path'; import {BrowserSafeApis} from '@remotion/renderer/client'; -import {loadConfigFile} from './load-config'; +import { + executeConfigFile, + loadConfigFile, + prepareConfigFile, +} from './load-config'; +import type {PreparedConfigFile} from './load-config'; import {Log} from './log'; import {parsedCli} from './parsed-cli'; @@ -9,8 +14,29 @@ const {configOption} = BrowserSafeApis.options; const defaultConfigFileJavascript = 'remotion.config.js'; const defaultConfigFileTypescript = 'remotion.config.ts'; +let loadedConfigFile: PreparedConfigFile | null = null; -export const loadConfig = (remotionRoot: string): Promise => { +export const getLoadedConfigFile = () => loadedConfigFile?.resolved ?? null; + +const loadInitialConfigFile = async ( + remotionRoot: string, + configFileName: string, + isJavascript: boolean, +) => { + try { + return await loadConfigFile(remotionRoot, configFileName, isJavascript); + } catch (error) { + Log.error( + {indent: false, logLevel: 'error'}, + error instanceof Error ? error.message : String(error), + ); + process.exit(1); + } +}; + +export const loadConfig = async ( + remotionRoot: string, +): Promise => { const configFile = configOption.getValue({commandLine: parsedCli}).value; if (configFile) { const fullPath = path.resolve(process.cwd(), configFile); @@ -22,20 +48,81 @@ export const loadConfig = (remotionRoot: string): Promise => { process.exit(1); } - return loadConfigFile(remotionRoot, configFile, fullPath.endsWith('.js')); + loadedConfigFile = await loadInitialConfigFile( + remotionRoot, + configFile, + fullPath.endsWith('.js'), + ); + return loadedConfigFile.resolved; } if (remotionRoot === null) { - return Promise.resolve(null); + loadedConfigFile = null; + return null; } if (existsSync(path.resolve(remotionRoot, defaultConfigFileTypescript))) { - return loadConfigFile(remotionRoot, defaultConfigFileTypescript, false); + loadedConfigFile = await loadInitialConfigFile( + remotionRoot, + defaultConfigFileTypescript, + false, + ); + return loadedConfigFile.resolved; } if (existsSync(path.resolve(remotionRoot, defaultConfigFileJavascript))) { - return loadConfigFile(remotionRoot, defaultConfigFileJavascript, true); + loadedConfigFile = await loadInitialConfigFile( + remotionRoot, + defaultConfigFileJavascript, + true, + ); + return loadedConfigFile.resolved; + } + + loadedConfigFile = null; + return null; +}; + +export const reloadConfig = async ({ + resetConfigOptions, +}: { + resetConfigOptions: () => void; +}): Promise => { + if (!loadedConfigFile) { + return false; + } + + const previousConfigFile = loadedConfigFile; + let nextConfigFile: PreparedConfigFile; + + try { + nextConfigFile = await prepareConfigFile( + previousConfigFile.remotionRoot, + previousConfigFile.resolved, + 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; } - return Promise.resolve(null); + resetConfigOptions(); + try { + executeConfigFile(nextConfigFile); + loadedConfigFile = nextConfigFile; + return true; + } 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; + } }; diff --git a/packages/cli/src/get-render-defaults.ts b/packages/cli/src/get-render-defaults.ts index c53cea32a6c..b6d444a0a11 100644 --- a/packages/cli/src/get-render-defaults.ts +++ b/packages/cli/src/get-render-defaults.ts @@ -1,3 +1,4 @@ +import type {LogLevel} from '@remotion/renderer'; import {RenderInternals} from '@remotion/renderer'; import {BrowserSafeApis} from '@remotion/renderer/client'; import type {RenderDefaults} from '@remotion/studio-shared'; @@ -24,7 +25,6 @@ const { encodingMaxRateOption, encodingBufferSizeOption, reproOption, - logLevelOption, delayRenderTimeoutInMillisecondsOption, headlessOption, forSeamlessAacConcatenationOption, @@ -45,11 +45,10 @@ const { sampleRateOption, } = BrowserSafeApis.options; -export const getRenderDefaults = (): RenderDefaults => { +export const getRenderDefaults = (logLevel: LogLevel): RenderDefaults => { const defaultJpegQuality = jpegQualityOption.getValue({ commandLine: parsedCli, }).value; - const logLevel = logLevelOption.getValue({commandLine: parsedCli}).value; const defaultCodec = ConfigInternals.getOutputCodecOrUndefined(); const concurrency = RenderInternals.resolveConcurrency( concurrencyOption.getValue({commandLine: parsedCli}).value, diff --git a/packages/cli/src/load-config.ts b/packages/cli/src/load-config.ts index 09949f96052..c49ee2d436a 100644 --- a/packages/cli/src/load-config.ts +++ b/packages/cli/src/load-config.ts @@ -2,27 +2,25 @@ import fs from 'node:fs'; import path from 'node:path'; import {isMainThread} from 'node:worker_threads'; import {BundlerInternals} from '@remotion/bundler'; -import {Log} from './log'; -export const loadConfigFile = async ( +export type PreparedConfigFile = { + code: string; + remotionRoot: string; + resolved: string; +}; + +export const prepareConfigFile = async ( remotionRoot: string, configFileName: string, isJavascript: boolean, -): Promise => { +): Promise => { const resolved = path.resolve(remotionRoot, configFileName); const tsconfigJson = path.join(remotionRoot, 'tsconfig.json'); if (!isJavascript && !fs.existsSync(tsconfigJson)) { - Log.error( - {indent: false, logLevel: 'error'}, - 'Could not find a tsconfig.json file in your project. Did you delete it? Create a tsconfig.json in the root of your project. Copy the default file from https://github.com/remotion-dev/template-helloworld/blob/main/tsconfig.json.', + throw new Error( + `Could not find a tsconfig.json file in your project. Did you delete it? Create a tsconfig.json in the root of your project. Copy the default file from https://github.com/remotion-dev/template-helloworld/blob/main/tsconfig.json. The root directory is: ${remotionRoot}`, ); - Log.error( - {indent: false, logLevel: 'error'}, - 'The root directory is:', - remotionRoot, - ); - process.exit(1); } const virtualOutfile = 'bundle.js'; @@ -38,28 +36,25 @@ export const loadConfigFile = async ( packages: 'external', }); if (result.errors.length > 0) { - Log.error( - {indent: false, logLevel: 'error'}, - 'Error in remotion.config.ts file', + throw new Error( + `Error in remotion.config.ts file: ${result.errors + .map((error) => error.text) + .join('\n')}`, ); - for (const err in result.errors) { - Log.error({indent: false, logLevel: 'error'}, err); - } - - process.exit(1); } const firstOutfile = result.outputFiles[0]; if (!firstOutfile) { - Log.error( - {indent: false, logLevel: 'error'}, - 'No output files found in the config file.', - ); - process.exit(1); + throw new Error('No output files found in the config file.'); } - let str = new TextDecoder().decode(firstOutfile.contents); + const code = new TextDecoder().decode(firstOutfile.contents); + return {code, remotionRoot, resolved}; +}; + +export const executeConfigFile = ({code, remotionRoot}: PreparedConfigFile) => { + let str = code; const currentCwd = process.cwd(); @@ -72,13 +67,27 @@ export const loadConfigFile = async ( str = str.replace('@remotion/cli/config', './config'); } - // Exectute the contents of the config file - // eslint-disable-next-line no-eval - eval(str); - - if (isMainThread) { - process.chdir(currentCwd); + try { + // Execute the contents of the config file + // eslint-disable-next-line no-eval + eval(str); + } finally { + if (isMainThread) { + process.chdir(currentCwd); + } } +}; - return resolved; +export const loadConfigFile = async ( + remotionRoot: string, + configFileName: string, + isJavascript: boolean, +): Promise => { + const prepared = await prepareConfigFile( + remotionRoot, + configFileName, + isJavascript, + ); + executeConfigFile(prepared); + return prepared; }; diff --git a/packages/cli/src/render-queue/process-still.ts b/packages/cli/src/render-queue/process-still.ts index d9759e1d8bc..e7774d57ef0 100644 --- a/packages/cli/src/render-queue/process-still.ts +++ b/packages/cli/src/render-queue/process-still.ts @@ -1,15 +1,13 @@ import {BrowserSafeApis} from '@remotion/renderer/client'; import type {JobProgressCallback, RenderJob} from '@remotion/studio-server'; -import {getRendererPortFromConfigFile} from '../config/preview-server'; import {convertEntryPointToServeUrl} from '../convert-entry-point-to-serve-url'; import {parsedCli} from '../parsed-cli'; import {renderStillFlow} from '../render-flows/still'; +import type {StudioRenderJobFixedConfig} from './studio-render-job-fixed-config'; const { - publicDirOption, askAIOption, keyboardShortcutsOption, - rspackOption, browserExecutableOption, bundleCacheOption, } = BrowserSafeApis.options; @@ -20,12 +18,14 @@ export const processStill = async ({ entryPoint, onProgress, addCleanupCallback, + fixedConfig, }: { job: RenderJob; remotionRoot: string; entryPoint: string; onProgress: JobProgressCallback; addCleanupCallback: (label: string, cb: () => void) => void; + fixedConfig: StudioRenderJobFixedConfig; }) => { if (job.type !== 'still') { throw new Error('Expected still job'); @@ -35,9 +35,6 @@ export const processStill = async ({ commandLine: parsedCli, }).value; - const publicDir = publicDirOption.getValue({ - commandLine: parsedCli, - }).value; const askAIEnabled = askAIOption.getValue({commandLine: parsedCli}).value; const keyboardShortcutsEnabled = keyboardShortcutsOption.getValue({ commandLine: parsedCli, @@ -45,7 +42,6 @@ export const processStill = async ({ const shouldCache = bundleCacheOption.getValue({ commandLine: parsedCli, }).value; - const rspack = rspackOption.getValue({commandLine: parsedCli}).value; const fullEntryPoint = convertEntryPointToServeUrl(entryPoint); @@ -64,8 +60,8 @@ export const processStill = async ({ serializedInputPropsWithCustomSchema: job.serializedInputPropsWithCustomSchema, overwrite: true, - port: getRendererPortFromConfigFile(), - publicDir, + port: fixedConfig.rendererPort, + publicDir: fixedConfig.publicDir, puppeteerTimeout: job.delayRenderTimeout, jpegQuality: job.jpegQuality, remainingArgs: [], @@ -88,7 +84,7 @@ export const processStill = async ({ mediaCacheSizeInBytes: job.mediaCacheSizeInBytes, askAIEnabled, keyboardShortcutsEnabled, - rspack, + rspack: fixedConfig.rspack, shouldCache, }); }; diff --git a/packages/cli/src/render-queue/process-video.ts b/packages/cli/src/render-queue/process-video.ts index 6ab36bc37e3..616ee980ac3 100644 --- a/packages/cli/src/render-queue/process-video.ts +++ b/packages/cli/src/render-queue/process-video.ts @@ -1,17 +1,15 @@ import type {LogLevel} from '@remotion/renderer'; import {BrowserSafeApis} from '@remotion/renderer/client'; import type {JobProgressCallback, RenderJob} from '@remotion/studio-server'; -import {getRendererPortFromConfigFile} from '../config/preview-server'; import {convertEntryPointToServeUrl} from '../convert-entry-point-to-serve-url'; import {getCliOptions} from '../get-cli-options'; import {parsedCli} from '../parsed-cli'; import {renderVideoFlow} from '../render-flows/render'; +import type {StudioRenderJobFixedConfig} from './studio-render-job-fixed-config'; const { - publicDirOption, askAIOption, keyboardShortcutsOption, - rspackOption, browserExecutableOption, bundleCacheOption, sampleRateOption, @@ -24,6 +22,7 @@ export const processVideoJob = async ({ onProgress, addCleanupCallback, logLevel, + fixedConfig, }: { job: RenderJob; remotionRoot: string; @@ -31,14 +30,12 @@ export const processVideoJob = async ({ onProgress: JobProgressCallback; addCleanupCallback: (label: string, cb: () => void) => void; logLevel: LogLevel; + fixedConfig: StudioRenderJobFixedConfig; }) => { if (job.type !== 'video' && job.type !== 'sequence') { throw new Error('Expected video job'); } - const publicDir = publicDirOption.getValue({ - commandLine: parsedCli, - }).value; const askAIEnabled = askAIOption.getValue({commandLine: parsedCli}).value; const keyboardShortcutsEnabled = keyboardShortcutsOption.getValue({ commandLine: parsedCli, @@ -55,7 +52,6 @@ export const processVideoJob = async ({ const browserExecutable = browserExecutableOption.getValue({ commandLine: parsedCli, }).value; - const rspack = rspackOption.getValue({commandLine: parsedCli}).value; const sampleRate = job.type === 'video' ? job.sampleRate @@ -78,8 +74,8 @@ export const processVideoJob = async ({ serializedInputPropsWithCustomSchema: job.serializedInputPropsWithCustomSchema, overwrite: true, - port: getRendererPortFromConfigFile(), - publicDir, + port: fixedConfig.rendererPort, + publicDir: fixedConfig.publicDir, puppeteerTimeout: job.delayRenderTimeout, jpegQuality: job.jpegQuality ?? undefined, remainingArgs: [], @@ -133,7 +129,7 @@ export const processVideoJob = async ({ imageSequencePattern: null, askAIEnabled, keyboardShortcutsEnabled, - rspack, + rspack: fixedConfig.rspack, shouldCache, }); }; diff --git a/packages/cli/src/render-queue/queue.ts b/packages/cli/src/render-queue/queue.ts index 6545b4e44db..b77355cfa35 100644 --- a/packages/cli/src/render-queue/queue.ts +++ b/packages/cli/src/render-queue/queue.ts @@ -13,6 +13,7 @@ import {printError} from '../print-error'; import {initialAggregateRenderProgress} from '../progress-types'; import {processStill} from './process-still'; import {processVideoJob} from './process-video'; +import type {StudioRenderJobFixedConfig} from './studio-render-job-fixed-config'; let jobQueue: RenderJobWithCleanup[] = []; @@ -53,6 +54,7 @@ const processJob = async ({ onProgress, addCleanupCallback, logLevel, + fixedConfig, }: { job: RenderJob; remotionRoot: string; @@ -60,6 +62,7 @@ const processJob = async ({ onProgress: JobProgressCallback; addCleanupCallback: (label: string, cb: () => void) => void; logLevel: LogLevel; + fixedConfig: StudioRenderJobFixedConfig; }) => { if (job.type === 'still') { await processStill({ @@ -68,6 +71,7 @@ const processJob = async ({ entryPoint, onProgress, addCleanupCallback, + fixedConfig, }); return; } @@ -80,6 +84,7 @@ const processJob = async ({ onProgress, addCleanupCallback, logLevel, + fixedConfig, }); return; } @@ -92,14 +97,16 @@ export const addJob = ({ entryPoint, remotionRoot, logLevel, + fixedConfig, }: { job: RenderJobWithCleanup; entryPoint: string; remotionRoot: string; logLevel: LogLevel; + fixedConfig: StudioRenderJobFixedConfig; }) => { jobQueue.push(job); - processJobIfPossible({entryPoint, remotionRoot, logLevel}); + processJobIfPossible({entryPoint, remotionRoot, logLevel, fixedConfig}); notifyClientsOfJobUpdate(); }; @@ -135,10 +142,12 @@ const processJobIfPossible = async ({ remotionRoot, entryPoint, logLevel, + fixedConfig, }: { remotionRoot: string; entryPoint: string; logLevel: LogLevel; + fixedConfig: StudioRenderJobFixedConfig; }) => { const runningJob = jobQueue.find((q) => { return q.status === 'running'; @@ -215,6 +224,7 @@ const processJobIfPossible = async ({ jobCleanups.push({label, job: cleanup}); }, logLevel, + fixedConfig, }); Log.info( {indent: false, logLevel}, @@ -288,5 +298,5 @@ const processJobIfPossible = async ({ ); } - processJobIfPossible({remotionRoot, entryPoint, logLevel}); + processJobIfPossible({remotionRoot, entryPoint, logLevel, fixedConfig}); }; diff --git a/packages/cli/src/render-queue/studio-render-job-fixed-config.ts b/packages/cli/src/render-queue/studio-render-job-fixed-config.ts new file mode 100644 index 00000000000..b0ef66f41c3 --- /dev/null +++ b/packages/cli/src/render-queue/studio-render-job-fixed-config.ts @@ -0,0 +1,5 @@ +export type StudioRenderJobFixedConfig = { + readonly publicDir: string | null; + readonly rendererPort: number | null; + readonly rspack: boolean; +}; diff --git a/packages/cli/src/setup-cache.ts b/packages/cli/src/setup-cache.ts index 3fa3121f7a7..08ab6f1753e 100644 --- a/packages/cli/src/setup-cache.ts +++ b/packages/cli/src/setup-cache.ts @@ -280,7 +280,7 @@ export const bundleOnCli = async ({ maxTimelineTracks, bufferStateDelayInMilliseconds, audioLatencyHint, - renderDefaults: getRenderDefaults(), + renderDefaults: getRenderDefaults(logLevel), }); bundlingState = { diff --git a/packages/cli/src/studio.ts b/packages/cli/src/studio.ts index ce32e80a2c4..08b27130ee3 100644 --- a/packages/cli/src/studio.ts +++ b/packages/cli/src/studio.ts @@ -1,9 +1,11 @@ import type {LogLevel} from '@remotion/renderer'; import {BrowserSafeApis} from '@remotion/renderer/client'; import {StudioServerInternals} from '@remotion/studio-server'; +import {chalk} from './chalk'; import {ConfigInternals} from './config'; import {convertEntryPointToServeUrl} from './convert-entry-point-to-serve-url'; import {findEntryPoint} from './entry-point'; +import {getLoadedConfigFile, reloadConfig} from './get-config-file-name'; import {getEnvironmentVariables} from './get-env'; import {getGitSource} from './get-github-repository'; import {getInputProps} from './get-input-props'; @@ -81,6 +83,42 @@ export const studioCommand = async ( StudioServerInternals.createFileWatcherRegistry(), ); + 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; @@ -119,6 +157,7 @@ export const studioCommand = async ( const relativePublicDir = publicDirOption.getValue({ commandLine: parsedCli, }).value; + const rendererPort = ConfigInternals.getRendererPortFromConfigFile(); const enableCrossSiteIsolation = enableCrossSiteIsolationOption.getValue({ commandLine: parsedCli, @@ -156,6 +195,12 @@ export const studioCommand = async ( bufferStateDelayInMilliseconds: ConfigInternals.getBufferStateDelayInMilliseconds(), }); + const getNumberOfAudioTags = () => + numberOfSharedAudioTagsOption.getValue({commandLine: parsedCli}).value; + const getAudioLatencyHint = () => + audioLatencyHintOption.getValue({commandLine: parsedCli}).value; + const getPreviewSampleRate = () => + previewSampleRateOption.getValue({commandLine: parsedCli}).value; const result = await StudioServerInternals.startStudio({ previewEntry: require.resolve('@remotion/studio/previewEntry'), @@ -173,13 +218,19 @@ export const studioCommand = async ( relativePublicDir, webpackOverride: ConfigInternals.getWebpackOverrideFn(), poll: webpackPollOption.getValue({commandLine: parsedCli}).value, - getRenderDefaults, + getRenderDefaults: () => getRenderDefaults(logLevel), getRenderQueue, - numberOfAudioTags: numberOfSharedAudioTagsOption.getValue({ - commandLine: parsedCli, - }).value, + getNumberOfAudioTags, queueMethods: { - addJob, + addJob: (options) => + addJob({ + ...options, + fixedConfig: { + publicDir: relativePublicDir, + rendererPort, + rspack: useRspack, + }, + }), cancelJob, removeJob, }, @@ -188,12 +239,8 @@ export const studioCommand = async ( ConfigInternals.getBufferStateDelayInMilliseconds(), binariesDirectory, forceIPv4: ipv4Option.getValue({commandLine: parsedCli}).value, - audioLatencyHint: audioLatencyHintOption.getValue({ - commandLine: parsedCli, - }).value, - previewSampleRate: previewSampleRateOption.getValue({ - commandLine: parsedCli, - }).value, + getAudioLatencyHint, + getPreviewSampleRate, enableCrossSiteIsolation, askAIEnabled, interactivityEnabled, diff --git a/packages/cli/src/test/config-reload.test.ts b/packages/cli/src/test/config-reload.test.ts new file mode 100644 index 00000000000..9d2dc64ea53 --- /dev/null +++ b/packages/cli/src/test/config-reload.test.ts @@ -0,0 +1,69 @@ +import {afterEach, expect, test} from 'bun:test'; +import {mkdtempSync, rmSync, writeFileSync} from 'node:fs'; +import {createRequire} from 'node:module'; +import {tmpdir} from 'node:os'; +import path from 'node:path'; +import {ConfigInternals} from '../config'; +import {loadConfig, reloadConfig} from '../get-config-file-name'; + +let temporaryDirectory: string | null = null; + +afterEach(() => { + ConfigInternals.resetConfigOptions(); + delete process.env.PATCH_BUN_DEVELOPMENT; + Reflect.deleteProperty(globalThis, 'require'); + if (temporaryDirectory) { + rmSync(temporaryDirectory, {recursive: true}); + temporaryDirectory = null; + } +}); + +const writeConfig = (contents: string) => { + if (!temporaryDirectory) { + throw new Error('Temporary directory was not created'); + } + + writeFileSync(path.join(temporaryDirectory, 'remotion.config.js'), contents); +}; + +test('an invalid config reload keeps the previous configuration', async () => { + process.env.PATCH_BUN_DEVELOPMENT = '1'; + Object.assign(globalThis, { + require: createRequire(path.join(__dirname, '..', 'load-config.ts')), + }); + temporaryDirectory = mkdtempSync(path.join(tmpdir(), 'remotion-config-')); + writeConfig( + `const {Config} = require('@remotion/cli/config'); Config.setStudioPort(4321);`, + ); + + await loadConfig(temporaryDirectory); + expect(ConfigInternals.getStudioPort()).toBe(4321); + + writeConfig( + `const {Config} = require('@remotion/cli/config'); Config.setStudioPort(5678); throw new Error('Invalid config');`, + ); + expect( + await reloadConfig({ + resetConfigOptions: ConfigInternals.resetConfigOptions, + }), + ).toBe(false); + expect(ConfigInternals.getStudioPort()).toBe(4321); + + writeConfig('this is not valid JavaScript }'); + expect( + await reloadConfig({ + resetConfigOptions: ConfigInternals.resetConfigOptions, + }), + ).toBe(false); + expect(ConfigInternals.getStudioPort()).toBe(4321); + + writeConfig( + `const {Config} = require('@remotion/cli/config'); Config.setStudioPort(6789);`, + ); + expect( + await reloadConfig({ + resetConfigOptions: ConfigInternals.resetConfigOptions, + }), + ).toBe(true); + expect(ConfigInternals.getStudioPort()).toBe(6789); +}); diff --git a/packages/cli/src/test/config-reset.test.ts b/packages/cli/src/test/config-reset.test.ts new file mode 100644 index 00000000000..8446978ab61 --- /dev/null +++ b/packages/cli/src/test/config-reset.test.ts @@ -0,0 +1,67 @@ +import {expect, test} from 'bun:test'; +import {BrowserSafeApis} from '@remotion/renderer/client'; +import {StudioServerInternals} from '@remotion/studio-server'; +import {DEFAULT_TIMELINE_TRACKS} from '@remotion/studio-shared'; +import {Config, ConfigInternals} from '../config'; +import {getRenderDefaults} from '../get-render-defaults'; + +test('Studio render defaults keep the startup log level', () => { + ConfigInternals.resetConfigOptions(); + Config.setLogLevel('verbose'); + + expect(getRenderDefaults('warn').logLevel).toBe('warn'); +}); + +test('reset config options restores defaults before reloading config', async () => { + ConfigInternals.resetConfigOptions(); + + Config.setStudioPort(4321); + Config.setMaxTimelineTracks(123); + Config.setChromiumOpenGlRenderer('angle'); + Config.setBufferStateDelayInMilliseconds(200); + Config.overrideWebpackConfig((config) => ({ + ...config, + name: 'first', + })); + Config.overrideWebpackConfig((config) => ({ + ...config, + devtool: 'source-map', + })); + + expect(ConfigInternals.getStudioPort()).toBe(4321); + expect(StudioServerInternals.getMaxTimelineTracks()).toBe(123); + expect( + BrowserSafeApis.options.glOption.getValue({commandLine: {}}).value, + ).toBe('angle'); + expect(ConfigInternals.getBufferStateDelayInMilliseconds()).toBe(200); + expect( + await ConfigInternals.getWebpackOverrideFn()({mode: 'development'}), + ).toEqual({mode: 'development', name: 'first', devtool: 'source-map'}); + + ConfigInternals.resetConfigOptions(); + + expect(ConfigInternals.getStudioPort()).toBeUndefined(); + expect(StudioServerInternals.getMaxTimelineTracks()).toBe( + DEFAULT_TIMELINE_TRACKS, + ); + expect( + BrowserSafeApis.options.glOption.getValue({commandLine: {}}).value, + ).toBeNull(); + expect(ConfigInternals.getBufferStateDelayInMilliseconds()).toBeNull(); + expect( + await ConfigInternals.getWebpackOverrideFn()({mode: 'development'}), + ).toEqual({mode: 'development'}); + expect( + BrowserSafeApis.options.askAIOption.getValue({commandLine: {}}).value, + ).toBe(true); + expect( + BrowserSafeApis.options.jpegQualityOption.getValue({commandLine: {}}).value, + ).toBe(80); + expect( + BrowserSafeApis.options.noOpenOption.getValue({commandLine: {}}).value, + ).toBe(false); + expect( + BrowserSafeApis.options.overwriteOption.getValue({commandLine: {}}, true) + .value, + ).toBe(true); +}); diff --git a/packages/renderer/src/options/image-sequence-pattern.tsx b/packages/renderer/src/options/image-sequence-pattern.tsx index 3adaf2a6294..ef689bc9ec5 100644 --- a/packages/renderer/src/options/image-sequence-pattern.tsx +++ b/packages/renderer/src/options/image-sequence-pattern.tsx @@ -34,5 +34,8 @@ export const imageSequencePatternOption = { setConfig: (pattern: string | null) => { currentImageSequencePattern = pattern; }, + reset: () => { + currentImageSequencePattern = null; + }, id: cliFlag, } satisfies AnyRemotionOption; diff --git a/packages/renderer/src/options/mute.tsx b/packages/renderer/src/options/mute.tsx index 03a706b8057..6665836e604 100644 --- a/packages/renderer/src/options/mute.tsx +++ b/packages/renderer/src/options/mute.tsx @@ -37,5 +37,8 @@ export const mutedOption = { setConfig: () => { mutedState = true; }, + reset: () => { + mutedState = DEFAULT_MUTED_STATE; + }, id: cliFlag, } satisfies AnyRemotionOption; diff --git a/packages/renderer/src/options/no-open.tsx b/packages/renderer/src/options/no-open.tsx index a3bdc4a4131..ef76320c74e 100644 --- a/packages/renderer/src/options/no-open.tsx +++ b/packages/renderer/src/options/no-open.tsx @@ -33,5 +33,8 @@ export const noOpenOption = { setConfig: (shouldOpen: boolean) => { shouldOpenBrowser = shouldOpen; }, + reset: () => { + shouldOpenBrowser = true; + }, id: cliFlag, } satisfies AnyRemotionOption; diff --git a/packages/renderer/src/options/option.ts b/packages/renderer/src/options/option.ts index 39689653b44..969275004eb 100644 --- a/packages/renderer/src/options/option.ts +++ b/packages/renderer/src/options/option.ts @@ -16,6 +16,7 @@ export type RemotionOption = { source: string; }; setConfig: (value: Type) => void; + reset?: () => void; id: string; }; diff --git a/packages/renderer/src/options/override-duration.tsx b/packages/renderer/src/options/override-duration.tsx index a5ab0311395..84ba4aaf064 100644 --- a/packages/renderer/src/options/override-duration.tsx +++ b/packages/renderer/src/options/override-duration.tsx @@ -45,5 +45,8 @@ export const overrideDurationOption = { }); currentDuration = duration; }, + reset: () => { + currentDuration = null; + }, id: cliFlag, } satisfies AnyRemotionOption; diff --git a/packages/renderer/src/options/override-fps.tsx b/packages/renderer/src/options/override-fps.tsx index 927125f0b35..8a531f86b43 100644 --- a/packages/renderer/src/options/override-fps.tsx +++ b/packages/renderer/src/options/override-fps.tsx @@ -39,5 +39,8 @@ export const overrideFpsOption = { validateFps(fps, 'in Config.overrideFps()', false); currentFps = fps; }, + reset: () => { + currentFps = null; + }, id: cliFlag, } satisfies AnyRemotionOption; diff --git a/packages/renderer/src/options/override-height.tsx b/packages/renderer/src/options/override-height.tsx index b49be4230b4..4f276918a01 100644 --- a/packages/renderer/src/options/override-height.tsx +++ b/packages/renderer/src/options/override-height.tsx @@ -39,5 +39,8 @@ export const overrideHeightOption = { validateDimension(height, 'height', 'in Config.overrideHeight()'); currentHeight = height; }, + reset: () => { + currentHeight = null; + }, id: cliFlag, } satisfies AnyRemotionOption; diff --git a/packages/renderer/src/options/override-width.tsx b/packages/renderer/src/options/override-width.tsx index d48d91a7dcb..6db5dbdcf9d 100644 --- a/packages/renderer/src/options/override-width.tsx +++ b/packages/renderer/src/options/override-width.tsx @@ -39,5 +39,8 @@ export const overrideWidthOption = { validateDimension(width, 'width', 'in Config.overrideWidth()'); currentWidth = width; }, + reset: () => { + currentWidth = null; + }, id: cliFlag, } satisfies AnyRemotionOption; diff --git a/packages/renderer/src/options/overwrite.tsx b/packages/renderer/src/options/overwrite.tsx index 2dec202379d..450b270400d 100644 --- a/packages/renderer/src/options/overwrite.tsx +++ b/packages/renderer/src/options/overwrite.tsx @@ -49,5 +49,8 @@ export const overwriteOption = { validate(value); shouldOverwrite = value; }, + reset: () => { + shouldOverwrite = null; + }, id: cliFlag, } satisfies AnyRemotionOption; diff --git a/packages/renderer/src/options/video-codec.tsx b/packages/renderer/src/options/video-codec.tsx index 143ec26088e..14868d04698 100644 --- a/packages/renderer/src/options/video-codec.tsx +++ b/packages/renderer/src/options/video-codec.tsx @@ -178,5 +178,8 @@ export const videoCodecOption = { return {value: DEFAULT_CODEC, source: 'default'}; }, setConfig: setCodec, + reset: () => { + codec = undefined; + }, id: cliFlag, } satisfies AnyRemotionOption; diff --git a/packages/studio-server/src/index.ts b/packages/studio-server/src/index.ts index ce20b57e65a..d9d85d71952 100644 --- a/packages/studio-server/src/index.ts +++ b/packages/studio-server/src/index.ts @@ -49,6 +49,7 @@ import { import {getInstallCommand} from './helpers/install-command'; import { getMaxTimelineTracks, + resetMaxTimelineTracks, setMaxTimelineTracks, } from './max-timeline-tracks'; import { @@ -67,6 +68,7 @@ export const StudioServerInternals = { getPackageManager, getMaxTimelineTracks, setMaxTimelineTracks, + resetMaxTimelineTracks, getLatestRemotionVersion, installFileWatcher, writeFileAndNotifyFileWatchers, diff --git a/packages/studio-server/src/max-timeline-tracks.ts b/packages/studio-server/src/max-timeline-tracks.ts index 767aa014c97..a1613d541cb 100644 --- a/packages/studio-server/src/max-timeline-tracks.ts +++ b/packages/studio-server/src/max-timeline-tracks.ts @@ -33,3 +33,7 @@ export const setMaxTimelineTracks = (maxTracks: number) => { export const getMaxTimelineTracks = () => { return maxTimelineTracks; }; + +export const resetMaxTimelineTracks = () => { + maxTimelineTracks = DEFAULT_TIMELINE_TRACKS; +}; diff --git a/packages/studio-server/src/preview-server/start-server.ts b/packages/studio-server/src/preview-server/start-server.ts index 406be92edc8..d10b2d2ed90 100644 --- a/packages/studio-server/src/preview-server/start-server.ts +++ b/packages/studio-server/src/preview-server/start-server.ts @@ -57,13 +57,13 @@ export const startServer = async (options: { logLevel: LogLevel; getRenderQueue: () => RenderJob[]; getRenderDefaults: () => RenderDefaults; - numberOfAudioTags: number; + getNumberOfAudioTags: () => number; queueMethods: QueueMethods; gitSource: GitSource | null; binariesDirectory: string | null; forceIPv4: boolean; - audioLatencyHint: AudioContextLatencyCategory | null; - previewSampleRate: number | null; + getAudioLatencyHint: () => AudioContextLatencyCategory | null; + getPreviewSampleRate: () => number | null; enableCrossSiteIsolation: boolean; askAIEnabled: boolean; interactivityEnabled: boolean; @@ -169,12 +169,12 @@ export const startServer = async (options: { logLevel: options.logLevel, getRenderQueue: options.getRenderQueue, getRenderDefaults: options.getRenderDefaults, - numberOfAudioTags: options.numberOfAudioTags, + getNumberOfAudioTags: options.getNumberOfAudioTags, queueMethods: options.queueMethods, gitSource: options.gitSource, binariesDirectory: options.binariesDirectory, - audioLatencyHint: options.audioLatencyHint, - previewSampleRate: options.previewSampleRate, + getAudioLatencyHint: options.getAudioLatencyHint, + getPreviewSampleRate: options.getPreviewSampleRate, enableCrossSiteIsolation: options.enableCrossSiteIsolation, getStudioRuntimeConfig: options.getStudioRuntimeConfig, }); diff --git a/packages/studio-server/src/routes.ts b/packages/studio-server/src/routes.ts index de2ae3641fe..4f14ec39fc9 100644 --- a/packages/studio-server/src/routes.ts +++ b/packages/studio-server/src/routes.ts @@ -297,9 +297,9 @@ const handleFallback = async ({ publicDir, getRenderQueue, getRenderDefaults, - numberOfAudioTags, - audioLatencyHint, - previewSampleRate, + getNumberOfAudioTags, + getAudioLatencyHint, + getPreviewSampleRate, gitSource, logLevel, enableCrossSiteIsolation, @@ -314,9 +314,9 @@ const handleFallback = async ({ getEnvVariables: () => Record; getRenderQueue: () => RenderJob[]; getRenderDefaults: () => RenderDefaults; - numberOfAudioTags: number; - audioLatencyHint: AudioContextLatencyCategory | null; - previewSampleRate: number | null; + getNumberOfAudioTags: () => number; + getAudioLatencyHint: () => AudioContextLatencyCategory | null; + getPreviewSampleRate: () => number | null; gitSource: GitSource | null; logLevel: LogLevel; enableCrossSiteIsolation: boolean; @@ -380,7 +380,7 @@ const handleFallback = async ({ packageManager === 'unknown' ? null : packageManager.startCommand, renderQueue: getRenderQueue(), completedClientRenders: getCompletedClientRenders(), - numberOfAudioTags, + numberOfAudioTags: getNumberOfAudioTags(), publicFiles: getFiles(), includeFavicon: true, title: 'Remotion Studio', @@ -398,8 +398,8 @@ const handleFallback = async ({ packageManager === 'unknown' ? 'unknown' : packageManager.manager, logLevel, mode: 'dev', - audioLatencyHint: audioLatencyHint ?? 'playback', - sampleRate: previewSampleRate, + audioLatencyHint: getAudioLatencyHint() ?? 'playback', + sampleRate: getPreviewSampleRate(), studioRuntimeConfig: getStudioRuntimeConfig(), }), ); @@ -587,12 +587,12 @@ export const handleRoutes = ({ logLevel, getRenderQueue, getRenderDefaults, - numberOfAudioTags, + getNumberOfAudioTags, queueMethods: methods, gitSource, binariesDirectory, - audioLatencyHint, - previewSampleRate, + getAudioLatencyHint, + getPreviewSampleRate, enableCrossSiteIsolation, getStudioRuntimeConfig, }: { @@ -611,12 +611,12 @@ export const handleRoutes = ({ logLevel: LogLevel; getRenderQueue: () => RenderJob[]; getRenderDefaults: () => RenderDefaults; - numberOfAudioTags: number; + getNumberOfAudioTags: () => number; queueMethods: QueueMethods; gitSource: GitSource | null; binariesDirectory: string | null; - audioLatencyHint: AudioContextLatencyCategory | null; - previewSampleRate: number | null; + getAudioLatencyHint: () => AudioContextLatencyCategory | null; + getPreviewSampleRate: () => number | null; enableCrossSiteIsolation: boolean; getStudioRuntimeConfig: () => StudioRuntimeConfig; }): Promise => { @@ -760,11 +760,11 @@ export const handleRoutes = ({ publicDir, getRenderQueue, getRenderDefaults, - numberOfAudioTags, + getNumberOfAudioTags, gitSource, logLevel, - audioLatencyHint, - previewSampleRate, + getAudioLatencyHint, + getPreviewSampleRate, enableCrossSiteIsolation, getStudioRuntimeConfig, }); diff --git a/packages/studio-server/src/start-studio.ts b/packages/studio-server/src/start-studio.ts index e90bafc58d5..58d677252f4 100644 --- a/packages/studio-server/src/start-studio.ts +++ b/packages/studio-server/src/start-studio.ts @@ -45,15 +45,15 @@ export const startStudio = async ({ poll, getRenderDefaults, getRenderQueue, - numberOfAudioTags, + getNumberOfAudioTags, queueMethods, previewEntry, gitSource, bufferStateDelayInMilliseconds, binariesDirectory, forceIPv4, - audioLatencyHint, - previewSampleRate, + getAudioLatencyHint, + getPreviewSampleRate, enableCrossSiteIsolation, askAIEnabled, interactivityEnabled, @@ -78,9 +78,9 @@ export const startStudio = async ({ poll: number | null; getRenderDefaults: () => RenderDefaults; getRenderQueue: () => RenderJob[]; - numberOfAudioTags: number; - audioLatencyHint: AudioContextLatencyCategory | null; - previewSampleRate: number | null; + getNumberOfAudioTags: () => number; + getAudioLatencyHint: () => AudioContextLatencyCategory | null; + getPreviewSampleRate: () => number | null; enableCrossSiteIsolation: boolean; queueMethods: QueueMethods; previewEntry: string; @@ -159,14 +159,14 @@ export const startStudio = async ({ logLevel, getRenderDefaults, getRenderQueue, - numberOfAudioTags, + getNumberOfAudioTags, queueMethods, gitSource, bufferStateDelayInMilliseconds, binariesDirectory, forceIPv4, - audioLatencyHint, - previewSampleRate, + getAudioLatencyHint, + getPreviewSampleRate, enableCrossSiteIsolation, askAIEnabled, interactivityEnabled, diff --git a/packages/studio-server/src/test/file-source-route.test.ts b/packages/studio-server/src/test/file-source-route.test.ts index 2f482ba2a7b..a01fff164c6 100644 --- a/packages/studio-server/src/test/file-source-route.test.ts +++ b/packages/studio-server/src/test/file-source-route.test.ts @@ -68,14 +68,16 @@ test('serves file source from an origin-less GET request', async () => { const response = makeResponse(); await handleRoutes({ - audioLatencyHint: null, binariesDirectory: null, enableCrossSiteIsolation: false, entryPoint: '', + getAudioLatencyHint: () => null, getCurrentInputProps: () => ({}), getEnvVariables: () => ({}), getRenderDefaults: () => ({}) as RenderDefaults, getRenderQueue: () => [], + getNumberOfAudioTags: () => 0, + getPreviewSampleRate: () => null, getStudioRuntimeConfig: () => ({ askAIEnabled: false, bufferStateDelayInMilliseconds: null, @@ -86,10 +88,8 @@ test('serves file source from an origin-less GET request', async () => { gitSource: null, liveEventsServer: noopLiveEventsServer, logLevel: 'info', - numberOfAudioTags: 0, outputHash: '/outputs', outputHashPrefix: '/outputs', - previewSampleRate: null, publicDir: remotionRoot, queueMethods: { addJob: () => undefined, diff --git a/packages/studio-shared/src/event-source-event.ts b/packages/studio-shared/src/event-source-event.ts index f95e94c1949..27976e7a77c 100644 --- a/packages/studio-shared/src/event-source-event.ts +++ b/packages/studio-shared/src/event-source-event.ts @@ -1,7 +1,7 @@ -import type {StaticFile} from 'remotion'; import type { CanUpdateSequencePropsResponse, SequencePropsSubscriptionKey, + StaticFile, } from 'remotion'; import type { CanUpdateDefaultPropsResponse, @@ -25,6 +25,9 @@ export type EventSourceEvent = type: 'new-env-variables'; newEnvVariables: Record; } + | { + type: 'config-file-changed'; + } | { type: 'root-file-changed'; } diff --git a/packages/studio/src/helpers/client-id.tsx b/packages/studio/src/helpers/client-id.tsx index 295a72af79b..f2f03791cb5 100644 --- a/packages/studio/src/helpers/client-id.tsx +++ b/packages/studio/src/helpers/client-id.tsx @@ -68,7 +68,8 @@ export const PreviewServerConnection: React.FC<{ const handleEvent = (newEvent: EventSourceEvent) => { if ( newEvent.type === 'new-input-props' || - newEvent.type === 'new-env-variables' + newEvent.type === 'new-env-variables' || + newEvent.type === 'config-file-changed' ) { reloadUrl(); }