🎥 Make videos programmatically with React
`@remotion/studio`: Add coding agents to app menu (#10151)
Jonny Burger0f7080aaa212
diff --git a/packages/docs/docs/config.mdx b/packages/docs/docs/config.mdxindex 9db9981753..a37b881659 100644--- a/packages/docs/docs/config.mdx+++ b/packages/docs/docs/config.mdx@@ -243,7 +243,7 @@ import {Config} from '@remotion/cli/config';Config.setDefaultCodingAgent('codex');```-Available coding agents: `codex`, `cursor`, `github-copilot`, and `claude-code`.+Available coding agents: `codex`, `cursor`, `copilot`, and `claude-code`.The [`--coding-agent`](/docs/cli/studio#--coding-agent) command line flag takes precedence over this option.diff --git a/packages/example/e2e/inspector-section-collapse.test.mts b/packages/example/e2e/inspector-section-collapse.test.mtsindex ceb7da32f4..4b47e648e8 100644--- a/packages/example/e2e/inspector-section-collapse.test.mts+++ b/packages/example/e2e/inspector-section-collapse.test.mts@@ -23,11 +23,15 @@ test.describe('inspector section collapse', () => {{timeout: 30_000},);- await page.locator('[title="Foreground"]').first().click();-- await expect(- page.getByRole('button', {name: 'Expand Background', exact: true}),- ).toBeVisible({timeout: 15_000});+ const foreground = page.locator('[title="Foreground"]').first();+ const expandBackground = page.getByRole('button', {+ name: 'Expand Background',+ exact: true,+ });+ await expect(async () => {+ await foreground.click();+ await expect(expandBackground).toBeVisible({timeout: 1_000});+ }).toPass({timeout: 15_000});await expect(page.getByRole('button', {name: 'Expand Border', exact: true}),).toBeVisible();diff --git a/packages/example/e2e/studio.test.mts b/packages/example/e2e/studio.test.mtsindex d62b859d3d..4eed5eb979 100644--- a/packages/example/e2e/studio.test.mts+++ b/packages/example/e2e/studio.test.mts@@ -75,6 +75,78 @@ test.describe('visual mode', () => {});});+ test('should pass the copied inspector prompt to editable coding agents', async ({+ context,+ page,+ }) => {+ await context.grantPermissions(['clipboard-read', 'clipboard-write'], {+ origin: STUDIO_URL,+ });+ await page.route('**/api/default-coding-agent-info', async (route) => {+ await route.fulfill({+ json: {+ success: true,+ data: {+ defaultCodingAgent: null,+ installedCodingAgents: [+ {id: 'codex', iconDataUrl: null, name: 'Codex'},+ {+ id: 'copilot',+ iconDataUrl: null,+ name: 'GitHub Copilot',+ },+ ],+ },+ },+ });+ });++ const launchRequests: unknown[] = [];+ await page.route('**/api/open-in-coding-agent', async (route) => {+ launchRequests.push(route.request().postDataJSON());+ await route.fulfill({+ json: {success: true, data: {success: true}},+ });+ });++ await page.goto(`${STUDIO_URL}/schema-test`);+ await page.locator('[data-sidebar-toggle="right"]').click();+ const sourceLocation = page+ .getByRole('group', {name: 'Inspector source location'})+ .first();+ await expect(sourceLocation).toBeVisible({timeout: 15_000});+ await sourceLocation.hover();++ await sourceLocation+ .getByRole('button', {name: 'Copy location for agents'})+ .click();+ const copiedPrompt = await page.evaluate(() =>+ navigator.clipboard.readText(),+ );+ expect(copiedPrompt.length).toBeGreaterThan(0);++ const openInAnotherApp = sourceLocation.getByRole('button', {+ name: 'Open in another app',+ });+ await openInAnotherApp.click();+ await page.getByRole('button', {name: 'Codex', exact: true}).click();+ await expect.poll(() => launchRequests.length).toBe(1);+ expect(launchRequests[0]).toEqual({+ codingAgentId: 'codex',+ prompt: copiedPrompt,+ });++ await openInAnotherApp.click();+ await page+ .getByRole('button', {name: 'GitHub Copilot', exact: true})+ .click();+ await expect.poll(() => launchRequests.length).toBe(2);+ expect(launchRequests[1]).toEqual({+ codingAgentId: 'copilot',+ prompt: null,+ });+ });+test('should open submenus toward the side with more space', async ({page,}) => {diff --git a/packages/renderer/src/options/default-coding-agent.tsx b/packages/renderer/src/options/default-coding-agent.tsxindex 86c9b620e0..9733cfa5b7 100644--- a/packages/renderer/src/options/default-coding-agent.tsx+++ b/packages/renderer/src/options/default-coding-agent.tsx@@ -3,7 +3,7 @@ import type {AnyRemotionOption} from './option';export const defaultCodingAgentIds = ['codex','cursor',- 'github-copilot',+ 'copilot','claude-code',] as const;diff --git a/packages/studio-server/src/helpers/coding-agent-registry.ts b/packages/studio-server/src/helpers/coding-agent-registry.tsindex fcb8c11eec..95afdf6102 100644--- a/packages/studio-server/src/helpers/coding-agent-registry.ts+++ b/packages/studio-server/src/helpers/coding-agent-registry.ts@@ -1,10 +1,10 @@-import {execFile} from 'node:child_process';-import {existsSync} from 'node:fs';+import {execFile, spawn} from 'node:child_process';+import {existsSync, readFileSync} from 'node:fs';import {homedir} from 'node:os';import path from 'node:path';import {promisify} from 'node:util';-import type {DefaultCodingAgent} from '@remotion/renderer';-import {defaultCodingAgentIds} from '@remotion/renderer';+import type {DefaultCodingAgent, LogLevel} from '@remotion/renderer';+import {defaultCodingAgentIds, RenderInternals} from '@remotion/renderer';const execFilePromise = promisify(execFile);@@ -12,43 +12,249 @@ export type InstalledCodingAgent = {id: DefaultCodingAgent;name: string;applicationPath: string;+ iconDataUrl: string | null;+ platform: SupportedCodingAgentPlatform;+ launchMode: 'direct' | 'terminal';+ terminal: InstalledTerminal | null;};-type CodingAgentDefinition = {- name: string;+type SupportedCodingAgentPlatform = 'darwin' | 'linux' | 'win32';++type LinuxTerminalId =+ | 'x-terminal-emulator'+ | 'gnome-terminal'+ | 'konsole'+ | 'kitty'+ | 'alacritty'+ | 'wezterm'+ | 'xterm';++type InstalledTerminal = {+ id: LinuxTerminalId | 'cmd';+ path: string;+};++type DarwinCodingAgentVariant = {bundleIdentifiers: readonly string[];applicationNames: readonly string[];};+type ExecutableCodingAgentVariant = {+ paths: (context: CodingAgentDiscoveryContext) => readonly string[];+ commands: readonly string[];+ launchMode: 'direct' | 'terminal';+};++type CodingAgentDefinition = {+ name: string;+ darwin: DarwinCodingAgentVariant;+ linux: readonly ExecutableCodingAgentVariant[];+ win32: readonly ExecutableCodingAgentVariant[];+};++type LinuxTerminalDefinition = {+ id: LinuxTerminalId;+ paths: readonly string[];+ commands: readonly string[];+};++export type CodingAgentDiscoveryContext = {+ platform: NodeJS.Platform;+ env: NodeJS.ProcessEnv;+ homeDirectory: string;+ pathExists: (filePath: string) => boolean;+ findMacApplications: (bundleIdentifier: string) => Promise<readonly string[]>;+};++const getLinuxCommandPaths = (+ context: CodingAgentDiscoveryContext,+ command: string,+) => [+ path.posix.join('/usr/local/bin', command),+ path.posix.join('/usr/bin', command),+ path.posix.join(context.homeDirectory, '.local/bin', command),+];++const getWindowsCommandPaths = (+ context: CodingAgentDiscoveryContext,+ command: string,+) => [+ path.win32.join(context.homeDirectory, '.local', 'bin', `${command}.exe`),+ path.win32.join(context.homeDirectory, '.local', 'bin', `${command}.cmd`),+];++const getWindowsEnvironmentPaths = (+ context: CodingAgentDiscoveryContext,+ 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 codingAgentDefinitions = {codex: {name: 'Codex',- bundleIdentifiers: ['com.openai.codex'],- applicationNames: ['ChatGPT.app'],+ darwin: {+ bundleIdentifiers: ['com.openai.codex'],+ applicationNames: ['ChatGPT.app'],+ },+ linux: [+ {+ paths: (context) => getLinuxCommandPaths(context, 'codex'),+ commands: ['codex'],+ launchMode: 'terminal',+ },+ ],+ win32: [+ {+ paths: (context) => [+ ...getWindowsCommandPaths(context, 'codex'),+ ...(context.env.LOCALAPPDATA+ ? [+ path.win32.join(+ context.env.LOCALAPPDATA,+ 'OpenAI',+ 'Codex',+ 'bin',+ 'codex.exe',+ ),+ path.win32.join(+ context.env.LOCALAPPDATA,+ 'Packages',+ 'OpenAI.Codex_2p2nqsd0c76g0',+ 'LocalCache',+ 'Local',+ 'OpenAI',+ 'Codex',+ 'bin',+ 'codex.exe',+ ),+ ]+ : []),+ ],+ commands: ['codex.exe', 'codex.cmd'],+ launchMode: 'terminal',+ },+ ],},cursor: {name: 'Cursor',- bundleIdentifiers: ['com.todesktop.230313mzl4w4u92'],- applicationNames: ['Cursor.app'],+ darwin: {+ bundleIdentifiers: ['com.todesktop.230313mzl4w4u92'],+ applicationNames: ['Cursor.app'],+ },+ linux: [+ {+ paths: (context) => getLinuxCommandPaths(context, 'cursor'),+ commands: ['cursor'],+ launchMode: 'direct',+ },+ {+ paths: (context) => [+ ...getLinuxCommandPaths(context, 'cursor-agent'),+ path.posix.join(context.homeDirectory, '.cursor/bin/cursor-agent'),+ ],+ commands: ['cursor-agent'],+ launchMode: 'terminal',+ },+ ],+ win32: [+ {+ paths: (context) =>+ getWindowsEnvironmentPaths(context, ['cursor', 'Cursor.exe']),+ commands: ['Cursor.exe', 'cursor.cmd'],+ launchMode: 'direct',+ },+ {+ paths: (context) => getWindowsCommandPaths(context, 'cursor-agent'),+ commands: ['cursor-agent.exe', 'cursor-agent.cmd'],+ launchMode: 'terminal',+ },+ ],},- 'github-copilot': {+ copilot: {name: 'GitHub Copilot',- bundleIdentifiers: ['com.github.githubapp'],- applicationNames: ['GitHub Copilot.app'],+ darwin: {+ bundleIdentifiers: ['com.github.githubapp'],+ applicationNames: ['GitHub Copilot.app'],+ },+ linux: [+ {+ paths: (context) => getLinuxCommandPaths(context, 'copilot'),+ commands: ['copilot'],+ launchMode: 'terminal',+ },+ ],+ win32: [+ {+ paths: (context) => getWindowsCommandPaths(context, 'copilot'),+ commands: ['copilot.exe', 'copilot.cmd'],+ launchMode: 'terminal',+ },+ ],},'claude-code': {name: 'Claude Code',- bundleIdentifiers: ['com.anthropic.claudefordesktop'],- applicationNames: ['Claude.app'],+ darwin: {+ bundleIdentifiers: ['com.anthropic.claudefordesktop'],+ applicationNames: ['Claude.app'],+ },+ linux: [+ {+ paths: (context) => [+ ...getLinuxCommandPaths(context, 'claude'),+ path.posix.join(context.homeDirectory, '.claude/local/claude'),+ ],+ commands: ['claude'],+ launchMode: 'terminal',+ },+ ],+ win32: [+ {+ paths: (context) => getWindowsCommandPaths(context, 'claude'),+ commands: ['claude.exe', 'claude.cmd'],+ launchMode: 'terminal',+ },+ ],},} satisfies Record<DefaultCodingAgent, CodingAgentDefinition>;-export type CodingAgentDiscoveryContext = {- platform: NodeJS.Platform;- homeDirectory: string;- pathExists: (filePath: string) => boolean;- findMacApplications: (bundleIdentifier: string) => Promise<readonly string[]>;-};+const linuxTerminalDefinitions: readonly LinuxTerminalDefinition[] = [+ {+ id: 'x-terminal-emulator',+ paths: ['/usr/bin/x-terminal-emulator'],+ commands: ['x-terminal-emulator'],+ },+ {+ id: 'gnome-terminal',+ paths: ['/usr/bin/gnome-terminal'],+ commands: ['gnome-terminal'],+ },+ {+ id: 'konsole',+ paths: ['/usr/bin/konsole'],+ commands: ['konsole'],+ },+ {id: 'kitty', paths: ['/usr/bin/kitty'], commands: ['kitty']},+ {id: 'alacritty', paths: ['/usr/bin/alacritty'], commands: ['alacritty']},+ {id: 'wezterm', paths: ['/usr/bin/wezterm'], commands: ['wezterm']},+ {id: 'xterm', paths: ['/usr/bin/xterm'], commands: ['xterm']},+];const findMacApplications = async (bundleIdentifier: string,@@ -66,51 +272,157 @@ const findMacApplications = async (}};+const getBundledCodingAgentIconDataUrl = (id: DefaultCodingAgent): string =>+ `data:image/png;base64,${readFileSync(+ path.join(__dirname, '..', '..', 'web', 'coding-agent-icons', `${id}.png`),+ ).toString('base64')}`;+const defaultDiscoveryContext: CodingAgentDiscoveryContext = {platform: process.platform,+ env: process.env,homeDirectory: homedir(),pathExists: existsSync,findMacApplications,};+const getPathDirectories = (context: CodingAgentDiscoveryContext) => {+ const value = context.env.PATH ?? context.env.Path ?? '';+ return value.split(context.platform === 'win32' ? ';' : ':').filter(Boolean);+};++const findExecutable = ({+ paths,+ commands,+ context,+}: {+ paths: readonly string[];+ commands: readonly string[];+ context: CodingAgentDiscoveryContext;+}) => {+ for (const executablePath of paths) {+ 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 commands) {+ const executablePath = pathImplementation.join(directory, command);+ if (context.pathExists(executablePath)) {+ return executablePath;+ }+ }+ }++ return null;+};++const findLinuxTerminal = (+ context: CodingAgentDiscoveryContext,+): InstalledTerminal | null => {+ for (const definition of linuxTerminalDefinitions) {+ const terminalPath = findExecutable({+ paths: definition.paths,+ commands: definition.commands,+ context,+ });+ if (terminalPath) {+ return {id: definition.id, path: terminalPath};+ }+ }++ return null;+};+export const discoverAvailableCodingAgents = async (context: CodingAgentDiscoveryContext,): Promise<readonly InstalledCodingAgent[]> => {- if (context.platform !== 'darwin') {+ if (+ context.platform !== 'darwin' &&+ context.platform !== 'linux' &&+ context.platform !== 'win32'+ ) {return [];}- const installedCodingAgents: InstalledCodingAgent[] = [];+ const {platform} = context;+ const terminal: InstalledTerminal | null =+ platform === 'linux'+ ? findLinuxTerminal(context)+ : platform === 'win32'+ ? {+ id: 'cmd',+ path: context.env.ComSpec ?? context.env.COMSPEC ?? 'cmd.exe',+ }+ : null;+ const installedCodingAgents: Omit<InstalledCodingAgent, 'iconDataUrl'>[] = [];for (const id of defaultCodingAgentIds) {const definition = codingAgentDefinitions[id];- const discoveredApplications = (- await Promise.all(- definition.bundleIdentifiers.map((bundleIdentifier) =>- context.findMacApplications(bundleIdentifier),- ),- )- ).flat();- const knownApplications = definition.applicationNames.flatMap((name) => [- path.posix.join('/Applications', name),- path.posix.join(context.homeDirectory, 'Applications', name),- ]);+ if (platform === 'darwin') {+ const discoveredApplications = (+ await Promise.all(+ definition.darwin.bundleIdentifiers.map((bundleIdentifier) =>+ context.findMacApplications(bundleIdentifier),+ ),+ )+ ).flat();+ const knownApplications = definition.darwin.applicationNames.flatMap(+ (name) => [+ path.posix.join('/Applications', name),+ path.posix.join(context.homeDirectory, 'Applications', name),+ ],+ );- for (const applicationPath of new Set([- ...discoveredApplications,- ...knownApplications,- ])) {- if (context.pathExists(applicationPath)) {+ for (const applicationPath of new Set([+ ...discoveredApplications,+ ...knownApplications,+ ])) {+ if (context.pathExists(applicationPath)) {+ installedCodingAgents.push({+ applicationPath,+ id,+ launchMode: 'direct',+ name: definition.name,+ platform,+ terminal: null,+ });+ break;+ }+ }++ continue;+ }++ for (const variant of definition[platform]) {+ if (variant.launchMode === 'terminal' && terminal === null) {+ continue;+ }++ const applicationPath = findExecutable({+ paths: variant.paths(context),+ commands: variant.commands,+ context,+ });+ if (applicationPath) {installedCodingAgents.push({applicationPath,id,+ launchMode: variant.launchMode,name: definition.name,+ platform,+ terminal: variant.launchMode === 'terminal' ? terminal : null,});break;}}}- return installedCodingAgents;+ return installedCodingAgents.map((codingAgent) => ({+ ...codingAgent,+ iconDataUrl: getBundledCodingAgentIconDataUrl(codingAgent.id),+ }));};let availableCodingAgents: Promise<readonly InstalledCodingAgent[]> | null =@@ -122,3 +434,271 @@ export const getAvailableCodingAgents = () => {);return availableCodingAgents;};++export const getCodingAgentLaunchCommand = ({+ codingAgent,+ projectPath,+}: {+ codingAgent: InstalledCodingAgent;+ projectPath: string;+}): {command: string; args: string[]; cwd: string | null} => {+ if (codingAgent.platform === 'darwin') {+ switch (codingAgent.id) {+ case 'codex':+ return {+ command: path.posix.join(+ codingAgent.applicationPath,+ 'Contents/Resources/codex',+ ),+ args: ['app', projectPath],+ cwd: null,+ };+ case 'cursor':+ return {+ command: path.posix.join(+ codingAgent.applicationPath,+ 'Contents/Resources/app/bin/cursor',+ ),+ args: ['--glass', '--suppress-popups-on-startup', projectPath],+ cwd: null,+ };+ case 'copilot':+ case 'claude-code':+ return {+ command: 'open',+ args: ['-a', codingAgent.applicationPath, projectPath],+ cwd: null,+ };+ default: {+ const invalidId: never = codingAgent.id;+ throw new Error(`Unknown coding agent: ${invalidId}`);+ }+ }+ }++ if (codingAgent.launchMode === 'direct') {+ return {+ command: codingAgent.applicationPath,+ args:+ codingAgent.id === 'cursor'+ ? ['--glass', '--suppress-popups-on-startup', projectPath]+ : [projectPath],+ cwd: null,+ };+ }++ if (codingAgent.terminal === null) {+ throw new Error(`No terminal found for coding agent ${codingAgent.name}`);+ }++ if (codingAgent.terminal.id === 'cmd') {+ return {+ command: codingAgent.terminal.path,+ args: [+ '/d',+ '/s',+ '/c',+ 'start',+ '',+ '/d',+ projectPath,+ codingAgent.terminal.path,+ '/k',+ codingAgent.applicationPath,+ ],+ cwd: null,+ };+ }++ const command = codingAgent.applicationPath;+ switch (codingAgent.terminal.id) {+ case 'gnome-terminal':+ return {+ command: codingAgent.terminal.path,+ args: [`--working-directory=${projectPath}`, '--', command],+ cwd: projectPath,+ };+ case 'konsole':+ return {+ command: codingAgent.terminal.path,+ args: ['--workdir', projectPath, '-e', command],+ cwd: projectPath,+ };+ case 'kitty':+ return {+ command: codingAgent.terminal.path,+ args: ['--directory', projectPath, command],+ cwd: projectPath,+ };+ case 'alacritty':+ return {+ command: codingAgent.terminal.path,+ args: ['--working-directory', projectPath, '-e', command],+ cwd: projectPath,+ };+ case 'wezterm':+ return {+ command: codingAgent.terminal.path,+ args: ['start', '--cwd', projectPath, '--', command],+ cwd: projectPath,+ };+ case 'x-terminal-emulator':+ case 'xterm':+ return {+ command: codingAgent.terminal.path,+ args: ['-e', command],+ cwd: projectPath,+ };+ default: {+ const invalidTerminal: never = codingAgent.terminal.id;+ throw new Error(`Unknown terminal: ${invalidTerminal}`);+ }+ }+};++type CodingAgentLaunchCommand = ReturnType<+ typeof getCodingAgentLaunchCommand+> & {+ waitForExit: boolean;+};++export const getCodingAgentLaunchCommands = ({+ codingAgent,+ projectPath,+ prompt,+}: {+ codingAgent: InstalledCodingAgent;+ projectPath: string;+ prompt: string | null;+}): readonly CodingAgentLaunchCommand[] => {+ const defaultCommand = {+ ...getCodingAgentLaunchCommand({codingAgent, projectPath}),+ waitForExit: false,+ };++ if (+ prompt === null ||+ codingAgent.platform !== 'darwin' ||+ codingAgent.id === 'copilot'+ ) {+ return [defaultCommand];+ }++ switch (codingAgent.id) {+ case 'codex': {+ const deepLink = new URL('codex://new');+ deepLink.searchParams.set('path', projectPath);+ deepLink.searchParams.set('prompt', prompt);+ return [+ {+ command: 'open',+ args: [deepLink.toString()],+ cwd: null,+ waitForExit: false,+ },+ ];+ }++ case 'cursor': {+ const deepLink = new URL('cursor://anysphere.cursor-deeplink/prompt');+ deepLink.searchParams.set('text', prompt);+ return [+ {...defaultCommand, waitForExit: true},+ {+ command: 'open',+ args: [deepLink.toString()],+ cwd: null,+ waitForExit: false,+ },+ ];+ }++ case 'claude-code': {+ const deepLink = new URL('claude://code/new');+ deepLink.searchParams.set('folder', projectPath);+ deepLink.searchParams.set('q', prompt);+ return [+ {+ command: 'open',+ args: [deepLink.toString()],+ cwd: null,+ waitForExit: false,+ },+ ];+ }++ default: {+ const invalidId: never = codingAgent.id;+ throw new Error(`Unknown coding agent: ${invalidId}`);+ }+ }+};++export const launchCodingAgent = async ({+ codingAgent,+ projectPath,+ logLevel,+ prompt,+}: {+ codingAgent: InstalledCodingAgent;+ projectPath: string;+ logLevel: LogLevel;+ prompt: string | null;+}): Promise<boolean> => {+ const commands = getCodingAgentLaunchCommands({+ codingAgent,+ projectPath,+ prompt,+ });++ for (const {command, args, cwd, waitForExit} of commands) {+ const success = await new Promise<boolean>((resolve) => {+ try {+ const child = spawn(command, args, {+ cwd: cwd ?? undefined,+ detached: !waitForExit,+ shell: false,+ stdio: 'ignore',+ });+ child.once('error', (error) => {+ RenderInternals.Log.error(+ {indent: false, logLevel},+ `Could not launch coding agent ${codingAgent.name}:`,+ error,+ );+ resolve(false);+ });+ if (waitForExit) {+ child.once('exit', (code) => {+ if (code !== 0) {+ RenderInternals.Log.error(+ {indent: false, logLevel},+ `Could not launch coding agent ${codingAgent.name}: Process exited with code ${code}`,+ );+ }++ resolve(code === 0);+ });+ } else {+ child.once('spawn', () => {+ child.unref();+ resolve(true);+ });+ }+ } catch (error) {+ RenderInternals.Log.error(+ {indent: false, logLevel},+ `Could not launch coding agent ${codingAgent.name}:`,+ error,+ );+ resolve(false);+ }+ });++ if (!success) {+ return false;+ }+ }++ return true;+};diff --git a/packages/studio-server/src/preview-server/api-routes.ts b/packages/studio-server/src/preview-server/api-routes.tsindex e776e56fc7..d3b08f324f 100644--- a/packages/studio-server/src/preview-server/api-routes.ts+++ b/packages/studio-server/src/preview-server/api-routes.ts@@ -13,6 +13,7 @@ import {compositionComponentInfoHandler} from './routes/composition-component-inimport {convertFigmaClipboardToSvgHandler} from './routes/convert-figma-clipboard-to-svg';import {getDefaultCodingAgentInfoHandler,+ openInCodingAgentHandler,updateDefaultCodingAgentHandler,} from './routes/default-coding-agent';import {@@ -79,6 +80,7 @@ export const allApiRoutes: {'/api/find-in-file': findInFileHandler,'/api/open-in-file-explorer': handleOpenInFileExplorer,'/api/open-in-editor': openInEditorHandler,+ '/api/open-in-coding-agent': openInCodingAgentHandler,'/api/register-client-render': registerClientRenderHandler,'/api/unregister-client-render': unregisterClientRenderHandler,'/api/update-default-props': updateDefaultPropsHandler,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 5b3acbcbb8..e22542675c 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,13 +4,18 @@ import {defaultCodingAgentIds} from '@remotion/renderer';import type {GetDefaultCodingAgentInfoRequest,GetDefaultCodingAgentInfoResponse,+ OpenInCodingAgentRequest,+ OpenInCodingAgentResponse,UpdateDefaultCodingAgentRequest,UpdateDefaultCodingAgentResponse,} from '@remotion/studio-shared';import * as recast from 'recast';import {parseAst} from '../../codemods/parse-ast';import {writeFileAndNotifyFileWatchers} from '../../file-watcher';-import {getAvailableCodingAgents} from '../../helpers/coding-agent-registry';+import {+ getAvailableCodingAgents,+ launchCodingAgent,+} from '../../helpers/coding-agent-registry';import type {ApiHandler} from '../api-types';export const updateDefaultCodingAgentInConfig = ({@@ -59,10 +64,34 @@ export const getDefaultCodingAgentInfoHandler: ApiHandler<const installedCodingAgents = await getAvailableCodingAgents();return {defaultCodingAgent: getDefaultCodingAgent(),- installedCodingAgents: installedCodingAgents.map(({id, name}) => ({- id,- name,- })),+ installedCodingAgents: installedCodingAgents.map(+ ({iconDataUrl, id, name}) => ({+ iconDataUrl,+ id,+ name,+ }),+ ),+ };+};++export const openInCodingAgentHandler: ApiHandler<+ OpenInCodingAgentRequest,+ OpenInCodingAgentResponse+> = async ({input, logLevel, remotionRoot}) => {+ const codingAgent = (await getAvailableCodingAgents()).find(+ (agent) => agent.id === input.codingAgentId,+ );+ if (!codingAgent) {+ return {success: false};+ }++ return {+ success: await launchCodingAgent({+ codingAgent,+ projectPath: remotionRoot,+ logLevel,+ prompt: input.prompt,+ }),};};diff --git a/packages/studio-server/src/test/coding-agent-registry.test.ts b/packages/studio-server/src/test/coding-agent-registry.test.tsindex 259d830352..40e922507f 100644--- a/packages/studio-server/src/test/coding-agent-registry.test.ts+++ b/packages/studio-server/src/test/coding-agent-registry.test.ts@@ -1,44 +1,197 @@import {expect, test} from 'bun:test';+import type {CodingAgentDiscoveryContext} from '../helpers/coding-agent-registry';import {discoverAvailableCodingAgents} from '../helpers/coding-agent-registry';-test('discovers supported macOS coding agents without launching them', async () => {- const existingPaths = new Set([- '/Custom/Applications/ChatGPT.app',- '/Users/test/Applications/Claude.app',- ]);- const codingAgents = await discoverAvailableCodingAgents({- platform: 'darwin',- homeDirectory: '/Users/test',+const makeContext = ({+ platform,+ paths,+ env = {},+ macApplications = {},+}: {+ platform: NodeJS.Platform;+ paths: readonly string[];+ env?: NodeJS.ProcessEnv;+ macApplications?: Record<string, readonly string[]>;+}): CodingAgentDiscoveryContext => {+ 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(- bundleIdentifier === 'com.openai.codex'- ? ['/Custom/Applications/ChatGPT.app']- : [],- ),- });+ Promise.resolve(macApplications[bundleIdentifier] ?? []),+ };+};++const withoutIconData = (+ codingAgents: Awaited<ReturnType<typeof discoverAvailableCodingAgents>>,+) =>+ codingAgents.map(({iconDataUrl, ...codingAgent}) => ({+ ...codingAgent,+ hasBundledPngIcon:+ iconDataUrl?.startsWith('data:image/png;base64,') ?? false,+ }));++test('discovers supported macOS coding agents without launching them', async () => {+ const codingAgents = await discoverAvailableCodingAgents(+ makeContext({+ platform: 'darwin',+ paths: [+ '/Custom/Applications/ChatGPT.app',+ '/home/test/Applications/Claude.app',+ ],+ macApplications: {+ 'com.openai.codex': ['/Custom/Applications/ChatGPT.app'],+ },+ }),+ );- expect(codingAgents).toEqual([+ expect(withoutIconData(codingAgents)).toEqual([{applicationPath: '/Custom/Applications/ChatGPT.app',+ hasBundledPngIcon: true,id: 'codex',+ launchMode: 'direct',name: 'Codex',+ platform: 'darwin',+ terminal: null,},{- applicationPath: '/Users/test/Applications/Claude.app',+ applicationPath: '/home/test/Applications/Claude.app',+ hasBundledPngIcon: true,id: 'claude-code',+ launchMode: 'direct',name: 'Claude Code',+ platform: 'darwin',+ terminal: null,+ },+ ]);+});++test('discovers Linux coding agents and a terminal from known locations and PATH', async () => {+ const codingAgents = await discoverAvailableCodingAgents(+ makeContext({+ platform: 'linux',+ paths: [+ '/custom/bin/codex',+ '/custom/bin/cursor',+ '/custom/bin/copilot',+ '/home/test/.claude/local/claude',+ '/usr/bin/gnome-terminal',+ ],+ env: {PATH: '/custom/bin:/usr/local/bin'},+ }),+ );++ expect(+ withoutIconData(codingAgents).map(+ ({id, applicationPath, launchMode, platform, terminal}) => ({+ id,+ applicationPath,+ launchMode,+ platform,+ terminal,+ }),+ ),+ ).toEqual([+ {+ applicationPath: '/custom/bin/codex',+ id: 'codex',+ launchMode: 'terminal',+ platform: 'linux',+ terminal: {id: 'gnome-terminal', path: '/usr/bin/gnome-terminal'},+ },+ {+ applicationPath: '/custom/bin/cursor',+ id: 'cursor',+ launchMode: 'direct',+ platform: 'linux',+ terminal: null,+ },+ {+ applicationPath: '/custom/bin/copilot',+ id: 'copilot',+ launchMode: 'terminal',+ platform: 'linux',+ terminal: {id: 'gnome-terminal', path: '/usr/bin/gnome-terminal'},+ },+ {+ applicationPath: '/home/test/.claude/local/claude',+ id: 'claude-code',+ launchMode: 'terminal',+ platform: 'linux',+ terminal: {id: 'gnome-terminal', path: '/usr/bin/gnome-terminal'},+ },+ ]);+});++test('discovers Windows coding agents from install folders and PATH', async () => {+ const cursor =+ 'C:\\Users\\test\\AppData\\Local\\Programs\\cursor\\Cursor.exe';+ const codingAgents = await discoverAvailableCodingAgents(+ makeContext({+ platform: 'win32',+ paths: [+ 'C:\\Tools\\codex.cmd',+ cursor,+ 'C:\\Tools\\copilot.cmd',+ 'C:\\Tools\\claude.cmd',+ ],+ env: {+ ComSpec: 'C:\\Windows\\System32\\cmd.exe',+ LOCALAPPDATA: 'C:\\Users\\test\\AppData\\Local',+ PATH: 'C:\\Tools;C:\\Windows',+ },+ }),+ );++ expect(+ codingAgents.map(+ ({id, applicationPath, launchMode, platform, terminal}) => ({+ id,+ applicationPath,+ launchMode,+ platform,+ terminal,+ }),+ ),+ ).toEqual([+ {+ applicationPath: 'C:\\Tools\\codex.cmd',+ id: 'codex',+ launchMode: 'terminal',+ platform: 'win32',+ terminal: {id: 'cmd', path: 'C:\\Windows\\System32\\cmd.exe'},+ },+ {+ applicationPath: cursor,+ id: 'cursor',+ launchMode: 'direct',+ platform: 'win32',+ terminal: null,+ },+ {+ applicationPath: 'C:\\Tools\\copilot.cmd',+ id: 'copilot',+ launchMode: 'terminal',+ platform: 'win32',+ terminal: {id: 'cmd', path: 'C:\\Windows\\System32\\cmd.exe'},+ },+ {+ applicationPath: 'C:\\Tools\\claude.cmd',+ id: 'claude-code',+ launchMode: 'terminal',+ platform: 'win32',+ terminal: {id: 'cmd', path: 'C:\\Windows\\System32\\cmd.exe'},},]);});test('does not report coding agents on unsupported platforms', async () => {- const codingAgents = await discoverAvailableCodingAgents({- platform: 'linux',- homeDirectory: '/home/test',- pathExists: () => true,- findMacApplications: () => Promise.resolve(['/Applications/ChatGPT.app']),- });+ const codingAgents = await discoverAvailableCodingAgents(+ makeContext({platform: 'freebsd', paths: []}),+ );expect(codingAgents).toEqual([]);});diff --git a/packages/studio-server/src/test/default-coding-agent-route.test.ts b/packages/studio-server/src/test/default-coding-agent-route.test.tsindex 991e943704..1fc395392e 100644--- a/packages/studio-server/src/test/default-coding-agent-route.test.ts+++ b/packages/studio-server/src/test/default-coding-agent-route.test.ts@@ -31,7 +31,7 @@ test('persists the selected coding agent through the route', async () => {entryPoint: '',getDefaultCodingAgent: () => 'cursor',getDefaultEditor: () => null,- input: {defaultCodingAgent: 'codex'},+ input: {defaultCodingAgent: 'copilot'},logLevel: 'error',methods: {addJob: () => undefined,@@ -49,7 +49,7 @@ test('persists the selected coding agent through the route', async () => {["import {Config} from '@remotion/cli/config';",'Config.setOverwriteOutput(true);',- "Config.setDefaultCodingAgent('codex');",+ "Config.setDefaultCodingAgent('copilot');",'',].join('\n'),);diff --git a/packages/studio-server/src/test/open-in-coding-agent.test.ts b/packages/studio-server/src/test/open-in-coding-agent.test.tsnew file mode 100644index 0000000000..df1765a49c--- /dev/null+++ b/packages/studio-server/src/test/open-in-coding-agent.test.ts@@ -0,0 +1,384 @@+import {expect, test} from 'bun:test';+import {+ chmodSync,+ existsSync,+ mkdirSync,+ mkdtempSync,+ readFileSync,+ realpathSync,+ rmSync,+ writeFileSync,+} from 'node:fs';+import {tmpdir} from 'node:os';+import path from 'node:path';+import {+ getCodingAgentLaunchCommand,+ getCodingAgentLaunchCommands,+ launchCodingAgent,+} from '../helpers/coding-agent-registry';++test('constructs macOS coding agent launch commands', () => {+ expect(+ getCodingAgentLaunchCommand({+ codingAgent: {+ applicationPath: '/Applications/ChatGPT.app',+ iconDataUrl: null,+ id: 'codex',+ launchMode: 'direct',+ name: 'Codex',+ platform: 'darwin',+ terminal: null,+ },+ projectPath: '/Users/test/My Project',+ }),+ ).toEqual({+ command: '/Applications/ChatGPT.app/Contents/Resources/codex',+ args: ['app', '/Users/test/My Project'],+ cwd: null,+ });++ expect(+ getCodingAgentLaunchCommand({+ codingAgent: {+ applicationPath: '/Applications/Cursor.app',+ iconDataUrl: null,+ id: 'cursor',+ launchMode: 'direct',+ name: 'Cursor',+ platform: 'darwin',+ terminal: null,+ },+ projectPath: '/Users/test/My Project',+ }),+ ).toEqual({+ command: '/Applications/Cursor.app/Contents/Resources/app/bin/cursor',+ args: ['--glass', '--suppress-popups-on-startup', '/Users/test/My Project'],+ cwd: null,+ });++ for (const codingAgent of [+ {+ applicationPath: '/Applications/GitHub Copilot.app',+ iconDataUrl: null,+ id: 'copilot' as const,+ launchMode: 'direct' as const,+ name: 'GitHub Copilot',+ platform: 'darwin' as const,+ terminal: null,+ },+ {+ applicationPath: '/Applications/Claude.app',+ iconDataUrl: null,+ id: 'claude-code' as const,+ launchMode: 'direct' as const,+ name: 'Claude Code',+ platform: 'darwin' as const,+ terminal: null,+ },+ ]) {+ expect(+ getCodingAgentLaunchCommand({+ codingAgent,+ projectPath: '/Users/test/My Project',+ }),+ ).toEqual({+ command: 'open',+ args: ['-a', codingAgent.applicationPath, '/Users/test/My Project'],+ cwd: null,+ });+ }+});++test('constructs Linux coding agent launch commands', () => {+ expect(+ getCodingAgentLaunchCommand({+ codingAgent: {+ applicationPath: '/usr/local/bin/codex',+ iconDataUrl: null,+ id: 'codex',+ launchMode: 'terminal',+ name: 'Codex',+ platform: 'linux',+ terminal: {+ id: 'gnome-terminal',+ path: '/usr/bin/gnome-terminal',+ },+ },+ projectPath: '/home/test/My Project',+ }),+ ).toEqual({+ command: '/usr/bin/gnome-terminal',+ args: [+ '--working-directory=/home/test/My Project',+ '--',+ '/usr/local/bin/codex',+ ],+ cwd: '/home/test/My Project',+ });++ expect(+ getCodingAgentLaunchCommand({+ codingAgent: {+ applicationPath: '/usr/bin/cursor',+ iconDataUrl: null,+ id: 'cursor',+ launchMode: 'direct',+ name: 'Cursor',+ platform: 'linux',+ terminal: null,+ },+ projectPath: '/home/test/My Project',+ }),+ ).toEqual({+ command: '/usr/bin/cursor',+ args: ['--glass', '--suppress-popups-on-startup', '/home/test/My Project'],+ cwd: null,+ });+});++test('constructs Windows coding agent launch commands', () => {+ expect(+ getCodingAgentLaunchCommand({+ codingAgent: {+ applicationPath: 'C:\\Tools\\copilot.cmd',+ iconDataUrl: null,+ id: 'copilot',+ launchMode: 'terminal',+ name: 'GitHub Copilot',+ platform: 'win32',+ terminal: {+ id: 'cmd',+ path: 'C:\\Windows\\System32\\cmd.exe',+ },+ },+ projectPath: 'C:\\Users\\test\\My Project',+ }),+ ).toEqual({+ command: 'C:\\Windows\\System32\\cmd.exe',+ args: [+ '/d',+ '/s',+ '/c',+ 'start',+ '',+ '/d',+ 'C:\\Users\\test\\My Project',+ 'C:\\Windows\\System32\\cmd.exe',+ '/k',+ 'C:\\Tools\\copilot.cmd',+ ],+ cwd: null,+ });+});++test('prefills editable macOS coding agents without submitting to Copilot', () => {+ const projectPath = '/Users/test/My Project';+ const prompt = 'MySequence in src/Comp.tsx:42';++ expect(+ getCodingAgentLaunchCommands({+ codingAgent: {+ applicationPath: '/Applications/ChatGPT.app',+ iconDataUrl: null,+ id: 'codex',+ launchMode: 'direct',+ name: 'Codex',+ platform: 'darwin',+ terminal: null,+ },+ projectPath,+ prompt,+ }),+ ).toEqual([+ {+ command: 'open',+ args: [+ 'codex://new?path=%2FUsers%2Ftest%2FMy+Project&prompt=MySequence+in+src%2FComp.tsx%3A42',+ ],+ cwd: null,+ waitForExit: false,+ },+ ]);++ expect(+ getCodingAgentLaunchCommands({+ codingAgent: {+ applicationPath: '/Applications/Cursor.app',+ iconDataUrl: null,+ id: 'cursor',+ launchMode: 'direct',+ name: 'Cursor',+ platform: 'darwin',+ terminal: null,+ },+ projectPath,+ prompt,+ }),+ ).toEqual([+ {+ command: '/Applications/Cursor.app/Contents/Resources/app/bin/cursor',+ args: ['--glass', '--suppress-popups-on-startup', projectPath],+ cwd: null,+ waitForExit: true,+ },+ {+ command: 'open',+ args: [+ 'cursor://anysphere.cursor-deeplink/prompt?text=MySequence+in+src%2FComp.tsx%3A42',+ ],+ cwd: null,+ waitForExit: false,+ },+ ]);++ expect(+ getCodingAgentLaunchCommands({+ codingAgent: {+ applicationPath: '/Applications/Claude.app',+ iconDataUrl: null,+ id: 'claude-code',+ launchMode: 'direct',+ name: 'Claude Code',+ platform: 'darwin',+ terminal: null,+ },+ projectPath,+ prompt,+ }),+ ).toEqual([+ {+ command: 'open',+ args: [+ 'claude://code/new?folder=%2FUsers%2Ftest%2FMy+Project&q=MySequence+in+src%2FComp.tsx%3A42',+ ],+ cwd: null,+ waitForExit: false,+ },+ ]);++ expect(+ getCodingAgentLaunchCommands({+ codingAgent: {+ applicationPath: '/Applications/GitHub Copilot.app',+ iconDataUrl: null,+ id: 'copilot',+ launchMode: 'direct',+ name: 'GitHub Copilot',+ platform: 'darwin',+ terminal: null,+ },+ projectPath,+ prompt,+ }),+ ).toEqual([+ {+ command: 'open',+ args: ['-a', '/Applications/GitHub Copilot.app', projectPath],+ cwd: null,+ waitForExit: false,+ },+ ]);+});++test.skipIf(process.platform === 'win32')(+ 'launches the project through the coding agent executable',+ async () => {+ const directory = mkdtempSync(+ path.join(tmpdir(), 'remotion-coding-agent-launch-'),+ );+ const applicationPath = path.join(directory, 'ChatGPT.app');+ const executable = path.join(+ applicationPath,+ 'Contents',+ 'Resources',+ 'codex',+ );+ const output = path.join(path.dirname(executable), 'received.txt');+ mkdirSync(path.dirname(executable), {recursive: true});+ writeFileSync(+ executable,+ '#!/bin/sh\nprintf "%s\\n" "$@" > "$(dirname "$0")/received.txt"\n',+ );+ chmodSync(executable, 0o755);++ try {+ const success = await launchCodingAgent({+ codingAgent: {+ applicationPath,+ iconDataUrl: null,+ id: 'codex',+ launchMode: 'direct',+ name: 'Codex',+ platform: 'darwin',+ terminal: null,+ },+ logLevel: 'error',+ projectPath: '/Users/test/My Project',+ prompt: null,+ });+ expect(success).toBe(true);++ for (let attempt = 0; attempt < 100 && !existsSync(output); attempt++) {+ await Bun.sleep(10);+ }++ expect(readFileSync(output, 'utf8')).toBe(+ 'app\n/Users/test/My Project\n',+ );+ } finally {+ rmSync(directory, {force: true, recursive: true});+ }+ },+);++test.skipIf(process.platform === 'win32')(+ 'launches a terminal coding agent in the project directory',+ async () => {+ const directory = mkdtempSync(+ path.join(tmpdir(), 'remotion-terminal-coding-agent-launch-'),+ );+ const projectPath = path.join(directory, 'My Project');+ const applicationPath = path.join(directory, 'codex');+ const terminalPath = path.join(directory, 'gnome-terminal');+ const output = path.join(directory, 'received.txt');+ mkdirSync(projectPath);+ writeFileSync(+ applicationPath,+ `#!/bin/sh\nprintf "%s\\n" "$PWD" > "${output}"\n`,+ );+ writeFileSync(+ terminalPath,+ '#!/bin/sh\nwhile [ "$#" -gt 0 ]; do\n if [ "$1" = "--" ]; then\n shift\n exec "$@"\n fi\n shift\ndone\n',+ );+ chmodSync(applicationPath, 0o755);+ chmodSync(terminalPath, 0o755);++ try {+ const success = await launchCodingAgent({+ codingAgent: {+ applicationPath,+ iconDataUrl: null,+ id: 'codex',+ launchMode: 'terminal',+ name: 'Codex',+ platform: 'linux',+ terminal: {id: 'gnome-terminal', path: terminalPath},+ },+ logLevel: 'error',+ projectPath,+ prompt: null,+ });+ expect(success).toBe(true);++ for (let attempt = 0; attempt < 100 && !existsSync(output); attempt++) {+ await Bun.sleep(10);+ }++ expect(readFileSync(output, 'utf8')).toBe(+ `${realpathSync(projectPath)}\n`,+ );+ } finally {+ rmSync(directory, {force: true, recursive: true});+ }+ },+);diff --git a/packages/studio-server/web/coding-agent-icons/claude-code.png b/packages/studio-server/web/coding-agent-icons/claude-code.pngnew file mode 100644index 0000000000..b870a7edf3Binary files /dev/null and b/packages/studio-server/web/coding-agent-icons/claude-code.png differdiff --git a/packages/studio-server/web/coding-agent-icons/codex.png b/packages/studio-server/web/coding-agent-icons/codex.pngnew file mode 100644index 0000000000..2f6a3f9758Binary files /dev/null and b/packages/studio-server/web/coding-agent-icons/codex.png differdiff --git a/packages/studio-server/web/coding-agent-icons/copilot.png b/packages/studio-server/web/coding-agent-icons/copilot.pngnew file mode 100644index 0000000000..f85f052fd3Binary files /dev/null and b/packages/studio-server/web/coding-agent-icons/copilot.png differdiff --git a/packages/studio-server/web/coding-agent-icons/cursor.png b/packages/studio-server/web/coding-agent-icons/cursor.pngnew file mode 100644index 0000000000..1de099b37cBinary files /dev/null and b/packages/studio-server/web/coding-agent-icons/cursor.png differdiff --git a/packages/studio-shared/src/api-requests.ts b/packages/studio-shared/src/api-requests.tsindex 0cd8782e45..fa2cd499d1 100644--- a/packages/studio-shared/src/api-requests.ts+++ b/packages/studio-shared/src/api-requests.ts@@ -61,6 +61,15 @@ export type OpenInEditorResponse = {success: boolean;};+export type OpenInCodingAgentRequest = {+ codingAgentId: DefaultCodingAgent;+ prompt: string | null;+};++export type OpenInCodingAgentResponse = {+ success: boolean;+};+export type FindInFileRequest = {fileName: string;lineNumber: number;@@ -1012,7 +1021,11 @@ export type UpdateDefaultEditorResponse =export type GetDefaultCodingAgentInfoRequest = {};export type GetDefaultCodingAgentInfoResponse = {defaultCodingAgent: DefaultCodingAgent | null;- installedCodingAgents: {id: DefaultCodingAgent; name: string}[];+ installedCodingAgents: {+ id: DefaultCodingAgent;+ name: string;+ iconDataUrl: string | null;+ }[];};export type UpdateDefaultCodingAgentRequest = {@@ -1084,6 +1097,10 @@ export type ApiRoutes = {>;'/api/remove-render': ReqAndRes<RemoveRenderRequest, undefined>;'/api/open-in-editor': ReqAndRes<OpenInEditorRequest, OpenInEditorResponse>;+ '/api/open-in-coding-agent': ReqAndRes<+ OpenInCodingAgentRequest,+ OpenInCodingAgentResponse+ >;'/api/default-coding-agent-info': ReqAndRes<GetDefaultCodingAgentInfoRequest,GetDefaultCodingAgentInfoResponsediff --git a/packages/studio-shared/src/index.ts b/packages/studio-shared/src/index.tsindex ed59f0d4db..f6ac57ecdf 100644--- a/packages/studio-shared/src/index.ts+++ b/packages/studio-shared/src/index.ts@@ -73,6 +73,8 @@ export {MoveKeyframesRequest,MoveKeyframesResponse,MoveSequenceKeyframe,+ OpenInCodingAgentRequest,+ OpenInCodingAgentResponse,OpenInEditorRequest,OpenInEditorResponse,OpenInFileExplorerRequest,diff --git a/packages/studio/src/components/CodingAgentIcon.tsx b/packages/studio/src/components/CodingAgentIcon.tsxnew file mode 100644index 0000000000..841d28dae6--- /dev/null+++ b/packages/studio/src/components/CodingAgentIcon.tsx@@ -0,0 +1,26 @@+import React from 'react';+import {AppsIcon} from '../icons/apps';++const iconStyle: React.CSSProperties = {+ flexShrink: 0,+ height: 18,+ width: 18,+};++export const CodingAgentIcon: React.FC<{+ readonly iconDataUrl: string | null;+}> = ({iconDataUrl}) => {+ if (iconDataUrl === null) {+ return <AppsIcon height={18} width={18} />;+ }++ return (+ <img+ alt=""+ aria-hidden+ draggable={false}+ src={iconDataUrl}+ style={iconStyle}+ />+ );+};diff --git a/packages/studio/src/components/ConfigureDefaultEditorModal.tsx b/packages/studio/src/components/ConfigureDefaultEditorModal.tsxindex 511058c696..4aa648e627 100644--- a/packages/studio/src/components/ConfigureDefaultEditorModal.tsx+++ b/packages/studio/src/components/ConfigureDefaultEditorModal.tsx@@ -4,10 +4,11 @@ import type {GetDefaultEditorInfoResponse,} from '@remotion/studio-shared';import React, {useCallback, useEffect, useMemo, useState} from 'react';-import {LIGHT_TEXT, WHITE} from '../helpers/colors';+import {LIGHT_TEXT} from '../helpers/colors';import {Checkmark} from '../icons/Checkmark';-import {CustomEditorIcon} from '../icons/custom-editor';+import {EditorIcon} from '../icons/editor';import {callApi} from './call-api';+import {CodingAgentIcon} from './CodingAgentIcon';import {Spacing} from './layout';import {ModalButton} from './ModalButton';import type {ComboboxValue} from './NewComposition/ComboBox';@@ -36,7 +37,7 @@ const description: React.CSSProperties = {};const title: React.CSSProperties = {- color: WHITE,+ color: LIGHT_TEXT,fontFamily: 'sans-serif',fontSize: 14,lineHeight: 1.5,@@ -48,8 +49,8 @@ const comboBoxStyle: React.CSSProperties = {width: '100%',};-const customEditorLabel: React.CSSProperties = {- display: 'inline-flex',+const appLabel: React.CSSProperties = {+ display: 'flex',alignItems: 'center',gap: 8,maxWidth: '100%',@@ -60,7 +61,7 @@ const customEditorLabel: React.CSSProperties = {lineHeight: 'inherit',};-const customEditorName: React.CSSProperties = {+const appName: React.CSSProperties = {minWidth: 0,overflow: 'hidden',textOverflow: 'ellipsis',@@ -107,15 +108,12 @@ export const DefaultEditorSettings: React.FC<{return {id: editor.id,keyHint: null,- label:- editor.id === 'custom' ? (- <span style={customEditorLabel}>- <CustomEditorIcon size={null} />- <span style={customEditorName}>{editor.name}</span>- </span>- ) : (- editor.name- ),+ label: (+ <span style={appLabel}>+ <EditorIcon editorId={editor.id} size={18} />+ <span style={appName}>{editor.name}</span>+ </span>+ ),leftItem: selectedEditor === editor.id ? <Checkmark /> : null,onClick: () => {setSelectedEditor(editor.id);@@ -152,7 +150,12 @@ export const DefaultEditorSettings: React.FC<{return {id: codingAgent.id,keyHint: null,- label: codingAgent.name,+ label: (+ <span style={appLabel}>+ <CodingAgentIcon iconDataUrl={codingAgent.iconDataUrl} />+ <span style={appName}>{codingAgent.name}</span>+ </span>+ ),leftItem: selectedCodingAgent === codingAgent.id ? <Checkmark /> : null,onClick: () => {setSelectedCodingAgent(codingAgent.id);@@ -249,7 +252,6 @@ export const DefaultEditorSettings: React.FC<{<div style={container}><div style={content}><p style={title}>Default editor</p>- <p style={description}>Used when Remotion Studio opens source files.</p><Spacing y={1} block />{editorInfo === null && error === null ? (<p style={description}>Loading installed editors...</p>@@ -269,9 +271,6 @@ export const DefaultEditorSettings: React.FC<{)}<Spacing y={2} block /><p style={title}>Default coding agent</p>- <p style={description}>- Used when Remotion Studio hands a project to a coding agent.- </p><Spacing y={1} block />{codingAgentInfo === null && error === null ? (<p style={description}>Loading installed coding agents...</p>diff --git a/packages/studio/src/components/InspectorLocationCopy.tsx b/packages/studio/src/components/InspectorLocationCopy.tsxindex 7619f2873c..2759e7681d 100644--- a/packages/studio/src/components/InspectorLocationCopy.tsx+++ b/packages/studio/src/components/InspectorLocationCopy.tsx@@ -79,6 +79,8 @@ export const InspectorLocationCopy: React.FC<{return (<div+ aria-label="Inspector source location"+ role="group"style={row}onPointerEnter={() => setHovered(true)}onPointerLeave={() => setHovered(false)}@@ -94,7 +96,10 @@ export const InspectorLocationCopy: React.FC<{pointerEvents: showAction ? 'auto' : 'none',}}>- <InspectorOpenInEditor location={openInEditorLocation} />+ <InspectorOpenInEditor+ location={openInEditorLocation}+ prompt={textToCopy}+ />{textToCopy ? (<InlineActionvariant={null}diff --git a/packages/studio/src/components/InspectorOpenInEditor.tsx b/packages/studio/src/components/InspectorOpenInEditor.tsxindex 539453fb0f..040a60580c 100644--- a/packages/studio/src/components/InspectorOpenInEditor.tsx+++ b/packages/studio/src/components/InspectorOpenInEditor.tsx@@ -1,3 +1,4 @@+import type {DefaultCodingAgent} from '@remotion/renderer';import type {EditorPickerId} from '@remotion/studio-shared';import React, {useCallback, useContext, useMemo, useState} from 'react';import type {OriginalPosition} from '../error-overlay/react-overlay/utils/get-source-map';@@ -8,11 +9,15 @@ import {WHITE,getBackgroundFromHoverState,} from '../helpers/colors';-import {openOriginalPositionInEditor} from '../helpers/open-in-editor';+import {+ openInCodingAgent,+ openOriginalPositionInEditor,+} from '../helpers/open-in-editor';import {CaretDown} from '../icons/caret';import {EditorIcon} from '../icons/editor';import {SetSelectedModalContext} from '../state/modals';import {useZIndex} from '../state/z-index';+import {CodingAgentIcon} from './CodingAgentIcon';import type {RenderInlineAction} from './InlineAction';import {InlineDropdown} from './InlineDropdown';import type {ComboboxValue} from './NewComposition/ComboBox';@@ -20,6 +25,7 @@ import {showNotification} from './Notifications/NotificationCenter';import {canUseEditorPicker,getPreferredEditorId,+ useDefaultCodingAgentInfo,useDefaultEditorInfo,} from './use-default-editor-info';@@ -63,7 +69,8 @@ const editorMenuIconSize = 18;export const InspectorOpenInEditor: React.FC<{readonly location: OriginalPosition | null;readonly label?: React.ReactNode;-}> = ({label, location}) => {+ readonly prompt?: string | null;+}> = ({label, location, prompt = null}) => {const {previewServerState} = useContext(StudioServerConnectionCtx);const {setSelectedModal} = useContext(SetSelectedModalContext);const {tabIndex} = useZIndex();@@ -73,6 +80,7 @@ export const InspectorOpenInEditor: React.FC<{previewServerState.type === 'connected',);const editorInfo = useDefaultEditorInfo(editorPickerAvailable);+ const codingAgentInfo = useDefaultCodingAgentInfo(editorPickerAvailable);const openWithEditor = useCallback(async (editorId: EditorPickerId | null) => {@@ -90,6 +98,22 @@ export const InspectorOpenInEditor: React.FC<{);const preferredEditorId = getPreferredEditorId(editorInfo);+ const openWithCodingAgent = useCallback(+ async (codingAgentId: DefaultCodingAgent, codingAgentName: string) => {+ try {+ const response = await openInCodingAgent(+ codingAgentId,+ codingAgentId === 'copilot' ? null : prompt,+ );+ if (!response.success) {+ showNotification(`Could not open ${codingAgentName}`, 2000);+ }+ } catch (err) {+ showNotification((err as Error).message, 2000);+ }+ },+ [prompt],+ );const editorName = window.remotion_editorName ?? 'default editor';const canOpenDefault =location !== null && window.remotion_editorName !== null;@@ -146,14 +170,44 @@ export const InspectorOpenInEditor: React.FC<{type: 'item' as const,value: editor.id,}));+ const codingAgents: ComboboxValue[] = (+ codingAgentInfo?.installedCodingAgents ?? []+ ).map((codingAgent) => ({+ id: `open-in-coding-agent-${codingAgent.id}`,+ keyHint: null,+ label: <span style={menuLabel}>{codingAgent.name}</span>,+ leftItem: <CodingAgentIcon iconDataUrl={codingAgent.iconDataUrl} />,+ onClick: () => {+ openWithCodingAgent(codingAgent.id, codingAgent.name).catch(+ () => undefined,+ );+ },+ quickSwitcherLabel: null,+ subMenu: null,+ type: 'item' as const,+ value: `coding-agent-${codingAgent.id}`,+ }));+ const editorSection: ComboboxValue[] = alternateEditors.length+ ? [+ {type: 'section-header', id: 'editors-header', label: 'Editors'},+ ...alternateEditors,+ ]+ : [];+ const codingAgentSection: ComboboxValue[] = codingAgents.length+ ? [+ {type: 'section-header', id: 'agents-header', label: 'Agents'},+ ...codingAgents,+ ]+ : [];+ const apps: ComboboxValue[] = [...editorSection, ...codingAgentSection];const settingsItems: ComboboxValue[] = [- ...(alternateEditors.length > 0+ ...(apps.length > 0? [{type: 'divider' as const, id: 'editor-settings-divider'}]: []),{- id: 'set-default-editor',+ id: 'change-default-apps',keyHint: null,- label: <span style={menuLabel}>Set default editor...</span>,+ label: <span style={menuLabel}>Change default apps...</span>,leftItem: null,onClick: () => {setSelectedModal({@@ -166,13 +220,15 @@ export const InspectorOpenInEditor: React.FC<{quickSwitcherLabel: null,subMenu: null,type: 'item' as const,- value: 'set-default-editor',+ value: 'change-default-apps',},];- return [...alternateEditors, ...settingsItems];+ return [...apps, ...settingsItems];}, [+ codingAgentInfo?.installedCodingAgents,editorInfo?.installedEditors,+ openWithCodingAgent,openWithEditor,preferredEditorId,setSelectedModal,@@ -204,7 +260,7 @@ export const InspectorOpenInEditor: React.FC<{onOpenChange={setDropdownOpened}renderAction={renderDropdownAction}style={dropdownStyle}- title="Open in another editor"+ title="Open in another app"unhoveredColor={dropdownForegroundColor}values={menuItems}variant="compact"diff --git a/packages/studio/src/components/Menu/MenuSectionHeader.tsx b/packages/studio/src/components/Menu/MenuSectionHeader.tsxnew file mode 100644index 0000000000..1a522447fe--- /dev/null+++ b/packages/studio/src/components/Menu/MenuSectionHeader.tsx@@ -0,0 +1,20 @@+import React from 'react';+import {WHITE_ALPHA_50} from '../../helpers/colors';++const sectionHeader: React.CSSProperties = {+ color: WHITE_ALPHA_50,+ fontSize: 10,+ lineHeight: '12px',+ paddingBottom: 2,+ paddingLeft: 8,+ paddingRight: 8,+ paddingTop: 6,+ userSelect: 'none',+ WebkitUserSelect: 'none',+};++export const MenuSectionHeader: React.FC<{+ readonly children: string;+}> = ({children}) => {+ return <div style={sectionHeader}>{children}</div>;+};diff --git a/packages/studio/src/components/NewComposition/ComboBox.tsx b/packages/studio/src/components/NewComposition/ComboBox.tsxindex e0a0639808..92d8f098ab 100644--- a/packages/studio/src/components/NewComposition/ComboBox.tsx+++ b/packages/studio/src/components/NewComposition/ComboBox.tsx@@ -82,6 +82,12 @@ type DividerItem = {id: string;};+type SectionHeaderItem = {+ type: 'section-header';+ id: string;+ label: string;+};+export type SubMenu = {preselectIndex: number | false;leaveLeftSpace: boolean;@@ -101,7 +107,7 @@ export type SelectionItem = {disabled?: boolean;};-export type ComboboxValue = DividerItem | SelectionItem;+export type ComboboxValue = DividerItem | SectionHeaderItem | SelectionItem;export const Combobox: React.FC<{readonly values: ComboboxValue[];diff --git a/packages/studio/src/components/NewComposition/MenuContent.tsx b/packages/studio/src/components/NewComposition/MenuContent.tsxindex cddc8b11e4..43c0a93cda 100644--- a/packages/studio/src/components/NewComposition/MenuContent.tsx+++ b/packages/studio/src/components/NewComposition/MenuContent.tsx@@ -7,6 +7,7 @@ import {useKeybinding} from '../../helpers/use-keybinding';import {VERTICAL_SCROLLBAR_CLASSNAME} from '../Menu/is-menu-item';import {MenuDivider} from '../Menu/MenuDivider';import type {MenuId} from '../Menu/MenuItem';+import {MenuSectionHeader} from '../Menu/MenuSectionHeader';import type {SubMenuActivated} from '../Menu/MenuSubItem';import {MenuSubItem} from '../Menu/MenuSubItem';import {@@ -86,7 +87,7 @@ export const MenuContent: React.FC<{}, []);const isItemSelectable = useCallback((v: ComboboxValue) => {- return v.type !== 'divider' && !v.disabled;+ return v.type === 'item' && !v.disabled;}, []);const onArrowUp = useCallback(() => {@@ -147,8 +148,8 @@ export const MenuContent: React.FC<{throw new Error('cannot find item');}- if (item.type === 'divider') {- throw new Error('cannot find divider');+ if (item.type !== 'item') {+ throw new Error('cannot select non-interactive menu item');}if (item.disabled) {@@ -173,8 +174,8 @@ export const MenuContent: React.FC<{throw new Error('cannot find item');}- if (item.type === 'divider') {- throw new Error('cannot find divider');+ if (item.type !== 'item') {+ throw new Error('cannot select non-interactive menu item');}if (!item.subMenu) {@@ -363,8 +364,8 @@ export const MenuContent: React.FC<{return;}- if (item.type === 'divider') {- throw new Error('should not select divider');+ if (item.type !== 'item') {+ throw new Error('should not select non-interactive menu item');}if (!item.subMenu && subMenuActivated) {@@ -401,6 +402,12 @@ export const MenuContent: React.FC<{return <MenuDivider key={item.id} />;}+ if (item.type === 'section-header') {+ return (+ <MenuSectionHeader key={item.id}>{item.label}</MenuSectionHeader>+ );+ }+const onClick = (id: string, e: PointerEvent<HTMLDivElement>) => {item.onClick(id, e);if (item.subMenu) {diff --git a/packages/studio/src/components/NewComposition/menu-typeahead.ts b/packages/studio/src/components/NewComposition/menu-typeahead.tsindex 834816de55..1a366c3573 100644--- a/packages/studio/src/components/NewComposition/menu-typeahead.ts+++ b/packages/studio/src/components/NewComposition/menu-typeahead.ts@@ -1,7 +1,7 @@import type {ComboboxValue} from './ComboBox';const getLabelToMatch = (value: ComboboxValue): string | null => {- if (value.type === 'divider' || value.disabled) {+ if (value.type !== 'item' || value.disabled) {return null;}@@ -30,7 +30,7 @@ export const findTypeaheadMenuItem = ({return label ? label.toLowerCase().startsWith(normalizedQuery) : false;});- if (!matched || matched.type === 'divider') {+ if (!matched || matched.type !== 'item') {return null;}diff --git a/packages/studio/src/components/use-default-editor-info.ts b/packages/studio/src/components/use-default-editor-info.tsindex c0df36a9b0..ff77016cf8 100644--- a/packages/studio/src/components/use-default-editor-info.ts+++ b/packages/studio/src/components/use-default-editor-info.ts@@ -1,5 +1,6 @@import type {EditorPickerId,+ GetDefaultCodingAgentInfoResponse,GetDefaultEditorInfoResponse,} from '@remotion/studio-shared';import {useEffect, useState} from 'react';@@ -7,6 +8,8 @@ import {getBrowserStudioOperations} from '../helpers/browser-studio-operations';import {callApi} from './call-api';let editorInfoPromise: Promise<GetDefaultEditorInfoResponse> | null = null;+let codingAgentInfoPromise: Promise<GetDefaultCodingAgentInfoResponse> | null =+ null;const loadDefaultEditorInfo = () => {editorInfoPromise ??= callApi('/api/default-editor-info', {}).catch((err) => {@@ -17,6 +20,18 @@ const loadDefaultEditorInfo = () => {return editorInfoPromise;};+const loadDefaultCodingAgentInfo = () => {+ codingAgentInfoPromise ??= callApi(+ '/api/default-coding-agent-info',+ {},+ ).catch((err) => {+ codingAgentInfoPromise = null;+ throw err;+ });++ return codingAgentInfoPromise;+};+export const canUseEditorPicker = (previewServerConnected: boolean) => {return (previewServerConnected &&@@ -60,3 +75,29 @@ export const useDefaultEditorInfo = (enabled: boolean) => {return editorInfo;};++export const useDefaultCodingAgentInfo = (enabled: boolean) => {+ const [codingAgentInfo, setCodingAgentInfo] =+ useState<GetDefaultCodingAgentInfoResponse | null>(null);++ useEffect(() => {+ if (!enabled) {+ return;+ }++ let cancelled = false;+ loadDefaultCodingAgentInfo()+ .then((response) => {+ if (!cancelled) {+ setCodingAgentInfo(response);+ }+ })+ .catch(() => undefined);++ return () => {+ cancelled = true;+ };+ }, [enabled]);++ return codingAgentInfo;+};diff --git a/packages/studio/src/helpers/open-in-editor.ts b/packages/studio/src/helpers/open-in-editor.tsindex 6caa5e8d29..db63e30a58 100644--- a/packages/studio/src/helpers/open-in-editor.ts+++ b/packages/studio/src/helpers/open-in-editor.ts@@ -1,3 +1,4 @@+import type {DefaultCodingAgent} from '@remotion/renderer';import type {CompositionComponentInfoResponse,EditorPickerId,@@ -35,6 +36,13 @@ export const openInEditor = (});};+export const openInCodingAgent = (+ codingAgentId: DefaultCodingAgent,+ prompt: string | null,+) => {+ return callApi('/api/open-in-coding-agent', {codingAgentId, prompt});+};+export const openOriginalPositionInEditor = async (originalPosition: OriginalPosition,editorId: EditorPickerId | null,diff --git a/packages/studio/src/helpers/use-menu-structure.tsx b/packages/studio/src/helpers/use-menu-structure.tsxindex 4c5fa1120d..cd49e64291 100644--- a/packages/studio/src/helpers/use-menu-structure.tsx+++ b/packages/studio/src/helpers/use-menu-structure.tsx@@ -1178,7 +1178,7 @@ const itemToSearchResult = (if (item.subMenu) {return item.subMenu.items.map((subItem) => {- if (subItem.type === 'divider') {+ if (subItem.type !== 'item') {return null;}@@ -1211,7 +1211,7 @@ export const makeSearchResults = (const items: TQuickSwitcherResult[] = actions.map((menu) => {return menu.items.map((item): TQuickSwitcherResult[] | null => {- if (item.type === 'divider') {+ if (item.type !== 'item') {return null;}diff --git a/packages/studio/src/test/menu-typeahead.test.ts b/packages/studio/src/test/menu-typeahead.test.tsindex 0b2af953b8..a76bc0cc9b 100644--- a/packages/studio/src/test/menu-typeahead.test.ts+++ b/packages/studio/src/test/menu-typeahead.test.ts@@ -4,6 +4,7 @@ import {findTypeaheadMenuItem} from '../components/NewComposition/menu-typeaheadconst values: ComboboxValue[] = [{type: 'divider', id: 'divider-1'},+ {type: 'section-header', id: 'fruit-header', label: 'Fruit'},{type: 'item',id: 'apple',@@ -56,7 +57,8 @@ test('matches string label prefix (case-insensitive)', () => {expect(findTypeaheadMenuItem({query: 'AP', values})).toBe('apple');});-test('skips dividers and disabled items', () => {+test('skips dividers, section headers, and disabled items', () => {+ expect(findTypeaheadMenuItem({query: 'fruit', values})).toBe(null);expect(findTypeaheadMenuItem({query: 'ban', values})).toBe(null);});