🎥 Make videos programmatically with React
Add Studio terminal shortcut helper
Jonny Burger0a4892e22b37
diff --git a/packages/studio-server/src/helpers/app-discovery.ts b/packages/studio-server/src/helpers/app-discovery.tsnew file mode 100644index 0000000000..e1cf1fa016--- /dev/null+++ b/packages/studio-server/src/helpers/app-discovery.ts@@ -0,0 +1,69 @@+import type {DefaultEditor} from '@remotion/renderer';+import type {GetDefaultEditorInfoResponse} from '@remotion/studio-shared';+import {+ getAvailableCodingAgents,+ getRunningCodingAgents,+} from './coding-agent-registry';+import {resolveCustomEditorExecutable} from './custom-editor';+import {getAvailableEditors, getRunningEditors} from './editor-registry';++let appDiscovery: ReturnType<typeof discoverApps> | null = null;++const discoverApps = async () => {+ const [installedEditors, installedCodingAgents] = await Promise.all([+ getAvailableEditors(),+ getAvailableCodingAgents(),+ ]);+ const [runningEditors, runningCodingAgents] = await Promise.all([+ getRunningEditors(installedEditors),+ getRunningCodingAgents(installedCodingAgents),+ ]);+ return {+ installedEditors,+ installedCodingAgents,+ runningEditors,+ runningCodingAgents,+ };+};++// The terminal helper and Studio requests share the same in-flight discovery+// and process snapshot. Configuration and app history are read separately.+export const getAppDiscovery = () => {+ appDiscovery ??= discoverApps();+ return appDiscovery;+};++export const getEditorInfo = async (+ configuredEditor: DefaultEditor | null,+): Promise<GetDefaultEditorInfoResponse> => {+ const {installedEditors, runningEditors} = await getAppDiscovery();+ const customEditor =+ configuredEditor &&+ typeof configuredEditor === 'object' &&+ resolveCustomEditorExecutable(configuredEditor)+ ? configuredEditor+ : null;+ return {+ defaultEditor:+ configuredEditor && typeof configuredEditor === 'object'+ ? 'custom'+ : configuredEditor,+ runningEditors,+ installedEditors: [+ ...installedEditors.map(({id, name, nameWithType}) => ({+ id,+ name,+ nameWithType,+ })),+ ...(customEditor+ ? [+ {+ id: 'custom' as const,+ name: customEditor.name,+ nameWithType: customEditor.name,+ },+ ]+ : []),+ ],+ };+};diff --git a/packages/studio-server/src/helpers/open-in-editor.ts b/packages/studio-server/src/helpers/open-in-editor.tsindex ceb53c117c..03c69132da 100644--- a/packages/studio-server/src/helpers/open-in-editor.ts+++ b/packages/studio-server/src/helpers/open-in-editor.ts@@ -475,10 +475,9 @@ export async function launchEditor(return false;}+ const isDirectory = fs.statSync(fileName).isDirectory();let folderToOpen =- isVsCodeDerivative(editor.command) && !fs.statSync(fileName).isDirectory()- ? projectFolder- : null;+ isVsCodeDerivative(editor.command) && !isDirectory ? projectFolder : null;if (process.platform === 'linux' &&@@ -529,7 +528,7 @@ export async function launchEditor(isVsCodeDerivative(editor.command) && vsCodeNewWindow;// The file URL cannot specify both a workspace folder and a source location.- if (!shouldOpenVsCodeNewWindow && folderToOpen === null) {+ if (!shouldOpenVsCodeNewWindow && folderToOpen === null && !isDirectory) {const result = openInEditorViaUrlScheme({editor: editor.command,fileName,@@ -546,7 +545,7 @@ export async function launchEditor(const args = shouldOpenVsCodeNewWindow? ['--new-window', fileName]- : lineNumber+ : lineNumber && !isDirectory? getArgumentsForLineNumber(editor.command,fileName,@@ -559,7 +558,7 @@ export async function launchEditor(args.unshift(folderToOpen);}- if (process.platform === 'darwin' && folderToOpen !== null) {+ if (process.platform === 'darwin' && (folderToOpen !== null || isDirectory)) {const applicationPath = editor.process.match(/^(.*?\.app)\/Contents\//,)?.[1];diff --git a/packages/studio-server/src/helpers/recently-used-apps.ts b/packages/studio-server/src/helpers/recently-used-apps.tsnew file mode 100644index 0000000000..cfd71168b8--- /dev/null+++ b/packages/studio-server/src/helpers/recently-used-apps.ts@@ -0,0 +1,62 @@+import {mkdir, readFile, writeFile} from 'node:fs/promises';+import path from 'node:path';+import {defaultCodingAgentIds, defaultEditorIds} from '@remotion/renderer';++const histories = new Map<string, Promise<readonly string[]>>();++export const getRecentlyUsedApps = ({+ remotionRoot,+ type,+ recentlyUsedIds,+}: {+ remotionRoot: string;+ type: 'editor' | 'coding-agent';+ recentlyUsedIds: readonly string[] | null;+}): Promise<readonly string[]> => {+ const filePath = path.join(+ remotionRoot,+ 'node_modules',+ '.cache',+ 'remotion',+ `recently-used-${type}s.json`,+ );+ const allowedIds: readonly string[] =+ type === 'editor' ? [...defaultEditorIds, 'custom'] : defaultCodingAgentIds;+ const previous =+ histories.get(filePath) ??+ (async () => {+ try {+ const stored: unknown = JSON.parse(await readFile(filePath, 'utf8'));+ return Array.isArray(stored)+ ? [+ ...new Set(+ stored.filter((id): id is string => allowedIds.includes(id)),+ ),+ ]+ : [];+ } catch {+ return [];+ }+ })();+ const history = previous.then(async (ids) => {+ if (recentlyUsedIds === null || !Array.isArray(recentlyUsedIds)) {+ return ids;+ }++ const updatedIds = [+ ...new Set(recentlyUsedIds.filter((id) => allowedIds.includes(id))),+ ];+ if (JSON.stringify(ids) !== JSON.stringify(updatedIds)) {+ try {+ await mkdir(path.dirname(filePath), {recursive: true});+ await writeFile(filePath, JSON.stringify(updatedIds));+ } catch {+ // Keep the history in memory when the project cache is not writable.+ }+ }++ return updatedIds;+ });+ histories.set(filePath, history);+ return history;+};diff --git a/packages/studio-server/src/open-browser-shortcut.ts b/packages/studio-server/src/open-browser-shortcut.tsdeleted file mode 100644index 6652e13d0a..0000000000--- a/packages/studio-server/src/open-browser-shortcut.ts+++ /dev/null@@ -1,124 +0,0 @@-import * as readline from 'node:readline';-import type {LogLevel} from '@remotion/renderer';-import {RenderInternals} from '@remotion/renderer';-import {focusBrowserTabByOrigin} from './better-opn';-import {maybeOpenBrowser} from './maybe-open-browser';-import {clearPrintPortMessageTimeout} from './preview-server/live-events';--type Key = {- name?: string;- ctrl?: boolean;- meta?: boolean;-};--export const registerOpenBrowserShortcut = ({- browserArgs,- browserFlag,- url,- logLevel,-}: {- browserArgs: string;- browserFlag: string;- url: string;- logLevel: LogLevel;-}): {registered: boolean; cleanup: () => void} => {- if (!process.stdin.isTTY) {- return {registered: false, cleanup: () => undefined};- }-- if (typeof process.stdin.setRawMode !== 'function') {- return {registered: false, cleanup: () => undefined};- }-- const wasRaw = process.stdin.isRaw;- const shouldPauseAfterCleanup = process.stdin.isPaused();- let cleanedUp = false;- let isOpeningBrowser = false;-- const cleanup = () => {- if (cleanedUp) {- return;- }-- cleanedUp = true;- process.stdin.removeListener('keypress', onKeypress);- process.removeListener('SIGINT', cleanup);- process.removeListener('exit', cleanup);-- if (!wasRaw && process.stdin.isTTY) {- process.stdin.setRawMode(false);- }-- if (shouldPauseAfterCleanup) {- process.stdin.pause();- }- };-- const openStudio = async () => {- if (isOpeningBrowser) {- return;- }-- isOpeningBrowser = true;- clearPrintPortMessageTimeout();- try {- const didFocus = await focusBrowserTabByOrigin({- url,- browserArgs,- browserFlag,- });- if (didFocus) {- RenderInternals.Log.info(- {indent: false, logLevel},- RenderInternals.chalk.blue(`Opened ${url} in browser`),- );- return;- }-- const result = await maybeOpenBrowser({- browserArgs,- browserFlag,- shouldOpenBrowser: true,- url,- logLevel,- });- if (result.didOpenBrowser) {- RenderInternals.Log.info(- {indent: false, logLevel},- RenderInternals.chalk.blue(`Opened ${url} in browser`),- );- }- } catch (err) {- RenderInternals.Log.error(- {indent: false, logLevel},- 'Could not open browser:',- err,- );- } finally {- isOpeningBrowser = false;- }- };-- function onKeypress(_str: string, key: Key | undefined) {- if (key?.ctrl && key.name === 'c') {- cleanup();- process.kill(process.pid, 'SIGINT');- return;- }-- if (key?.meta || key?.ctrl || key?.name !== 's') {- return;- }-- openStudio().catch(() => undefined);- }-- readline.emitKeypressEvents(process.stdin);- process.stdin.setRawMode(true);- process.stdin.resume();- process.stdin.on('keypress', onKeypress);- process.once('SIGINT', cleanup);- process.once('exit', cleanup);-- return {registered: true, cleanup};-};diff --git a/packages/studio-server/src/preview-server/routes/default-coding-agent.ts b/packages/studio-server/src/preview-server/routes/default-coding-agent.tsindex 402c51dc34..5becc111da 100644--- a/packages/studio-server/src/preview-server/routes/default-coding-agent.ts+++ b/packages/studio-server/src/preview-server/routes/default-coding-agent.ts@@ -4,23 +4,26 @@ import type {OpenInCodingAgentRequest,OpenInCodingAgentResponse,} from '@remotion/studio-shared';+import {getAppDiscovery} from '../../helpers/app-discovery';import {getAvailableCodingAgents,- getRunningCodingAgents,launchCodingAgent,} from '../../helpers/coding-agent-registry';import {getAvailableGitClients} from '../../helpers/git-client-registry';+import {getRecentlyUsedApps} from '../../helpers/recently-used-apps';import {getAvailableTerminals} from '../../helpers/terminal-registry';import type {ApiHandler} from '../api-types';export const getDefaultCodingAgentInfoHandler: ApiHandler<GetDefaultCodingAgentInfoRequest,GetDefaultCodingAgentInfoResponse-> = async ({getDefaultCodingAgent}) => {- const installedCodingAgents = await getAvailableCodingAgents();- const runningCodingAgents = await getRunningCodingAgents(- installedCodingAgents,- );+> = async ({getDefaultCodingAgent, input, remotionRoot}) => {+ await getRecentlyUsedApps({+ remotionRoot,+ type: 'coding-agent',+ recentlyUsedIds: input.recentlyUsedIds ?? null,+ });+ const {installedCodingAgents, runningCodingAgents} = await getAppDiscovery();const installedTerminals = await getAvailableTerminals();const installedGitClients = await getAvailableGitClients();return {diff --git a/packages/studio-server/src/preview-server/routes/default-editor.ts b/packages/studio-server/src/preview-server/routes/default-editor.tsindex b724917efb..ef2bd6a6da 100644--- a/packages/studio-server/src/preview-server/routes/default-editor.ts+++ b/packages/studio-server/src/preview-server/routes/default-editor.ts@@ -2,47 +2,18 @@ import type {GetDefaultEditorInfoRequest,GetDefaultEditorInfoResponse,} from '@remotion/studio-shared';-import {resolveCustomEditorExecutable} from '../../helpers/custom-editor';-import {- getAvailableEditors,- getRunningEditors,-} from '../../helpers/editor-registry';+import {getEditorInfo} from '../../helpers/app-discovery';+import {getRecentlyUsedApps} from '../../helpers/recently-used-apps';import type {ApiHandler} from '../api-types';export const getDefaultEditorInfoHandler: ApiHandler<GetDefaultEditorInfoRequest,GetDefaultEditorInfoResponse-> = async ({getDefaultEditor}) => {- const installedEditors = await getAvailableEditors();- const runningEditors = await getRunningEditors(installedEditors);- const configuredEditor = getDefaultEditor();- const customEditor =- configuredEditor &&- typeof configuredEditor === 'object' &&- resolveCustomEditorExecutable(configuredEditor)- ? configuredEditor- : null;- return {- defaultEditor:- configuredEditor && typeof configuredEditor === 'object'- ? 'custom'- : configuredEditor,- runningEditors,- installedEditors: [- ...installedEditors.map(({id, name, nameWithType}) => ({- id,- name,- nameWithType,- })),- ...(customEditor- ? [- {- id: 'custom' as const,- name: customEditor.name,- nameWithType: customEditor.name,- },- ]- : []),- ],- };+> = async ({getDefaultEditor, input, remotionRoot}) => {+ await getRecentlyUsedApps({+ remotionRoot,+ type: 'editor',+ recentlyUsedIds: input.recentlyUsedIds ?? null,+ });+ return getEditorInfo(getDefaultEditor());};diff --git a/packages/studio-server/src/start-studio.ts b/packages/studio-server/src/start-studio.tsindex f1e77e9576..46495c4e1b 100644--- a/packages/studio-server/src/start-studio.ts+++ b/packages/studio-server/src/start-studio.ts@@ -21,7 +21,6 @@ import type {import {getFileWatcherRegistry} from './file-watcher';import {getNetworkAddress} from './get-network-address';import {maybeOpenBrowser} from './maybe-open-browser';-import {registerOpenBrowserShortcut} from './open-browser-shortcut';import type {QueueMethods} from './preview-server/api-types';import {noOpUntilRestart} from './preview-server/close-and-restart';import {getAbsolutePublicDir} from './preview-server/get-absolute-public-dir';@@ -32,6 +31,7 @@ import {import {getFiles, initPublicFolderWatch} from './preview-server/public-folder';import {startServer} from './preview-server/start-server';import {printServerReadyComment, setServerReadyComment} from './server-ready';+import {registerStudioShortcuts} from './studio-shortcuts';import {watchRootFile} from './watch-root-file';export type StartStudioResult =@@ -233,11 +233,14 @@ export const startStudio = async ({printServerReadyComment('Server ready', logLevel);RenderInternals.Log.info({indent: false, logLevel}, 'Building...');const studioUrl = `http://localhost:${port}`;- const openBrowserShortcut = registerOpenBrowserShortcut({+ const studioShortcuts = registerStudioShortcuts({browserArgs,browserFlag,url: studioUrl,logLevel,+ remotionRoot,+ getDefaultEditor,+ getDefaultCodingAgent,});let action: 'restart' | 'shutdown';@@ -252,7 +255,7 @@ export const startStudio = async ({action = await noOpUntilRestart();} finally {- openBrowserShortcut.cleanup();+ studioShortcuts.cleanup();}RenderInternals.Log.info(diff --git a/packages/studio-server/src/studio-shortcuts.ts b/packages/studio-server/src/studio-shortcuts.tsnew file mode 100644index 0000000000..bf80ab044c--- /dev/null+++ b/packages/studio-server/src/studio-shortcuts.ts@@ -0,0 +1,273 @@+import * as readline from 'node:readline';+import type {+ DefaultCodingAgent,+ DefaultEditor,+ LogLevel,+} from '@remotion/renderer';+import {RenderInternals} from '@remotion/renderer';+import {+ getPreferredApp,+ preferredFallbackEditorIds,+} from '@remotion/studio-shared';+import {focusBrowserTabByOrigin} from './better-opn';+import {getAppDiscovery, getEditorInfo} from './helpers/app-discovery';+import {+ launchCodingAgent,+ type InstalledCodingAgent,+} from './helpers/coding-agent-registry';+import {launchCustomEditor} from './helpers/custom-editor';+import {launchEditor} from './helpers/open-in-editor';+import {getRecentlyUsedApps} from './helpers/recently-used-apps';+import {resolveEditor, type ResolvedEditor} from './helpers/resolve-editor';+import {maybeOpenBrowser} from './maybe-open-browser';+import {clearPrintPortMessageTimeout} from './preview-server/live-events';++type Key = {+ name?: string;+ ctrl?: boolean;+ meta?: boolean;+};++export const registerStudioShortcuts = ({+ browserArgs,+ browserFlag,+ url,+ logLevel,+ remotionRoot,+ getDefaultEditor,+ getDefaultCodingAgent,+}: {+ browserArgs: string;+ browserFlag: string;+ url: string;+ logLevel: LogLevel;+ remotionRoot: string;+ getDefaultEditor: () => DefaultEditor | null;+ getDefaultCodingAgent: () => DefaultCodingAgent | null;+}): {registered: boolean; cleanup: () => void} => {+ if (!process.stdin.isTTY) {+ return {registered: false, cleanup: () => undefined};+ }++ if (typeof process.stdin.setRawMode !== 'function') {+ return {registered: false, cleanup: () => undefined};+ }++ const wasRaw = process.stdin.isRaw;+ const shouldPauseAfterCleanup = process.stdin.isPaused();+ let cleanedUp = false;+ let isOpeningBrowser = false;+ let editor: ResolvedEditor | null = null;+ let codingAgent: InstalledCodingAgent | null = null;+ const openingApps = new Set<string>();++ const discoverShortcuts = async () => {+ const [discovery, editorInfo, recentEditors, recentCodingAgents] =+ await Promise.all([+ getAppDiscovery(),+ getEditorInfo(getDefaultEditor()),+ getRecentlyUsedApps({+ remotionRoot,+ type: 'editor',+ recentlyUsedIds: null,+ }),+ getRecentlyUsedApps({+ remotionRoot,+ type: 'coding-agent',+ recentlyUsedIds: null,+ }),+ ]);+ const preferredEditor = getPreferredApp({+ installedApps: editorInfo.installedEditors,+ configuredId: editorInfo.defaultEditor,+ runningIds: editorInfo.runningEditors ?? [],+ recentlyUsedIds: recentEditors,+ fallbackIds: preferredFallbackEditorIds,+ });+ editor = preferredEditor+ ? await resolveEditor({+ defaultEditor: getDefaultEditor(),+ preferredEditor: preferredEditor.id,+ logLevel,+ })+ : null;+ codingAgent = getPreferredApp({+ installedApps: discovery.installedCodingAgents,+ configuredId: getDefaultCodingAgent(),+ runningIds: discovery.runningCodingAgents,+ recentlyUsedIds: recentCodingAgents,+ fallbackIds: discovery.installedCodingAgents.map(({id}) => id),+ });+ };++ const printShortcuts = () => {+ if (cleanedUp) {+ return;+ }++ const shortcuts = [+ '[s] Open Studio',+ ...(codingAgent ? [`[a] Open agent (${codingAgent.name})`] : []),+ ...(editor+ ? [+ `[c] Open editor (${editor.name === 'Code' ? 'VS Code' : editor.name})`,+ ]+ : []),+ ];+ RenderInternals.Log.info(+ {indent: false, logLevel},+ RenderInternals.chalk.gray(shortcuts.join(' ')),+ );+ };++ const openApp = async (key: 'a' | 'c') => {+ if (openingApps.has(key) || cleanedUp) {+ return;+ }++ openingApps.add(key);+ try {+ if (key === 'a' && codingAgent) {+ await launchCodingAgent({+ codingAgent,+ projectPath: remotionRoot,+ logLevel,+ prompt: null,+ });+ } else if (key === 'c' && editor) {+ if (editor.type === 'custom') {+ await launchCustomEditor({+ editor: editor.editor,+ resolvedExecutable: editor,+ targetPath: remotionRoot,+ lineNumber: 1,+ columnNumber: 1,+ logLevel,+ spawnProcess: null,+ });+ } else {+ await launchEditor(+ {+ editor,+ fileName: remotionRoot,+ lineNumber: 1,+ colNumber: 1,+ vsCodeNewWindow: false,+ logLevel,+ },+ remotionRoot,+ );+ }+ }+ } catch (err) {+ RenderInternals.Log.error(+ {indent: false, logLevel},+ key === 'a' ? 'Could not open coding agent:' : 'Could not open editor:',+ err,+ );+ } finally {+ openingApps.delete(key);+ }+ };++ const cleanup = () => {+ if (cleanedUp) {+ return;+ }++ cleanedUp = true;+ process.stdin.removeListener('keypress', onKeypress);+ process.removeListener('SIGINT', cleanup);+ process.removeListener('exit', cleanup);++ if (!wasRaw && process.stdin.isTTY) {+ process.stdin.setRawMode(false);+ }++ if (shouldPauseAfterCleanup) {+ process.stdin.pause();+ }+ };++ const openStudio = async () => {+ if (isOpeningBrowser) {+ return;+ }++ isOpeningBrowser = true;+ clearPrintPortMessageTimeout();+ try {+ const didFocus = await focusBrowserTabByOrigin({+ url,+ browserArgs,+ browserFlag,+ });+ if (didFocus) {+ RenderInternals.Log.info(+ {indent: false, logLevel},+ RenderInternals.chalk.blue(`Opened ${url} in browser`),+ );+ return;+ }++ const result = await maybeOpenBrowser({+ browserArgs,+ browserFlag,+ shouldOpenBrowser: true,+ url,+ logLevel,+ });+ if (result.didOpenBrowser) {+ RenderInternals.Log.info(+ {indent: false, logLevel},+ RenderInternals.chalk.blue(`Opened ${url} in browser`),+ );+ }+ } catch (err) {+ RenderInternals.Log.error(+ {indent: false, logLevel},+ 'Could not open browser:',+ err,+ );+ } finally {+ isOpeningBrowser = false;+ }+ };++ function onKeypress(_str: string, key: Key | undefined) {+ if (key?.ctrl && key.name === 'c') {+ cleanup();+ process.kill(process.pid, 'SIGINT');+ return;+ }++ if (key?.meta || key?.ctrl) {+ return;+ }++ if (key?.name === 's') {+ openStudio().catch(() => undefined);+ } else if (key?.name === 'a' || key?.name === 'c') {+ openApp(key.name).catch(() => undefined);+ }+ }++ readline.emitKeypressEvents(process.stdin);+ process.stdin.setRawMode(true);+ process.stdin.resume();+ process.stdin.on('keypress', onKeypress);+ process.once('SIGINT', cleanup);+ process.once('exit', cleanup);+ // Discovery may finish after other startup logs; never await it here.+ discoverShortcuts()+ .catch((err) => {+ RenderInternals.Log.verbose(+ {indent: false, logLevel},+ 'Could not discover Studio shortcuts:',+ err,+ );+ })+ .then(printShortcuts);++ return {registered: true, cleanup};+};diff --git a/packages/studio-shared/src/api-requests.ts b/packages/studio-shared/src/api-requests.tsindex 14371932ea..5a12300e6e 100644--- a/packages/studio-shared/src/api-requests.ts+++ b/packages/studio-shared/src/api-requests.ts@@ -1396,7 +1396,9 @@ export type UpdateConfigResponse =| {success: true}| {success: false; reason: string};-export type GetDefaultEditorInfoRequest = {};+export type GetDefaultEditorInfoRequest = {+ recentlyUsedIds?: readonly EditorPickerId[];+};export type EditorPickerId = BuiltInEditor | 'custom';export type GetDefaultEditorInfoResponse = {defaultEditor: EditorPickerId | null;@@ -1408,7 +1410,9 @@ export type GetDefaultEditorInfoResponse = {}[];};-export type GetDefaultCodingAgentInfoRequest = {};+export type GetDefaultCodingAgentInfoRequest = {+ recentlyUsedIds?: readonly DefaultCodingAgent[];+};export type GetDefaultCodingAgentInfoResponse = {defaultCodingAgent: DefaultCodingAgent | null;runningCodingAgents: readonly DefaultCodingAgent[] | null;diff --git a/packages/studio-shared/src/get-preferred-app.ts b/packages/studio-shared/src/get-preferred-app.tsnew file mode 100644index 0000000000..bffeb478b7--- /dev/null+++ b/packages/studio-shared/src/get-preferred-app.ts@@ -0,0 +1,53 @@+import type {EditorPickerId} from './api-requests';++export const preferredFallbackEditorIds: readonly EditorPickerId[] = [+ 'zed',+ 'vscode',+ 'cursor',+];++export const getPreferredApp = <+ App extends {id: string; nameWithType: string},+>({+ installedApps,+ configuredId,+ runningIds,+ recentlyUsedIds,+ fallbackIds,+}: {+ installedApps: readonly App[];+ configuredId: string | null;+ runningIds: readonly string[];+ recentlyUsedIds: readonly string[];+ fallbackIds: readonly string[];+}): App | null => {+ const configuredApp = installedApps.find((app) => app.id === configuredId);+ if (configuredApp) {+ return configuredApp;+ }++ return (+ [...installedApps]+ .sort((a, b) => {+ const runningDifference =+ Number(runningIds.includes(b.id)) - Number(runningIds.includes(a.id));+ if (runningDifference !== 0) {+ return runningDifference;+ }++ for (const ids of [recentlyUsedIds, fallbackIds]) {+ const aIndex = ids.indexOf(a.id);+ const bIndex = ids.indexOf(b.id);+ const difference =+ (aIndex === -1 ? ids.length : aIndex) -+ (bIndex === -1 ? ids.length : bIndex);+ if (difference !== 0) {+ return difference;+ }+ }++ return a.nameWithType.localeCompare(b.nameWithType);+ })+ .at(0) ?? null+ );+};diff --git a/packages/studio-shared/src/index.ts b/packages/studio-shared/src/index.tsindex 544f79b352..702d9625ac 100644--- a/packages/studio-shared/src/index.ts+++ b/packages/studio-shared/src/index.ts@@ -297,6 +297,7 @@ export {getLocationFromBuildError,} from './get-location-from-build-error';export {getProjectName} from './get-project-name';+export {getPreferredApp, preferredFallbackEditorIds} from './get-preferred-app';export type {GitSource} from './git-source';export {HotMiddlewareMessage,diff --git a/packages/studio/src/components/SettingsContext.tsx b/packages/studio/src/components/SettingsContext.tsxindex 18ac1d11a6..268aef6afe 100644--- a/packages/studio/src/components/SettingsContext.tsx+++ b/packages/studio/src/components/SettingsContext.tsx@@ -15,7 +15,11 @@ import React, {} from 'react';import {getBrowserStudioOperations} from '../helpers/browser-studio-operations';import {StudioServerConnectionCtx} from '../helpers/client-id';-import {appSelectedEvent} from '../state/recently-used-apps';+import {+ appSelectedEvent,+ codingAgentHistory,+ editorHistory,+} from '../state/recently-used-apps';import {callApi} from './call-api';import {showNotification} from './Notifications/NotificationCenter';import {UpdateStatusProvider} from './UpdateStatusContext';@@ -120,8 +124,16 @@ export const SettingsProvider: React.FC<{const requestController = new AbortController();controller = requestController;Promise.all([- callApi('/api/default-coding-agent-info', {}, requestController.signal),- callApi('/api/default-editor-info', {}, requestController.signal),+ callApi(+ '/api/default-coding-agent-info',+ {recentlyUsedIds: codingAgentHistory.getRecentlyUsed()},+ requestController.signal,+ ),+ callApi(+ '/api/default-editor-info',+ {recentlyUsedIds: editorHistory.getRecentlyUsed()},+ requestController.signal,+ ),]).then(([codingAgentInfo, editorInfo]) => {if (requestController.signal.aborted) {diff --git a/packages/studio/src/components/use-default-editor-info.ts b/packages/studio/src/components/use-default-editor-info.tsindex b96f0d35ca..0f5cfb00f4 100644--- a/packages/studio/src/components/use-default-editor-info.ts+++ b/packages/studio/src/components/use-default-editor-info.ts@@ -3,6 +3,7 @@ import type {GetDefaultCodingAgentInfoResponse,GetDefaultEditorInfoResponse,} from '@remotion/studio-shared';+import {preferredFallbackEditorIds} from '@remotion/studio-shared';import {getBrowserStudioOperations} from '../helpers/browser-studio-operations';import {getPreferredApp} from '../helpers/get-preferred-app';import {codingAgentHistory, editorHistory} from '../state/recently-used-apps';@@ -20,12 +21,6 @@ export const canOpenInEditor = (previewServerConnected: boolean) => {return previewServerConnected && getBrowserStudioOperations() === null;};-const preferredFallbackEditorIds: EditorPickerId[] = [- 'zed',- 'vscode',- 'cursor',-];-export const getPreferredEditorId = (editorInfo: GetDefaultEditorInfoResponse | null,): EditorPickerId | null => {diff --git a/packages/studio/src/helpers/get-preferred-app.ts b/packages/studio/src/helpers/get-preferred-app.tsindex 0b02c6e758..45209b05db 100644--- a/packages/studio/src/helpers/get-preferred-app.ts+++ b/packages/studio/src/helpers/get-preferred-app.ts@@ -1,45 +1 @@-export const getPreferredApp = <- App extends {id: string; nameWithType: string},->({- installedApps,- configuredId,- runningIds,- recentlyUsedIds,- fallbackIds,-}: {- installedApps: readonly App[];- configuredId: string | null;- runningIds: readonly string[];- recentlyUsedIds: readonly string[];- fallbackIds: readonly string[];-}): App | null => {- const configuredApp = installedApps.find((app) => app.id === configuredId);- if (configuredApp) {- return configuredApp;- }-- return (- [...installedApps]- .sort((a, b) => {- const runningDifference =- Number(runningIds.includes(b.id)) - Number(runningIds.includes(a.id));- if (runningDifference !== 0) {- return runningDifference;- }-- for (const ids of [recentlyUsedIds, fallbackIds]) {- const aIndex = ids.indexOf(a.id);- const bIndex = ids.indexOf(b.id);- const difference =- (aIndex === -1 ? ids.length : aIndex) -- (bIndex === -1 ? ids.length : bIndex);- if (difference !== 0) {- return difference;- }- }-- return a.nameWithType.localeCompare(b.nameWithType);- })- .at(0) ?? null- );-};+export {getPreferredApp} from '@remotion/studio-shared';