🎥 Make videos programmatically with React
Share process scans between editors and coding agents
Jonny Burger6fdc3bb6d2ee
diff --git a/packages/studio-server/src/helpers/coding-agent-registry.ts b/packages/studio-server/src/helpers/coding-agent-registry.tsindex 700a80c021..c6b2b65dab 100644--- a/packages/studio-server/src/helpers/coding-agent-registry.ts+++ b/packages/studio-server/src/helpers/coding-agent-registry.ts@@ -5,6 +5,7 @@ import path from 'node:path';import {promisify} from 'node:util';import type {DefaultCodingAgent, LogLevel} from '@remotion/renderer';import {defaultCodingAgentIds, RenderInternals} from '@remotion/renderer';+import {getRunningProcesses} from './running-processes';const execFilePromise = promisify(execFile);@@ -441,60 +442,43 @@ export const getRunningCodingAgents = async (return [];}- try {- const {stdout} =- process.platform === 'win32'- ? await execFilePromise(- 'powershell.exe',- [- '-NoProfile',- '-NonInteractive',- '-Command',- 'Get-CimInstance Win32_Process | ForEach-Object { $_.CommandLine }',- ],- {timeout: 5000},- )- : await execFilePromise(- 'ps',- ['-ax', '-o', process.platform === 'darwin' ? 'comm=' : 'args='],- {timeout: 5000},- );- const processes = stdout.split(/\r?\n/).map((line) => line.trim());- return installedCodingAgents- .filter((agent) => {- if (agent.platform === 'darwin') {- return processes.some((processPath) =>- processPath.startsWith(`${agent.applicationPath}/Contents/MacOS/`),- );- }+ const processes = await getRunningProcesses();+ if (processes === null) {+ return [];+ }- const commands = codingAgentDefinitions[agent.id][agent.platform]- .flatMap((variant) => variant.commands)- .map((command) => command.replace(/\.(exe|cmd)$/i, ''));- const escapedCommands = commands.map((command) =>- command.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'),- );- const escapedPath = agent.applicationPath.replace(- /[.*+?^${}()|[\]\\]/g,- '\\$&',+ return installedCodingAgents+ .filter((agent) => {+ if (agent.platform === 'darwin') {+ return processes.some(({executable: processPath}) =>+ processPath?.startsWith(`${agent.applicationPath}/Contents/MacOS/`),);- const executable = new RegExp(- `^"?(?:${escapedPath}|(?:[^"\\s]*[/\\\\])?(?:${escapedCommands.join('|')})(?:\\.(?:exe|cmd|js))?)"?(?=\\s|$)`,- agent.platform === 'win32' ? 'i' : '',+ }++ const commands = codingAgentDefinitions[agent.id][agent.platform]+ .flatMap((variant) => variant.commands)+ .map((command) => command.replace(/\.(exe|cmd)$/i, ''));+ const escapedCommands = commands.map((command) =>+ command.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'),+ );+ const escapedPath = agent.applicationPath.replace(+ /[.*+?^${}()|[\]\\]/g,+ '\\$&',+ );+ const executable = new RegExp(+ `^"?(?:${escapedPath}|(?:[^"\\s]*[/\\\\])?(?:${escapedCommands.join('|')})(?:\\.(?:exe|cmd|js))?)"?(?=\\s|$)`,+ agent.platform === 'win32' ? 'i' : '',+ );+ return processes.some(({commandLine}) => {+ // Node-based CLIs put the script after the interpreter path.+ const withoutNode = (commandLine ?? '').replace(+ /^(?:"[^"\r\n]*[/\\]node(?:\.exe)?"|(?:[^\s"]*[/\\])?node(?:\.exe)?)\s+/i,+ '',);- return processes.some((commandLine) => {- // Node-based CLIs put the script after the interpreter path.- const withoutNode = commandLine.replace(- /^(?:"[^"\r\n]*[/\\]node(?:\.exe)?"|(?:[^\s"]*[/\\])?node(?:\.exe)?)\s+/i,- '',- );- return executable.test(withoutNode);- });- })- .map((agent) => agent.id);- } catch {- return [];- }+ return executable.test(withoutNode);+ });+ })+ .map((agent) => agent.id);};export const getCodingAgentLaunchCommand = ({diff --git a/packages/studio-server/src/helpers/open-in-editor.ts b/packages/studio-server/src/helpers/open-in-editor.tsindex c0f037c3dd..ceb53c117c 100644--- a/packages/studio-server/src/helpers/open-in-editor.ts+++ b/packages/studio-server/src/helpers/open-in-editor.ts@@ -5,11 +5,10 @@*/import type {ChildProcess} from 'node:child_process';-import child_process, {exec} from 'node:child_process';+import child_process from 'node:child_process';import fs from 'node:fs';import os from 'node:os';import path from 'node:path';-import util from 'node:util';/*** Copyright (c) 2015-present, Facebook, Inc.*@@ -19,11 +18,10 @@ import util from 'node:util';import type {LogLevel} from '@remotion/renderer';import {RenderInternals} from '@remotion/renderer';import {openInEditorViaUrlScheme} from './open-in-editor-url-scheme';+import {getRunningProcesses} from './running-processes';const {Log} = RenderInternals;-const execProm = util.promisify(exec);-const isVsCodeDerivative = (editor: Editor) => {const editorBasename = path.basename(editor).replace(/\.(exe|cmd|bat)$/i, '');return [@@ -367,27 +365,22 @@ export const findMacOsEditorsFromProcessOutput = (};export async function guessEditor(): Promise<ProcessAndCommand[]> {- // We can find out which editor is currently running by:- // `ps x` on macOS and Linux- // `Get-Process` on Windowsconst availableEditors: ProcessAndCommand[] = [];- try {+ const processes = await getRunningProcesses();+ if (processes !== null) {if (process.platform === 'darwin') {- const output = (await execProm('ps x')).stdout.toString();+ const output = processes+ .map(({executable}) => executable ?? '')+ .join('\n');return findMacOsEditorsFromProcessOutput(output);}if (process.platform === 'win32') {- // Some processes need elevated rights to get its executable path.- // Just filter them out upfront. This also saves 10-20ms on the command.- const output = (- await execProm(- 'wmic process where "executablepath is not null" get executablepath',- )- ).stdout.toString();- const runningProcesses = output.split('\r\n');- for (let i = 0; i < runningProcesses.length; i++) {- const processPath = runningProcesses[i].trim();+ for (const {executable: processPath} of processes) {+ if (processPath === null) {+ continue;+ }+const processName = path.basename(processPath);if (COMMON_EDITORS_WIN.indexOf(processName as Editor) !== -1) {availableEditors.push({@@ -401,12 +394,9 @@ export async function guessEditor(): Promise<ProcessAndCommand[]> {}if (process.platform === 'linux') {- // --no-heading No header line- // x List all processes owned by you- // -o comm Need only names column- const output = (- await execProm('ps x --no-heading -o comm --sort=comm')- ).stdout.toString();+ const output = processes+ .map(({executable}) => executable ?? '')+ .join('\n');const processNames = Object.keys(COMMON_EDITORS_LINUX);for (let i = 0; i < processNames.length; i++) {const processName = processNames[i];@@ -420,8 +410,6 @@ export async function guessEditor(): Promise<ProcessAndCommand[]> {return availableEditors;}- } catch {- // Ignore...}// Last resort, use old skool env varsdiff --git a/packages/studio-server/src/helpers/running-processes.ts b/packages/studio-server/src/helpers/running-processes.tsnew file mode 100644index 0000000000..33668a6937--- /dev/null+++ b/packages/studio-server/src/helpers/running-processes.ts@@ -0,0 +1,94 @@+import {execFile} from 'node:child_process';+import {promisify} from 'node:util';++const execFilePromise = promisify(execFile);++type RunningProcess = {+ executable: string | null;+ commandLine: string | null;+};++let processSnapshot: {+ promise: Promise<readonly RunningProcess[] | null>;+ expiresAt: number;+} | null = null;++export const getRunningProcesses = (): Promise<+ readonly RunningProcess[] | null+> => {+ if (processSnapshot !== null && processSnapshot.expiresAt > Date.now()) {+ return processSnapshot.promise;+ }++ const snapshot = {+ expiresAt: Infinity,+ promise: (async (): Promise<readonly RunningProcess[] | null> => {+ try {+ if (process.platform === 'win32') {+ const {stdout} = await execFilePromise(+ 'powershell.exe',+ [+ '-NoProfile',+ '-NonInteractive',+ '-Command',+ 'ConvertTo-Json -Compress -InputObject @(Get-CimInstance Win32_Process | Select-Object ExecutablePath, CommandLine)',+ ],+ {timeout: 5000},+ );+ const processes: {+ ExecutablePath: string | null;+ CommandLine: string | null;+ }[] = JSON.parse(stdout);+ return processes.map(({ExecutablePath, CommandLine}) => ({+ executable: ExecutablePath,+ commandLine: CommandLine,+ }));+ }++ if (process.platform === 'darwin') {+ const {stdout} = await execFilePromise('ps', ['-ax', '-o', 'comm='], {+ timeout: 5000,+ });+ return stdout+ .split('\n')+ .filter(Boolean)+ .map((line) => ({+ executable: line.trim(),+ commandLine: null,+ }));+ }++ if (process.platform === 'linux') {+ // AIX format descriptors separate the name and arguments with a tab,+ // preserving spaces in either field while querying ps only once.+ const {stdout} = await execFilePromise(+ 'ps',+ ['-axww', '--no-headers', '-o', '%c\t%a'],+ {timeout: 5000},+ );+ return stdout+ .split('\n')+ .filter(Boolean)+ .map((line) => {+ const separator = line.indexOf('\t');+ return {+ executable: line.slice(0, separator).trim(),+ commandLine: line.slice(separator + 1).trim(),+ };+ });+ }+ } catch {+ return null;+ }++ return null;+ })(),+ };+ processSnapshot = snapshot;+ // Share the in-flight query and its result across nearby editor and agent+ // requests, but refresh it when Studio is revisited later.+ snapshot.promise.then(() => {+ snapshot.expiresAt = Date.now() + 1000;+ });+ return snapshot.promise;+};