🎥 Make videos programmatically with React
`@remotion/cli`: Add configurable default editor (#9923)
Jonny Burger48e4ef91a60b
diff --git a/packages/cli/src/config/index.ts b/packages/cli/src/config/index.tsindex 9d1906f9c0..a47a76dada 100644--- a/packages/cli/src/config/index.ts+++ b/packages/cli/src/config/index.ts@@ -12,6 +12,7 @@ import type {ColorSpace,Crf,DeleteAfter,+ DefaultEditor,FrameRange,NumberOfGifLoops,StillImageFormat,@@ -120,6 +121,7 @@ const {enableCrossSiteIsolationOption,imageSequencePatternOption,darkModeOption,+ defaultEditorOption,askAIOption,publicLicenseKeyOption,interactivityOption,@@ -614,6 +616,10 @@ type FlatConfig = RemotionConfigObject &* Default: false*/setForceNewStudioEnabled: (forceNew: boolean) => void;+ /**+ * Set the editor used when opening files from Remotion Studio.+ */+ setDefaultEditor: (editor: DefaultEditor) => void;setDeleteAfter: (day: DeleteAfter | null) => void;/**@@ -831,6 +837,7 @@ export const Config: FlatConfig = {setEnableCrossSiteIsolation: enableCrossSiteIsolationOption.setConfig,setAskAIEnabled: askAIOption.setConfig,setPublicLicenseKey: publicLicenseKeyOption.setConfig,+ setDefaultEditor: defaultEditorOption.setConfig,setForceNewStudioEnabled: forceNewStudioOption.setConfig,setIPv4: ipv4Option.setConfig,setBundleOutDir: outDirOption.setConfig,diff --git a/packages/cli/src/parsed-cli.ts b/packages/cli/src/parsed-cli.tsindex ea22cf4cfd..b0bb970eee 100644--- a/packages/cli/src/parsed-cli.ts+++ b/packages/cli/src/parsed-cli.ts@@ -29,6 +29,7 @@ const {publicPathOption,audioLatencyHintOption,darkModeOption,+ defaultEditorOption,publicLicenseKeyOption,forceNewStudioOption,numberOfSharedAudioTagsOption,@@ -95,6 +96,7 @@ export type CommandLineOptions = {typeof ignoreCertificateErrorsOption> | null;[darkModeOption.cliFlag]: TypeOfOption<typeof darkModeOption> | null;+ [defaultEditorOption.cliFlag]: TypeOfOption<typeof defaultEditorOption>;[disableWebSecurityOption.cliFlag]: TypeOfOption<typeof disableWebSecurityOption> | null;diff --git a/packages/cli/src/studio.ts b/packages/cli/src/studio.tsindex a20e3369f7..24b6f9ae7f 100644--- a/packages/cli/src/studio.ts+++ b/packages/cli/src/studio.ts@@ -37,6 +37,7 @@ const {portOption,browserOption,previewSampleRateOption,+ defaultEditorOption,} = BrowserSafeApis.options;export const studioCommand = async (@@ -191,6 +192,8 @@ export const studioCommand = async (audioLatencyHintOption.getValue({commandLine: parsedCli}).value;const getPreviewSampleRate = () =>previewSampleRateOption.getValue({commandLine: parsedCli}).value;+ const getDefaultEditor = () =>+ defaultEditorOption.getValue({commandLine: parsedCli}).value;const result = await StudioServerInternals.startStudio({previewEntry: require.resolve('@remotion/studio/previewEntry'),@@ -232,6 +235,7 @@ export const studioCommand = async (forceIPv4: ipv4Option.getValue({commandLine: parsedCli}).value,getAudioLatencyHint,getPreviewSampleRate,+ getDefaultEditor,enableCrossSiteIsolation,forceNew: forceNewStudioOption.getValue({commandLine: parsedCli}).value,rspack: useRspack,diff --git a/packages/cli/src/test/config-reload.test.ts b/packages/cli/src/test/config-reload.test.tsindex 15a15d0c97..ed2510872a 100644--- a/packages/cli/src/test/config-reload.test.ts+++ b/packages/cli/src/test/config-reload.test.ts@@ -3,6 +3,7 @@ import {mkdtempSync, rmSync, writeFileSync} from 'node:fs';import {createRequire} from 'node:module';import {tmpdir} from 'node:os';import path from 'node:path';+import {BrowserSafeApis} from '@remotion/renderer/client';import {ConfigInternals} from '../config';import {loadConfig, reloadConfig} from '../get-config-file-name';@@ -33,14 +34,18 @@ test('an invalid config reload keeps the previous configuration', async () => {});temporaryDirectory = mkdtempSync(path.join(tmpdir(), 'remotion-config-'));writeConfig(- `const {Config} = require('@remotion/cli/config'); Config.setStudioPort(4321);`,+ `const {Config} = require('@remotion/cli/config'); Config.setStudioPort(4321); Config.setDefaultEditor('cursor');`,);await loadConfig(temporaryDirectory);expect(ConfigInternals.getStudioPort()).toBe(4321);+ expect(+ BrowserSafeApis.options.defaultEditorOption.getValue({commandLine: {}})+ .value,+ ).toBe('cursor');writeConfig(- `const {Config} = require('@remotion/cli/config'); Config.setStudioPort(5678); throw new Error('Invalid config');`,+ `const {Config} = require('@remotion/cli/config'); Config.setStudioPort(5678); Config.setDefaultEditor('windsurf'); throw new Error('Invalid config');`,);expect(await reloadConfig({@@ -48,6 +53,10 @@ test('an invalid config reload keeps the previous configuration', async () => {}),).toBe(false);expect(ConfigInternals.getStudioPort()).toBe(4321);+ expect(+ BrowserSafeApis.options.defaultEditorOption.getValue({commandLine: {}})+ .value,+ ).toBe('cursor');writeConfig('this is not valid JavaScript }');expect(@@ -58,7 +67,7 @@ test('an invalid config reload keeps the previous configuration', async () => {expect(ConfigInternals.getStudioPort()).toBe(4321);writeConfig(- `const {Config} = require('@remotion/cli/config'); Config.setStudioPort(6789);`,+ `const {Config} = require('@remotion/cli/config'); Config.setStudioPort(6789); Config.setDefaultEditor('zed');`,);expect(await reloadConfig({@@ -66,6 +75,23 @@ test('an invalid config reload keeps the previous configuration', async () => {}),).toBe(true);expect(ConfigInternals.getStudioPort()).toBe(6789);+ expect(+ BrowserSafeApis.options.defaultEditorOption.getValue({commandLine: {}})+ .value,+ ).toBe('zed');++ writeConfig(+ `const {Config} = require('@remotion/cli/config'); Config.setStudioPort(7890);`,+ );+ expect(+ await reloadConfig({+ resetConfigOptions: ConfigInternals.resetConfigOptions,+ }),+ ).toBe(true);+ expect(+ BrowserSafeApis.options.defaultEditorOption.getValue({commandLine: {}})+ .value,+ ).toBeNull();});test('warns when the bundler-specific override does not match the selected bundler', async () => {diff --git a/packages/cli/src/test/config-reset.test.ts b/packages/cli/src/test/config-reset.test.tsindex 9791ce10ea..1446816015 100644--- a/packages/cli/src/test/config-reset.test.ts+++ b/packages/cli/src/test/config-reset.test.ts@@ -37,6 +37,7 @@ test('reset config options restores defaults before reloading config', async ()Config.setStudioPort(4321);Config.setMaxTimelineTracks(123);Config.setChromiumOpenGlRenderer('angle');+ Config.setDefaultEditor('cursor');Config.setBufferStateDelayInMilliseconds(200);Config.overrideBundlerConfig((config, {bundler}) => ({...config,@@ -60,6 +61,10 @@ test('reset config options restores defaults before reloading config', async ()expect(BrowserSafeApis.options.glOption.getValue({commandLine: {}}).value,).toBe('angle');+ expect(+ BrowserSafeApis.options.defaultEditorOption.getValue({commandLine: {}})+ .value,+ ).toBe('cursor');expect(ConfigInternals.getBufferStateDelayInMilliseconds()).toBe(200);const sharedWebpackConfig = await ConfigInternals.getBundlerOverrideFn()({mode: 'development'},@@ -96,6 +101,10 @@ test('reset config options restores defaults before reloading config', async ()expect(BrowserSafeApis.options.glOption.getValue({commandLine: {}}).value,).toBeNull();+ expect(+ BrowserSafeApis.options.defaultEditorOption.getValue({commandLine: {}})+ .value,+ ).toBeNull();expect(ConfigInternals.getBufferStateDelayInMilliseconds()).toBeNull();expect(await ConfigInternals.getBundlerOverrideFn()(@@ -124,6 +133,20 @@ test('reset config options restores defaults before reloading config', async ()).toBe(true);});+test('the CLI editor flag takes precedence over Config.setDefaultEditor()', () => {+ ConfigInternals.resetConfigOptions();+ Config.setDefaultEditor('cursor');++ expect(+ BrowserSafeApis.options.defaultEditorOption.getValue({+ commandLine: {editor: 'zed'},+ }),+ ).toEqual({source: 'cli', value: 'zed'});+ expect(() => Config.setDefaultEditor('invalid' as 'cursor')).toThrow(+ 'Config.setDefaultEditor() must be one of',+ );+});+test('bundler overrides can be fixed at Studio startup', async () => {ConfigInternals.resetConfigOptions();Config.overrideBundlerConfig((config) => ({...config, name: 'startup'}));diff --git a/packages/docs/docs/cli/studio.mdx b/packages/docs/docs/cli/studio.mdxindex dac72d11e8..0d8b208a84 100644--- a/packages/docs/docs/cli/studio.mdx+++ b/packages/docs/docs/cli/studio.mdx@@ -57,6 +57,14 @@ Inline JSON string isn't supported on Windows shells because it removes the `"`<Options id="disable-interactivity" />+### `--editor`<AvailableFrom v="4.0.503" />++<Options id="editor" cli />++```sh title="Terminal"+npx remotion studio --editor=cursor+```+### `--rspack`<AvailableFrom v="4.0.502" /><Options id="rspack" />diff --git a/packages/docs/docs/config.mdx b/packages/docs/docs/config.mdxindex dcc88710e3..f4d93ecc17 100644--- a/packages/docs/docs/config.mdx+++ b/packages/docs/docs/config.mdx@@ -227,6 +227,22 @@ Config.setInteractivityEnabled(false);The [command line flag](/docs/cli/studio#--disable-interactivity) `--disable-interactivity` will take precedence over this option.+## `setDefaultEditor()`<AvailableFrom v="4.0.503" />++<Options id="editor" />++```ts twoslash title="remotion.config.ts"+import {Config} from '@remotion/cli/config';+// ---cut---+Config.setDefaultEditor('cursor');+```++The supported editor IDs are `vscode`, `cursor`, `windsurf`, `zed`, `vscodium`, `webstorm`, and `sublime-text`. `vscode` also recognizes VS Code Insiders, and `zed` also recognizes Zed Preview.++The editor is detected from its installation and does not need to be running. If the configured editor is not installed, Remotion prints a warning and falls back to automatic editor detection.++The [command line flag](/docs/cli/studio#--editor) `--editor` will take precedence over this option.+## ~~`setAllowHtmlInCanvasEnabled()`~~<AvailableFrom v="4.0.447" />:::info Deprecateddiff --git a/packages/renderer/src/client.ts b/packages/renderer/src/client.tsindex 3737bd2754..9be8ce1620 100644--- a/packages/renderer/src/client.ts+++ b/packages/renderer/src/client.ts@@ -35,6 +35,8 @@ import {} from './pixel-format';import {validateOutputFilename} from './validate-output-filename';export {AvailableOptions, TypeOfOption} from './options';+export {defaultEditorIds} from './options/default-editor';+export type {DefaultEditor} from './options/default-editor';export {HardwareAccelerationOption} from './options/hardware-acceleration';export {ProResProfile} from './options/prores-profile';diff --git a/packages/renderer/src/index.ts b/packages/renderer/src/index.tsindex bbe1f4465d..64209ac506 100644--- a/packages/renderer/src/index.ts+++ b/packages/renderer/src/index.ts@@ -119,6 +119,8 @@ export type {ChromiumOptions} from './open-browser';export {ChromeMode} from './options/chrome-mode';export {ColorSpace} from './options/color-space';export type {Concurrency} from './options/concurrency';+export {defaultEditorIds} from './options/default-editor';+export type {DefaultEditor} from './options/default-editor';export type {DeleteAfter} from './options/delete-after';export {OpenGlRenderer} from './options/gl';export {NumberOfGifLoops} from './options/number-of-gif-loops';diff --git a/packages/renderer/src/options/default-editor.tsx b/packages/renderer/src/options/default-editor.tsxnew file mode 100644index 0000000000..d1619d8d46--- /dev/null+++ b/packages/renderer/src/options/default-editor.tsx@@ -0,0 +1,68 @@+import type {AnyRemotionOption} from './option';++export const defaultEditorIds = [+ 'vscode',+ 'cursor',+ 'windsurf',+ 'zed',+ 'vscodium',+ 'webstorm',+ 'sublime-text',+] as const;++export type DefaultEditor = (typeof defaultEditorIds)[number];++const cliFlag = 'editor' as const;+let defaultEditor: DefaultEditor | null = null;++const validateDefaultEditor = (+ value: unknown,+ source: string,+): DefaultEditor | null => {+ if (value === null) {+ return null;+ }++ if (+ typeof value !== 'string' ||+ !defaultEditorIds.includes(value as DefaultEditor)+ ) {+ throw new TypeError(+ `${source} must be one of: ${defaultEditorIds.join(', ')}. Received: ${JSON.stringify(value)}`,+ );+ }++ return value as DefaultEditor;+};++export const defaultEditorOption = {+ name: 'Default editor',+ cliFlag,+ description: () => (+ <>+ Set the default editor for opening files from Remotion Studio. Available+ editors: <code>{defaultEditorIds.join(', ')}</code>.+ </>+ ),+ ssrName: null,+ docLink: 'https://www.remotion.dev/docs/config#setdefaulteditor',+ type: null as DefaultEditor | null,+ getValue: ({commandLine}) => {+ const cliValue = commandLine[cliFlag];+ if (cliValue !== undefined && cliValue !== null) {+ return {+ value: validateDefaultEditor(cliValue, `--${cliFlag}`),+ source: 'cli',+ };+ }++ return {+ value: defaultEditor,+ source: 'config',+ };+ },+ setConfig(value) {+ defaultEditor = validateDefaultEditor(value, 'Config.setDefaultEditor()');+ },+ id: cliFlag,+} satisfies AnyRemotionOption<DefaultEditor | null>;diff --git a/packages/renderer/src/options/index.tsx b/packages/renderer/src/options/index.tsxindex 81fc694810..041966d8f5 100644--- a/packages/renderer/src/options/index.tsx+++ b/packages/renderer/src/options/index.tsx@@ -15,6 +15,7 @@ import {configOption} from './config';import {crfOption} from './crf';import {enableCrossSiteIsolationOption} from './cross-site-isolation';import {darkModeOption} from './dark-mode';+import {defaultEditorOption} from './default-editor';import {deleteAfterOption} from './delete-after';import {disableGitSourceOption} from './disable-git-source';import {disableWebSecurityOption} from './disable-web-security';@@ -151,6 +152,7 @@ export const allOptions = {imageSequencePatternOption,mediaCacheSizeInBytesOption,darkModeOption,+ defaultEditorOption,publicLicenseKeyOption,isProductionOption,askAIOption,diff --git a/packages/studio-server/src/helpers/editor-registry.ts b/packages/studio-server/src/helpers/editor-registry.tsnew file mode 100644index 0000000000..57af0efb21--- /dev/null+++ b/packages/studio-server/src/helpers/editor-registry.ts@@ -0,0 +1,640 @@+import {execFile} from 'node:child_process';+import {existsSync} from 'node:fs';+import {homedir} from 'node:os';+import path from 'node:path';+import {promisify} from 'node:util';+import type {DefaultEditor} from '@remotion/renderer';+import {defaultEditorIds} from '@remotion/renderer';++const execFilePromise = promisify(execFile);++export type InstalledEditor = {+ id: DefaultEditor;+ name: string;+ process: string;+ command: string;+};++type DarwinEditorVariant = {+ name: string;+ bundleIdentifiers: readonly string[];+ applicationNames: readonly string[];+ executable: string;+ command: string;+};++type ExecutableEditorVariant = {+ name: string;+ paths: (context: EditorDiscoveryContext) => readonly string[];+ commands: readonly string[];+};++type EditorDefinition = {+ darwin: readonly DarwinEditorVariant[];+ linux: readonly ExecutableEditorVariant[];+ win32: readonly ExecutableEditorVariant[];+};++export type EditorDiscoveryContext = {+ platform: NodeJS.Platform;+ env: NodeJS.ProcessEnv;+ homeDirectory: string;+ pathExists: (filePath: string) => boolean;+ findMacApplications: (bundleIdentifier: string) => Promise<readonly string[]>;+ findWindowsApplications: (+ editor: DefaultEditor,+ ) => Promise<readonly string[]>;+};++const getWindowsEnvironmentPaths = (+ context: EditorDiscoveryContext,+ segments: readonly string[],+) => {+ const paths: string[] = [];+ if (context.env.LOCALAPPDATA) {+ paths.push(+ path.win32.join(context.env.LOCALAPPDATA, 'Programs', ...segments),+ );+ }++ for (const directory of [+ context.env.ProgramFiles,+ context.env['ProgramFiles(x86)'],+ ]) {+ if (directory) {+ paths.push(path.win32.join(directory, ...segments));+ }+ }++ return paths;+};++const editorDefinitions = {+ vscode: {+ darwin: [+ {+ name: 'VS Code',+ bundleIdentifiers: ['com.microsoft.VSCode'],+ applicationNames: ['Visual Studio Code.app'],+ executable: 'Contents/Resources/app/bin/code',+ command: 'code',+ },+ {+ name: 'VS Code Insiders',+ bundleIdentifiers: ['com.microsoft.VSCodeInsiders'],+ applicationNames: ['Visual Studio Code - Insiders.app'],+ executable: 'Contents/Resources/app/bin/code-insiders',+ command: 'code-insiders',+ },+ ],+ linux: [+ {+ name: 'VS Code',+ paths: () => [+ '/usr/share/code/bin/code',+ '/snap/bin/code',+ '/usr/bin/code',+ '/var/lib/flatpak/exports/bin/com.visualstudio.code',+ ],+ commands: ['code'],+ },+ {+ name: 'VS Code Insiders',+ paths: () => [+ '/snap/bin/code-insiders',+ '/usr/bin/code-insiders',+ '/var/lib/flatpak/exports/bin/com.visualstudio.code.insiders',+ ],+ commands: ['code-insiders'],+ },+ ],+ win32: [+ {+ name: 'VS Code',+ paths: (context) =>+ getWindowsEnvironmentPaths(context, [+ 'Microsoft VS Code',+ 'Code.exe',+ ]),+ commands: ['Code.exe', 'code.cmd'],+ },+ {+ name: 'VS Code Insiders',+ paths: (context) =>+ getWindowsEnvironmentPaths(context, [+ 'Microsoft VS Code Insiders',+ 'Code - Insiders.exe',+ ]),+ commands: ['Code - Insiders.exe', 'code-insiders.cmd'],+ },+ ],+ },+ cursor: {+ darwin: [+ {+ name: 'Cursor',+ bundleIdentifiers: ['com.todesktop.230313mzl4w4u92'],+ applicationNames: ['Cursor.app'],+ executable: 'Contents/Resources/app/bin/cursor',+ command: 'cursor',+ },+ ],+ linux: [+ {+ name: 'Cursor',+ paths: (context) => [+ '/usr/bin/cursor',+ '/usr/local/bin/cursor',+ path.posix.join(context.homeDirectory, '.local/bin/cursor'),+ ],+ commands: ['cursor'],+ },+ ],+ win32: [+ {+ name: 'Cursor',+ paths: (context) =>+ getWindowsEnvironmentPaths(context, ['cursor', 'Cursor.exe']),+ commands: ['Cursor.exe', 'cursor.cmd'],+ },+ ],+ },+ windsurf: {+ darwin: [+ {+ name: 'Windsurf',+ bundleIdentifiers: ['com.exafunction.windsurf'],+ applicationNames: ['Windsurf.app'],+ executable: 'Contents/Resources/app/bin/windsurf',+ command: 'windsurf',+ },+ ],+ linux: [+ {+ name: 'Windsurf',+ paths: (context) => [+ '/usr/bin/windsurf',+ '/usr/local/bin/windsurf',+ path.posix.join(context.homeDirectory, '.local/bin/windsurf'),+ ],+ commands: ['windsurf'],+ },+ ],+ win32: [+ {+ name: 'Windsurf',+ paths: (context) =>+ getWindowsEnvironmentPaths(context, ['Windsurf', 'Windsurf.exe']),+ commands: ['Windsurf.exe', 'windsurf.cmd'],+ },+ ],+ },+ zed: {+ darwin: [+ {+ name: 'Zed',+ bundleIdentifiers: ['dev.zed.Zed'],+ applicationNames: ['Zed.app'],+ executable: 'Contents/MacOS/cli',+ command: 'zed',+ },+ {+ name: 'Zed Preview',+ bundleIdentifiers: ['dev.zed.Zed-Preview'],+ applicationNames: ['Zed Preview.app'],+ executable: 'Contents/MacOS/cli',+ command: 'zed',+ },+ ],+ linux: [+ {+ name: 'Zed',+ paths: (context) => [+ '/usr/bin/zedit',+ '/usr/bin/zeditor',+ '/usr/bin/zed-editor',+ '/usr/bin/zed',+ path.posix.join(context.homeDirectory, '.local/bin/zed'),+ ],+ commands: ['zed', 'zedit', 'zeditor', 'zed-editor'],+ },+ ],+ win32: [+ {+ name: 'Zed',+ paths: (context) =>+ getWindowsEnvironmentPaths(context, ['Zed', 'Zed.exe']),+ commands: ['Zed.exe'],+ },+ ],+ },+ vscodium: {+ darwin: [+ {+ name: 'VSCodium',+ bundleIdentifiers: ['com.vscodium', 'com.visualstudio.code.oss'],+ applicationNames: ['VSCodium.app'],+ executable: 'Contents/Resources/app/bin/codium',+ command: 'vscodium',+ },+ ],+ linux: [+ {+ name: 'VSCodium',+ paths: (context) => [+ '/usr/bin/codium',+ '/usr/share/vscodium-bin/bin/codium',+ '/snap/bin/codium',+ '/var/lib/flatpak/exports/bin/com.vscodium.codium',+ path.posix.join(+ context.homeDirectory,+ '.local/share/flatpak/exports/bin/com.vscodium.codium',+ ),+ ],+ commands: ['codium', 'vscodium'],+ },+ ],+ win32: [+ {+ name: 'VSCodium',+ paths: (context) =>+ getWindowsEnvironmentPaths(context, ['VSCodium', 'VSCodium.exe']),+ commands: ['VSCodium.exe', 'codium.cmd'],+ },+ ],+ },+ webstorm: {+ darwin: [+ {+ name: 'WebStorm',+ bundleIdentifiers: ['com.jetbrains.WebStorm'],+ applicationNames: ['WebStorm.app'],+ executable: 'Contents/MacOS/webstorm',+ command: 'webstorm',+ },+ ],+ linux: [+ {+ name: 'WebStorm',+ paths: (context) => [+ '/snap/bin/webstorm',+ path.posix.join(+ context.homeDirectory,+ '.local/share/JetBrains/Toolbox/scripts/webstorm',+ ),+ ],+ commands: ['webstorm'],+ },+ ],+ win32: [+ {+ name: 'WebStorm',+ paths: (context) => {+ const localAppData = context.env.LOCALAPPDATA;+ return localAppData+ ? [+ path.win32.join(+ localAppData,+ 'JetBrains/Toolbox/scripts/webstorm.cmd',+ ),+ ]+ : [];+ },+ commands: ['webstorm64.exe', 'webstorm.exe', 'webstorm.cmd'],+ },+ ],+ },+ 'sublime-text': {+ darwin: [+ {+ name: 'Sublime Text',+ bundleIdentifiers: [+ 'com.sublimetext.4',+ 'com.sublimetext.3',+ 'com.sublimetext.2',+ ],+ applicationNames: [+ 'Sublime Text.app',+ 'Sublime Text Dev.app',+ 'Sublime Text 2.app',+ ],+ executable: 'Contents/SharedSupport/bin/subl',+ command: 'subl',+ },+ ],+ linux: [+ {+ name: 'Sublime Text',+ paths: () => ['/usr/bin/subl', '/snap/bin/subl'],+ commands: ['subl'],+ },+ ],+ win32: [+ {+ name: 'Sublime Text',+ paths: (context) => [+ ...getWindowsEnvironmentPaths(context, [+ 'Sublime Text',+ 'sublime_text.exe',+ ]),+ ...getWindowsEnvironmentPaths(context, [+ 'Sublime Text 3',+ 'sublime_text.exe',+ ]),+ ],+ commands: ['subl.exe', 'sublime_text.exe'],+ },+ ],+ },+} satisfies Record<DefaultEditor, EditorDefinition>;++export const getDefaultEditorName = (id: DefaultEditor) =>+ editorDefinitions[id].darwin[0].name;++const findMacApplications = async (+ bundleIdentifier: string,+): Promise<readonly string[]> => {+ try {+ const {stdout} = await execFilePromise('mdfind', [+ `kMDItemCFBundleIdentifier == '${bundleIdentifier}'`,+ ]);+ return stdout+ .split('\n')+ .map((line) => line.trim())+ .filter(Boolean);+ } catch {+ return [];+ }+};++type WindowsRegistryApplication = {+ displayName: string;+ displayIcon: string;+};++const windowsDisplayNamePrefixes = {+ vscode: ['Microsoft Visual Studio Code'],+ cursor: ['Cursor'],+ windsurf: ['Windsurf'],+ zed: ['Zed'],+ vscodium: ['VSCodium'],+ webstorm: ['WebStorm', 'JetBrains WebStorm'],+ 'sublime-text': ['Sublime Text'],+} satisfies Record<DefaultEditor, readonly string[]>;++const parseWindowsRegistryApplications = (+ output: string,+): readonly WindowsRegistryApplication[] => {+ const applications: WindowsRegistryApplication[] = [];+ let displayName = '';+ let displayIcon = '';++ const flush = () => {+ if (displayName && displayIcon) {+ applications.push({displayIcon, displayName});+ }++ displayName = '';+ displayIcon = '';+ };++ for (const line of output.split(/\r?\n/)) {+ if (line.startsWith('HKEY_')) {+ flush();+ continue;+ }++ const match = /^\s+(DisplayName|DisplayIcon)\s+REG_\w+\s+(.*)$/.exec(line);+ if (!match) {+ continue;+ }++ if (match[1] === 'DisplayName') {+ displayName = match[2].trim();+ } else {+ displayIcon = match[2].trim();+ }+ }++ flush();+ return applications;+};++const cleanWindowsDisplayIcon = (displayIcon: string) => {+ const quotedPath = /^"([^"]+)"/.exec(displayIcon);+ if (quotedPath) {+ return quotedPath[1];+ }++ return displayIcon.replace(/,\d+$/, '').trim();+};++let windowsRegistryApplications: Promise<+ readonly WindowsRegistryApplication[]+> | null = null;++const getWindowsRegistryApplications = () => {+ windowsRegistryApplications ??= Promise.all(+ [+ 'HKCU\\Software\\Microsoft\\Windows\\CurrentVersion\\Uninstall',+ 'HKLM\\Software\\Microsoft\\Windows\\CurrentVersion\\Uninstall',+ 'HKLM\\Software\\WOW6432Node\\Microsoft\\Windows\\CurrentVersion\\Uninstall',+ ].map(async (registryKey) => {+ try {+ const {stdout} = await execFilePromise('reg.exe', [+ 'query',+ registryKey,+ '/s',+ ]);+ return parseWindowsRegistryApplications(stdout);+ } catch {+ return [];+ }+ }),+ ).then((results) => results.flat());+ return windowsRegistryApplications;+};++const findWindowsApplications = async (editor: DefaultEditor) => {+ const prefixes = windowsDisplayNamePrefixes[editor];+ const applications = await getWindowsRegistryApplications();+ return applications+ .filter(({displayName}) =>+ prefixes.some((prefix) => displayName.startsWith(prefix)),+ )+ .map(({displayIcon}) => cleanWindowsDisplayIcon(displayIcon));+};++const defaultDiscoveryContext: EditorDiscoveryContext = {+ platform: process.platform,+ env: process.env,+ homeDirectory: homedir(),+ pathExists: existsSync,+ findMacApplications,+ findWindowsApplications,+};++const unique = (values: readonly string[]) => [...new Set(values)];++const findDarwinEditor = async ({+ id,+ variants,+ context,+}: {+ id: DefaultEditor;+ variants: readonly DarwinEditorVariant[];+ context: EditorDiscoveryContext;+}): Promise<InstalledEditor | null> => {+ for (const variant of variants) {+ const discoveredApplications = (+ await Promise.all(+ variant.bundleIdentifiers.map((bundleIdentifier) =>+ context.findMacApplications(bundleIdentifier),+ ),+ )+ ).flat();+ const knownApplications = variant.applicationNames.flatMap((name) => [+ path.join('/Applications', name),+ path.join(context.homeDirectory, 'Applications', name),+ ]);++ for (const applicationPath of unique([+ ...discoveredApplications,+ ...knownApplications,+ ])) {+ const executablePath = path.join(applicationPath, variant.executable);+ if (+ context.pathExists(applicationPath) &&+ context.pathExists(executablePath)+ ) {+ return {+ id,+ name: variant.name,+ process: executablePath,+ command: variant.command,+ };+ }+ }+ }++ return null;+};++const getPathDirectories = (context: EditorDiscoveryContext) => {+ const value = context.env.PATH ?? context.env.Path ?? '';+ return value.split(context.platform === 'win32' ? ';' : ':').filter(Boolean);+};++const findExecutable = ({+ variant,+ context,+}: {+ variant: ExecutableEditorVariant;+ context: EditorDiscoveryContext;+}) => {+ for (const executablePath of variant.paths(context)) {+ if (context.pathExists(executablePath)) {+ return executablePath;+ }+ }++ const pathImplementation =+ context.platform === 'win32' ? path.win32 : path.posix;+ for (const directory of getPathDirectories(context)) {+ for (const command of variant.commands) {+ const executablePath = pathImplementation.join(directory, command);+ if (context.pathExists(executablePath)) {+ return executablePath;+ }+ }+ }++ return null;+};++const findExecutableEditor = ({+ id,+ variants,+ context,+ additionalPaths,+}: {+ id: DefaultEditor;+ variants: readonly ExecutableEditorVariant[];+ context: EditorDiscoveryContext;+ additionalPaths: readonly string[];+}): InstalledEditor | null => {+ for (const executablePath of additionalPaths) {+ if (context.pathExists(executablePath)) {+ return {+ id,+ name: variants[0].name,+ process: executablePath,+ command: executablePath,+ };+ }+ }++ for (const variant of variants) {+ const executablePath = findExecutable({variant, context});+ if (executablePath) {+ return {+ id,+ name: variant.name,+ process: executablePath,+ command: executablePath,+ };+ }+ }++ return null;+};++export const discoverAvailableEditors = async (+ context: EditorDiscoveryContext,+): Promise<readonly InstalledEditor[]> => {+ if (+ context.platform !== 'darwin' &&+ context.platform !== 'linux' &&+ context.platform !== 'win32'+ ) {+ return [];+ }++ const results: InstalledEditor[] = [];+ for (const id of defaultEditorIds) {+ const definition = editorDefinitions[id];+ const windowsApplications =+ context.platform === 'win32'+ ? await context.findWindowsApplications(id)+ : [];+ const editor =+ context.platform === 'darwin'+ ? await findDarwinEditor({+ id,+ variants: definition.darwin,+ context,+ })+ : findExecutableEditor({+ id,+ variants:+ context.platform === 'win32'+ ? definition.win32+ : definition.linux,+ context,+ additionalPaths: windowsApplications,+ });++ if (editor) {+ results.push(editor);+ }+ }++ return results;+};++let availableEditors: Promise<readonly InstalledEditor[]> | null = null;++export const getAvailableEditors = () => {+ availableEditors ??= discoverAvailableEditors(defaultDiscoveryContext);+ return availableEditors;+};diff --git a/packages/studio-server/src/helpers/open-in-editor.ts b/packages/studio-server/src/helpers/open-in-editor.tsindex be7d7768cb..684b488c92 100644--- a/packages/studio-server/src/helpers/open-in-editor.ts+++ b/packages/studio-server/src/helpers/open-in-editor.ts@@ -31,6 +31,7 @@ const isVsCodeDerivative = (editor: Editor) => {editor === 'Code.exe' ||editor === 'vscodium' ||editor === 'VSCodium.exe' ||+ editor === 'codium' ||editor === 'Code - Insiders.exe' ||editor === 'cursor' ||editor === 'Cursor.exe' ||@@ -50,83 +51,7 @@ function isTerminalEditor(editor: Editor) {}}-// eslint-disable-next-line @typescript-eslint/no-unused-vars-const editorNames = [- 'atom',- '/Applications/Atom Beta.app/Contents/MacOS/Atom Beta',- 'brackets',- '/Applications/Sublime Text.app/Contents/SharedSupport/bin/subl',- '/Applications/Sublime Text Dev.app/Contents/SharedSupport/bin/subl',- '/Applications/Sublime Text 2.app/Contents/SharedSupport/bin/subl',- 'code',- 'code-insiders',- 'vscodium',- '/Applications/AppCode.app/Contents/MacOS/appcode',- '/Applications/CLion.app/Contents/MacOS/clion',- '/Applications/IntelliJ IDEA.app/Contents/MacOS/idea',- '/Applications/PhpStorm.app/Contents/MacOS/phpstorm',- '/Applications/PyCharm.app/Contents/MacOS/pycharm',- '/Applications/PyCharm CE.app/Contents/MacOS/pycharm',- '/Applications/RubyMine.app/Contents/MacOS/rubymine',- '/Applications/WebStorm.app/Contents/MacOS/webstorm',- '/Applications/GoLand.app/Contents/MacOS/goland',- '/Applications/Rider.app/Contents/MacOS/rider',- 'mvim',- 'emacs',- 'gvim',- 'idea',- 'phpstorm',- 'pycharm',- 'rubymine',- 'subl',- 'sublime_text',- 'vim',- 'webstorm',- 'goland',- 'rider',- 'Brackets.exe',- 'Code.exe',- 'Code - Insiders.exe',- 'VSCodium.exe',- 'atom.exe',- 'sublime_text.exe',- 'notepad++.exe',- 'clion.exe',- 'clion64.exe',- 'idea.exe',- 'idea64.exe',- 'phpstorm.exe',- 'phpstorm64.exe',- 'pycharm.exe',- 'pycharm64.exe',- 'rubymine.exe',- 'rubymine64.exe',- 'webstorm.exe',- 'webstorm64.exe',- 'goland.exe',- 'goland64.exe',- 'rider.exe',- 'rider64.exe',- 'nano',- 'cursor',- '/Applications/Cursor.app/Contents/MacOS/Cursor',- 'Cursor.exe',- 'windsurf',- '/Applications/Windsurf.app/Contents/MacOS/Windsurf',- 'Windsurf.exe',- 'zed',- 'zedit',- 'zeditor',- 'zed-editor',- '/Applications/Zed.app/Contents/MacOS/zed',- '/Applications/Zed.app/Contents/MacOS/cli',- '/Applications/Zed Preview.app/Contents/MacOS/zed',- '/Applications/Zed Preview.app/Contents/MacOS/cli',- '/Applications/Zed Preview.app/Contents/MacOS/Zed Preview',- 'Zed.exe',-] as const;--const displayNameForEditor: {[key in Editor]: string} = {+const displayNameForEditor: Record<string, string> = {'/Applications/AppCode.app/Contents/MacOS/appcode': 'AppCode','/Applications/Atom Beta.app/Contents/MacOS/Atom Beta': 'Atom Beta','/Applications/CLion.app/Contents/MacOS/clion': 'CLion',@@ -222,7 +147,7 @@ export const getDisplayNameForEditor = ();};-type Editor = (typeof editorNames)[number];+type Editor = string;// Map from full process name to binary that starts the process// We can't just re-use full process name, because it will spawn a new instance@@ -387,6 +312,10 @@ function getArgumentsForLineNumber(case 'Code - Insiders':case 'vscodium':case 'VSCodium':+ case 'codium':+ case 'com.vscodium.codium':+ case 'com.visualstudio.code':+ case 'com.visualstudio.code.insiders':case 'cursor':case 'Cursor':case 'windsurf':@@ -418,7 +347,7 @@ function getArgumentsForLineNumber(}}-type ProcessAndCommand = {+export type ProcessAndCommand = {process: string;command: Editor;};diff --git a/packages/studio-server/src/helpers/resolve-editor.ts b/packages/studio-server/src/helpers/resolve-editor.tsnew file mode 100644index 0000000000..5eb2b23919--- /dev/null+++ b/packages/studio-server/src/helpers/resolve-editor.ts@@ -0,0 +1,75 @@+import type {DefaultEditor, LogLevel} from '@remotion/renderer';+import {RenderInternals} from '@remotion/renderer';+import {getAvailableEditors, getDefaultEditorName} from './editor-registry';+import type {InstalledEditor} from './editor-registry';+import {getDisplayNameForEditor, guessEditor} from './open-in-editor';+import type {ProcessAndCommand} from './open-in-editor';++export type ResolvedEditor = ProcessAndCommand & {+ id: DefaultEditor | null;+ name: string;+};++type ResolveEditorDependencies = {+ getInstalledEditors: () => Promise<readonly InstalledEditor[]>;+ getLegacyEditors: () => Promise<readonly ProcessAndCommand[]>;+ warn: (message: string) => void;+ warnedEditors: Set<DefaultEditor>;+};++const legacyEditors = guessEditor();+const warnedEditors = new Set<DefaultEditor>();++const defaultDependencies: ResolveEditorDependencies = {+ getInstalledEditors: getAvailableEditors,+ getLegacyEditors: () => legacyEditors,+ warn: () => undefined,+ warnedEditors,+};++export const resolveEditor = async (+ {+ defaultEditor,+ logLevel,+ }: {+ defaultEditor: DefaultEditor | null;+ logLevel: LogLevel;+ },+ overrides: Partial<ResolveEditorDependencies> = {},+): Promise<ResolvedEditor | null> => {+ const dependencies = {+ ...defaultDependencies,+ warn: (message: string) => {+ RenderInternals.Log.warn({indent: false, logLevel}, message);+ },+ ...overrides,+ };++ if (defaultEditor) {+ const installedEditors = await dependencies.getInstalledEditors();+ const installedEditor = installedEditors.find(+ (editor) => editor.id === defaultEditor,+ );+ if (installedEditor) {+ return installedEditor;+ }++ if (!dependencies.warnedEditors.has(defaultEditor)) {+ dependencies.warnedEditors.add(defaultEditor);+ dependencies.warn(+ `The default editor ${getDefaultEditorName(defaultEditor)} (${defaultEditor}) is not installed. Falling back to automatic editor detection.`,+ );+ }+ }++ const [legacyEditor] = await dependencies.getLegacyEditors();+ if (!legacyEditor) {+ return null;+ }++ return {+ ...legacyEditor,+ id: null,+ name: getDisplayNameForEditor(legacyEditor.command) ?? legacyEditor.command,+ };+};diff --git a/packages/studio-server/src/preview-server/api-routes.ts b/packages/studio-server/src/preview-server/api-routes.tsindex 7b3c998095..624ec6d41e 100644--- a/packages/studio-server/src/preview-server/api-routes.ts+++ b/packages/studio-server/src/preview-server/api-routes.ts@@ -67,9 +67,9 @@ export const allApiRoutes: {'/api/unsubscribe-from-file-existence': unsubscribeFromFileExistence,'/api/subscribe-to-file-existence': subscribeToFileExistence,'/api/remove-render': handleRemoveRender,- '/api/open-in-editor': openInEditorHandler,'/api/find-in-file': findInFileHandler,'/api/open-in-file-explorer': handleOpenInFileExplorer,+ '/api/open-in-editor': openInEditorHandler,'/api/register-client-render': registerClientRenderHandler,'/api/unregister-client-render': unregisterClientRenderHandler,'/api/update-default-props': updateDefaultPropsHandler,diff --git a/packages/studio-server/src/preview-server/api-types.ts b/packages/studio-server/src/preview-server/api-types.tsindex 60da295a70..d7748dc19b 100644--- a/packages/studio-server/src/preview-server/api-types.ts+++ b/packages/studio-server/src/preview-server/api-types.ts@@ -1,5 +1,5 @@import type {IncomingMessage, ServerResponse} from 'node:http';-import type {LogLevel} from '@remotion/renderer';+import type {DefaultEditor, LogLevel} from '@remotion/renderer';import type {RenderJobWithCleanup} from '@remotion/studio-shared';export type QueueMethods = {@@ -29,4 +29,5 @@ export type ApiHandler<ReqData, ResData> = (params: {publicDir: string;binariesDirectory: string | null;configFile: string | null;+ getDefaultEditor: () => DefaultEditor | null;}) => Promise<ResData>;diff --git a/packages/studio-server/src/preview-server/handler.ts b/packages/studio-server/src/preview-server/handler.tsindex fa7ca0e95e..08ee1c4f0b 100644--- a/packages/studio-server/src/preview-server/handler.ts+++ b/packages/studio-server/src/preview-server/handler.ts@@ -1,5 +1,5 @@import type {IncomingMessage, ServerResponse} from 'node:http';-import type {LogLevel} from '@remotion/renderer';+import type {DefaultEditor, LogLevel} from '@remotion/renderer';import type {ApiHandler, QueueMethods} from './api-types';import {parseRequestBody} from './parse-body';import {validateSameOrigin} from './validate-same-origin';@@ -15,6 +15,7 @@ export const handleRequest = async <Req, Res>({binariesDirectory,publicDir,configFile,+ getDefaultEditor,}: {remotionRoot: string;publicDir: string;@@ -23,6 +24,7 @@ export const handleRequest = async <Req, Res>({entryPoint: string;binariesDirectory: string | null;configFile: string | null;+ getDefaultEditor: () => DefaultEditor | null;handler: ApiHandler<Req, Res>;logLevel: LogLevel;methods: QueueMethods;@@ -52,6 +54,7 @@ export const handleRequest = async <Req, Res>({binariesDirectory,publicDir,configFile,+ getDefaultEditor,});response.end(diff --git a/packages/studio-server/src/preview-server/routes/open-in-editor.ts b/packages/studio-server/src/preview-server/routes/open-in-editor.tsindex a152644e6f..b30b98a5ee 100644--- a/packages/studio-server/src/preview-server/routes/open-in-editor.ts+++ b/packages/studio-server/src/preview-server/routes/open-in-editor.ts@@ -1,36 +1,48 @@import path from 'node:path';+import type {DefaultEditor, LogLevel} from '@remotion/renderer';import type {OpenInEditorRequest,OpenInEditorResponse,} from '@remotion/studio-shared';-import {- getDisplayNameForEditor,- guessEditor,- launchEditor,-} from '../../helpers/open-in-editor';+import {launchEditor} from '../../helpers/open-in-editor';+import {resolveEditor} from '../../helpers/resolve-editor';import type {ApiHandler} from '../api-types';-const editorGuess = guessEditor();--export const getEditorName = async () => {- const [edit] = await editorGuess;- return getDisplayNameForEditor(edit ? edit.command : null);+export const getEditorName = async ({+ getDefaultEditor,+ logLevel,+}: {+ getDefaultEditor: () => DefaultEditor | null;+ logLevel: LogLevel;+}) => {+ const editor = await resolveEditor({+ defaultEditor: getDefaultEditor(),+ logLevel,+ });+ return editor?.name ?? null;};export const openInEditorHandler: ApiHandler<OpenInEditorRequest,OpenInEditorResponse-> = async ({input, remotionRoot, logLevel}) => {+> = async ({input, remotionRoot, logLevel, getDefaultEditor}) => {try {if (!('stack' in input)) {throw new TypeError('Need to pass stack');}const {stack} = input;- const guess = await editorGuess;+ const editor = await resolveEditor({+ defaultEditor: getDefaultEditor(),+ logLevel,+ });+ if (!editor) {+ return {success: false};+ }+const didOpen = await launchEditor({colNumber: stack.originalColumnNumber as number,- editor: guess[0],+ editor,fileName: path.resolve(remotionRoot, stack.originalFileName as string),lineNumber: stack.originalLineNumber as number,vsCodeNewWindow: false,diff --git a/packages/studio-server/src/preview-server/start-server.ts b/packages/studio-server/src/preview-server/start-server.tsindex 49557273d0..3ec3e72165 100644--- a/packages/studio-server/src/preview-server/start-server.ts+++ b/packages/studio-server/src/preview-server/start-server.ts@@ -10,7 +10,7 @@ import {WatchIgnoreNextChangePlugin,webpack,} from '@remotion/bundler';-import type {LogLevel} from '@remotion/renderer';+import type {DefaultEditor, LogLevel} from '@remotion/renderer';import {RenderInternals} from '@remotion/renderer';import type {GitSource,@@ -71,6 +71,7 @@ export const startServer = async (options: {forceNew: boolean;rspack: boolean;getStudioRuntimeConfig: () => StudioRuntimeConfig;+ getDefaultEditor: () => DefaultEditor | null;configFile: string | null;}): Promise<StartServerResult> => {const desiredPort =@@ -176,6 +177,7 @@ export const startServer = async (options: {getPreviewSampleRate: options.getPreviewSampleRate,enableCrossSiteIsolation: options.enableCrossSiteIsolation,getStudioRuntimeConfig: options.getStudioRuntimeConfig,+ getDefaultEditor: options.getDefaultEditor,configFile: options.configFile,});})diff --git a/packages/studio-server/src/routes.ts b/packages/studio-server/src/routes.tsindex e1a590f51d..0d71385106 100644--- a/packages/studio-server/src/routes.ts+++ b/packages/studio-server/src/routes.ts@@ -4,7 +4,7 @@ import type {IncomingMessage, ServerResponse} from 'node:http';import path, {join} from 'node:path';import {URLSearchParams} from 'node:url';import {BundlerInternals} from '@remotion/bundler';-import type {LogLevel} from '@remotion/renderer';+import type {DefaultEditor, LogLevel} from '@remotion/renderer';import {RenderInternals} from '@remotion/renderer';import type {ApiRoutes,@@ -85,6 +85,7 @@ const handleFallback = async ({logLevel,enableCrossSiteIsolation,getStudioRuntimeConfig,+ getDefaultEditor,}: {remotionRoot: string;hash: string;@@ -102,6 +103,7 @@ const handleFallback = async ({logLevel: LogLevel;enableCrossSiteIsolation: boolean;getStudioRuntimeConfig: () => StudioRuntimeConfig;+ getDefaultEditor: () => DefaultEditor | null;}) => {const acceptsHtml = (request.headers.accept ?? '').includes('text/html');if (request.method === 'GET' && acceptsHtml) {@@ -131,7 +133,7 @@ const handleFallback = async ({);}- const displayName = await getEditorName();+ const displayName = await getEditorName({getDefaultEditor, logLevel});response.setHeader('content-type', 'text/html');if (enableCrossSiteIsolation) {@@ -376,6 +378,7 @@ export const handleRoutes = ({getPreviewSampleRate,enableCrossSiteIsolation,getStudioRuntimeConfig,+ getDefaultEditor,configFile,}: {staticHash: string;@@ -401,6 +404,7 @@ export const handleRoutes = ({getPreviewSampleRate: () => number | null;enableCrossSiteIsolation: boolean;getStudioRuntimeConfig: () => StudioRuntimeConfig;+ getDefaultEditor: () => DefaultEditor | null;configFile: string | null;}): Promise<void> => {const url = new URL(request.url as string, 'http://localhost');@@ -477,6 +481,7 @@ export const handleRoutes = ({binariesDirectory,publicDir,configFile,+ getDefaultEditor,});}}@@ -554,5 +559,6 @@ export const handleRoutes = ({getPreviewSampleRate,enableCrossSiteIsolation,getStudioRuntimeConfig,+ getDefaultEditor,});};diff --git a/packages/studio-server/src/start-studio.ts b/packages/studio-server/src/start-studio.tsindex bafa97cd3b..835c3b6580 100644--- a/packages/studio-server/src/start-studio.ts+++ b/packages/studio-server/src/start-studio.ts@@ -6,7 +6,7 @@ import type {RspackOverrideFn,WebpackOverrideFn,} from '@remotion/bundler';-import type {LogLevel} from '@remotion/renderer';+import type {DefaultEditor, LogLevel} from '@remotion/renderer';import {RenderInternals} from '@remotion/renderer';import type {GitSource,@@ -61,6 +61,7 @@ export const startStudio = async ({forceNew,rspack,getStudioRuntimeConfig,+ getDefaultEditor,configFile,}: {browserArgs: string;@@ -91,6 +92,7 @@ export const startStudio = async ({forceNew: boolean;rspack: boolean;getStudioRuntimeConfig: () => StudioRuntimeConfig;+ getDefaultEditor: () => DefaultEditor | null;configFile: string | null;}): Promise<StartStudioResult> => {try {@@ -170,6 +172,7 @@ export const startStudio = async ({forceNew,rspack,getStudioRuntimeConfig,+ getDefaultEditor,configFile,});diff --git a/packages/studio-server/src/test/apply-codemod.test.ts b/packages/studio-server/src/test/apply-codemod.test.tsindex 548b84b472..7caf943c95 100644--- a/packages/studio-server/src/test/apply-codemod.test.ts+++ b/packages/studio-server/src/test/apply-codemod.test.ts@@ -322,6 +322,7 @@ const getHandlerOptions = <T>({publicDir: remotionRoot,binariesDirectory: null,configFile: null,+ getDefaultEditor: () => null,});const runCompositionCodemodUndoRedoTest = async ({diff --git a/packages/studio-server/src/test/download-remote-asset.test.ts b/packages/studio-server/src/test/download-remote-asset.test.tsindex 0551189543..492d087fa6 100644--- a/packages/studio-server/src/test/download-remote-asset.test.ts+++ b/packages/studio-server/src/test/download-remote-asset.test.ts@@ -68,6 +68,7 @@ test('follows validated redirects for remote assets', async () => {const response = await downloadRemoteAssetHandler({binariesDirectory: null,configFile: null,+ getDefaultEditor: () => null,entryPoint: '',input: {url: 'https://93.184.216.34/raw-link'},logLevel: 'info',@@ -137,6 +138,7 @@ test('blocks redirects to private IP addresses', async () => {downloadRemoteAssetHandler({binariesDirectory: null,configFile: null,+ getDefaultEditor: () => null,entryPoint: '',input: {url: 'https://93.184.216.34/raw-link'},logLevel: 'info',diff --git a/packages/studio-server/src/test/editor-registry.test.ts b/packages/studio-server/src/test/editor-registry.test.tsnew file mode 100644index 0000000000..15379c7183--- /dev/null+++ b/packages/studio-server/src/test/editor-registry.test.ts@@ -0,0 +1,183 @@+import {expect, test} from 'bun:test';+import path from 'node:path';+import type {DefaultEditor} from '@remotion/renderer';+import {+ discoverAvailableEditors,+ getDefaultEditorName,+} from '../helpers/editor-registry';+import type {+ EditorDiscoveryContext,+ InstalledEditor,+} from '../helpers/editor-registry';+import {resolveEditor} from '../helpers/resolve-editor';++const makeContext = ({+ platform,+ paths,+ env = {},+ macApplications = {},+ windowsApplications = {},+}: {+ platform: NodeJS.Platform;+ paths: readonly string[];+ env?: NodeJS.ProcessEnv;+ macApplications?: Record<string, readonly string[]>;+ windowsApplications?: Partial<Record<DefaultEditor, readonly string[]>>;+}): EditorDiscoveryContext => {+ const existingPaths = new Set(paths);+ return {+ platform,+ env,+ homeDirectory: platform === 'win32' ? 'C:\\Users\\test' : '/home/test',+ pathExists: (filePath) => existingPaths.has(filePath),+ findMacApplications: (bundleIdentifier) =>+ Promise.resolve(macApplications[bundleIdentifier] ?? []),+ findWindowsApplications: (editor) =>+ Promise.resolve(windowsApplications[editor] ?? []),+ };+};++test('discovers installed macOS editors by bundle ID without running them', async () => {+ const cursorApplication = '/Custom/Applications/Cursor.app';+ const cursorExecutable = path.join(+ cursorApplication,+ 'Contents/Resources/app/bin/cursor',+ );+ const editors = await discoverAvailableEditors(+ makeContext({+ platform: 'darwin',+ paths: [cursorApplication, cursorExecutable],+ macApplications: {+ 'com.todesktop.230313mzl4w4u92': [cursorApplication],+ },+ }),+ );++ expect(editors).toEqual([+ {+ command: 'cursor',+ id: 'cursor',+ name: 'Cursor',+ process: cursorExecutable,+ },+ ]);+});++test('discovers installed Linux editors from known locations and PATH', async () => {+ const editors = await discoverAvailableEditors(+ makeContext({+ platform: 'linux',+ paths: ['/custom/bin/code', '/home/test/.local/bin/zed'],+ env: {PATH: '/custom/bin:/usr/local/bin'},+ }),+ );++ expect(editors.map(({id, process}) => ({id, process}))).toEqual([+ {id: 'vscode', process: '/custom/bin/code'},+ {id: 'zed', process: '/home/test/.local/bin/zed'},+ ]);+});++test('discovers installed Windows editors from install folders and PATH', async () => {+ const windsurf = path.win32.join(+ 'C:\\Users\\test\\AppData\\Local',+ 'Programs',+ 'Windsurf',+ 'Windsurf.exe',+ );+ const sublime = path.win32.join('C:\\Tools', 'subl.exe');+ const webstorm = 'D:\\JetBrains\\WebStorm\\bin\\webstorm64.exe';+ const editors = await discoverAvailableEditors(+ makeContext({+ platform: 'win32',+ paths: [windsurf, sublime, webstorm],+ env: {+ LOCALAPPDATA: 'C:\\Users\\test\\AppData\\Local',+ PATH: 'C:\\Tools;C:\\Windows',+ },+ windowsApplications: {webstorm: [webstorm]},+ }),+ );++ expect(editors.map(({id, process}) => ({id, process}))).toEqual([+ {id: 'windsurf', process: windsurf},+ {id: 'webstorm', process: webstorm},+ {id: 'sublime-text', process: sublime},+ ]);+});++test('uses the configured installed editor instead of legacy detection', async () => {+ const cursor: InstalledEditor = {+ command: '/usr/bin/cursor',+ id: 'cursor',+ name: 'Cursor',+ process: '/usr/bin/cursor',+ };+ let legacyDetectionCalls = 0;++ const resolved = await resolveEditor(+ {defaultEditor: 'cursor', logLevel: 'info'},+ {+ getInstalledEditors: () => Promise.resolve([cursor]),+ getLegacyEditors: () => {+ legacyDetectionCalls++;+ return Promise.resolve([]);+ },+ },+ );++ expect(resolved).toEqual(cursor);+ expect(legacyDetectionCalls).toBe(0);+});++test('warns once and falls back when the configured editor is unavailable', async () => {+ const warnings: string[] = [];+ const warnedEditors = new Set<DefaultEditor>();+ const dependencies = {+ getInstalledEditors: () => Promise.resolve([]),+ getLegacyEditors: () =>+ Promise.resolve([{command: 'code', process: 'code'}]),+ warn: (message: string) => warnings.push(message),+ warnedEditors,+ };++ const first = await resolveEditor(+ {defaultEditor: 'cursor', logLevel: 'info'},+ dependencies,+ );+ const second = await resolveEditor(+ {defaultEditor: 'cursor', logLevel: 'info'},+ dependencies,+ );++ expect(first).toEqual({+ command: 'code',+ id: null,+ name: 'VS Code',+ process: 'code',+ });+ expect(second).toEqual(first);+ expect(warnings).toEqual([+ `The default editor ${getDefaultEditorName('cursor')} (cursor) is not installed. Falling back to automatic editor detection.`,+ ]);+});++test('preserves legacy detection when no default editor is configured', async () => {+ let installedEditorDetectionCalls = 0;+ const resolved = await resolveEditor(+ {defaultEditor: null, logLevel: 'info'},+ {+ getInstalledEditors: () => {+ installedEditorDetectionCalls++;+ return Promise.resolve([]);+ },+ getLegacyEditors: () =>+ Promise.resolve([+ {command: 'Windsurf.exe', process: 'C:\\Windsurf.exe'},+ ]),+ },+ );++ expect(installedEditorDetectionCalls).toBe(0);+ expect(resolved?.name).toBe('Windsurf');+});diff --git a/packages/studio-server/src/test/file-source-route.test.ts b/packages/studio-server/src/test/file-source-route.test.tsindex 5ee5368ec3..510dc48d8a 100644--- a/packages/studio-server/src/test/file-source-route.test.ts+++ b/packages/studio-server/src/test/file-source-route.test.ts@@ -74,6 +74,7 @@ test('serves file source from an origin-less GET request', async () => {entryPoint: '',getAudioLatencyHint: () => null,getCurrentInputProps: () => ({}),+ getDefaultEditor: () => null,getEnvVariables: () => ({}),getRenderDefaults: () => ({}) as RenderDefaults,getRenderQueue: () => [],diff --git a/packages/studio-server/src/test/handler.test.ts b/packages/studio-server/src/test/handler.test.tsindex 22b3da4bf4..15ded14be5 100644--- a/packages/studio-server/src/test/handler.test.ts+++ b/packages/studio-server/src/test/handler.test.ts@@ -65,6 +65,7 @@ test('rejects cross-origin API requests before calling the handler', async () =>didCallHandler = true;return Promise.resolve({});},+ getDefaultEditor: () => null,logLevel: 'info',methods: {addJob: () => undefined,@@ -96,6 +97,7 @@ test('allows same-origin API requests from non-local peers', async () => {handler: ({input}) => {return Promise.resolve({input});},+ getDefaultEditor: () => null,logLevel: 'info',methods: {addJob: () => undefined,@@ -137,6 +139,7 @@ test('rejects API requests without an Origin header before calling the handler',didCallHandler = true;return Promise.resolve({});},+ getDefaultEditor: () => null,logLevel: 'info',methods: {addJob: () => undefined,@@ -168,6 +171,7 @@ test('allows GET API requests without an Origin header', async () => {handler: ({input}) => {return Promise.resolve({input});},+ getDefaultEditor: () => null,logLevel: 'info',methods: {addJob: () => undefined,@@ -206,6 +210,7 @@ test('allows HEAD API requests without an Origin header', async () => {handler: ({input}) => {return Promise.resolve({input});},+ getDefaultEditor: () => null,logLevel: 'info',methods: {addJob: () => undefined,@@ -247,6 +252,7 @@ test('rejects requests with a mismatched Origin scheme before calling the handledidCallHandler = true;return Promise.resolve({});},+ getDefaultEditor: () => null,logLevel: 'info',methods: {addJob: () => undefined,@@ -275,9 +281,10 @@ test('allows same-origin API requests', async () => {binariesDirectory: null,configFile: null,entryPoint: '',- handler: ({input}) => {- return Promise.resolve({input});+ handler: ({getDefaultEditor, input}) => {+ return Promise.resolve({defaultEditor: getDefaultEditor(), input});},+ getDefaultEditor: () => 'cursor',logLevel: 'info',methods: {addJob: () => undefined,@@ -297,6 +304,7 @@ test('allows same-origin API requests', async () => {expect(response.statusCode).toBe(200);expect(JSON.parse(response.body)).toEqual({data: {+ defaultEditor: 'cursor',input: {relativePath: 'logo.png',},diff --git a/packages/studio-server/src/test/insert-element.test.ts b/packages/studio-server/src/test/insert-element.test.tsindex 816130d18a..8c6abcb910 100644--- a/packages/studio-server/src/test/insert-element.test.ts+++ b/packages/studio-server/src/test/insert-element.test.ts@@ -82,6 +82,7 @@ const makeFixture = () => {return insertElementHandler({binariesDirectory: null,configFile: null,+ getDefaultEditor: () => null,entryPoint: compositionFile,input,logLevel: 'error',diff --git a/packages/studio-server/src/test/resolve-composition-component.test.ts b/packages/studio-server/src/test/resolve-composition-component.test.tsindex 524f5ef53f..83c5458a2c 100644--- a/packages/studio-server/src/test/resolve-composition-component.test.ts+++ b/packages/studio-server/src/test/resolve-composition-component.test.ts@@ -1936,6 +1936,7 @@ test('rejects composition insertion requests that traverse out of the project ropublicDir: tempDir,binariesDirectory: null,configFile: null,+ getDefaultEditor: () => null,});expect(response.success).toBe(false);diff --git a/packages/studio-server/src/test/save-multiple-effect-props.test.ts b/packages/studio-server/src/test/save-multiple-effect-props.test.tsindex 4ea9bc7020..43a42cb9ec 100644--- a/packages/studio-server/src/test/save-multiple-effect-props.test.ts+++ b/packages/studio-server/src/test/save-multiple-effect-props.test.ts@@ -115,6 +115,7 @@ export const Comp = () => {publicDir: '',binariesDirectory: null,configFile: null,+ getDefaultEditor: () => null,});const output = readFileSync(filePath, 'utf-8');diff --git a/packages/studio-server/src/test/save-sequence-props.test.ts b/packages/studio-server/src/test/save-sequence-props.test.tsindex a6f58b6543..d1311ff129 100644--- a/packages/studio-server/src/test/save-sequence-props.test.ts+++ b/packages/studio-server/src/test/save-sequence-props.test.ts@@ -191,6 +191,7 @@ test('saveSequenceProps saves inline caption patches as an undoable source edit'publicDir: '',binariesDirectory: null,configFile: null,+ getDefaultEditor: () => null,});expect(readFileSync(filePath, 'utf-8')).toContain("text: 'Updated'");@@ -297,6 +298,7 @@ export const Comp = () => {publicDir: '',binariesDirectory: null,configFile: null,+ getDefaultEditor: () => null,});const output = readFileSync(filePath, 'utf-8');@@ -410,6 +412,7 @@ export const Comp = () => {publicDir: '',binariesDirectory: null,configFile: null,+ getDefaultEditor: () => null,});const output = readFileSync(filePath, 'utf-8');diff --git a/packages/studio-server/src/test/split-jsx-sequence.test.ts b/packages/studio-server/src/test/split-jsx-sequence.test.tsindex 57f66353de..7a0e6bd8c3 100644--- a/packages/studio-server/src/test/split-jsx-sequence.test.ts+++ b/packages/studio-server/src/test/split-jsx-sequence.test.ts@@ -186,6 +186,7 @@ const getHandlerOptions = <T>({publicDir: remotionRoot,binariesDirectory: null,configFile: null,+ getDefaultEditor: () => null,});test('splitJsxSequenceHandler writes success and failure responses', async () => {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.tsindex 527595c5e6..2e3bb0b318 100644--- a/packages/studio-server/src/test/update-element-install-target.test.ts+++ b/packages/studio-server/src/test/update-element-install-target.test.ts@@ -28,6 +28,7 @@ const callHandler = ({return updateElementInstallTargetHandler({binariesDirectory: null,configFile: null,+ getDefaultEditor: () => null,entryPoint: '',input,logLevel: 'info',