feat: implement worktree setup commands management

- Introduced `readFile` and `writeFile` methods in the FilesAPI for reading and writing files.
- Added `execCommands` method to execute shell commands in a specified directory.
- Implemented `runWorktreeSetupCommands` function to handle setup commands for worktrees.
- Created `OpenChamberConfig` service for managing project-specific configuration, including setup commands.
- Enhanced `useMultiRunStore` to save and execute setup commands during multi-run creation.
- Updated VSCode bridge to handle file read/write and command execution requests.
- Added server endpoints for reading and writing files, and executing shell commands.
This commit is contained in:
Bohdan Triapitsyn
2026-01-07 22:01:49 +02:00
parent b8463b787b
commit 4433888903
16 changed files with 1789 additions and 280 deletions
+110
View File
@@ -531,6 +531,116 @@ export async function handleBridgeMessage(message: BridgeRequest, ctx?: BridgeCo
return { id, type, success: true, data: { home: normalizeFsPath(home) } };
}
case 'api:fs:read': {
const target = (payload as { path: string })?.path;
if (!target) {
return { id, type, success: false, error: 'Path is required' };
}
try {
const workspaceRoot = vscode.workspace.workspaceFolders?.[0]?.uri.fsPath || os.homedir();
const resolvedPath = resolveUserPath(target, workspaceRoot);
const uri = vscode.Uri.file(resolvedPath);
const bytes = await vscode.workspace.fs.readFile(uri);
const content = Buffer.from(bytes).toString('utf8');
return { id, type, success: true, data: { content, path: normalizeFsPath(resolvedPath) } };
} catch (error) {
const message = error instanceof Error ? error.message : 'Failed to read file';
return { id, type, success: false, error: message };
}
}
case 'api:fs:write': {
const { path: targetPath, content } = (payload as { path: string; content: string }) || {};
if (!targetPath) {
return { id, type, success: false, error: 'Path is required' };
}
if (typeof content !== 'string') {
return { id, type, success: false, error: 'Content is required' };
}
try {
const workspaceRoot = vscode.workspace.workspaceFolders?.[0]?.uri.fsPath || os.homedir();
const resolvedPath = resolveUserPath(targetPath, workspaceRoot);
const uri = vscode.Uri.file(resolvedPath);
// Ensure parent directory exists
const parentUri = vscode.Uri.file(path.dirname(resolvedPath));
try {
await vscode.workspace.fs.createDirectory(parentUri);
} catch {
// Directory may already exist
}
await vscode.workspace.fs.writeFile(uri, Buffer.from(content, 'utf8'));
return { id, type, success: true, data: { success: true, path: normalizeFsPath(resolvedPath) } };
} catch (error) {
const message = error instanceof Error ? error.message : 'Failed to write file';
return { id, type, success: false, error: message };
}
}
case 'api:fs:exec': {
const { commands, cwd } = (payload as { commands: string[]; cwd: string }) || {};
if (!Array.isArray(commands) || commands.length === 0) {
return { id, type, success: false, error: 'Commands array is required' };
}
if (!cwd) {
return { id, type, success: false, error: 'Working directory (cwd) is required' };
}
try {
const workspaceRoot = vscode.workspace.workspaceFolders?.[0]?.uri.fsPath || os.homedir();
const resolvedCwd = resolveUserPath(cwd, workspaceRoot);
const { exec } = await import('child_process');
const { promisify } = await import('util');
const execAsync = promisify(exec);
const shell = process.env.SHELL || (process.platform === 'win32' ? 'cmd.exe' : '/bin/sh');
const shellFlag = process.platform === 'win32' ? '/c' : '-c';
const results: Array<{
command: string;
success: boolean;
exitCode?: number;
stdout?: string;
stderr?: string;
error?: string;
}> = [];
for (const cmd of commands) {
if (typeof cmd !== 'string' || !cmd.trim()) {
results.push({ command: cmd, success: false, error: 'Invalid command' });
continue;
}
try {
// Use async exec to not block the extension host event loop
const { stdout, stderr } = await execAsync(`${shell} ${shellFlag} "${cmd.replace(/"/g, '\\"')}"`, {
cwd: resolvedCwd,
timeout: 300000, // 5 minutes per command
});
results.push({
command: cmd,
success: true,
exitCode: 0,
stdout: (stdout || '').trim(),
stderr: (stderr || '').trim(),
});
} catch (execError) {
const err = execError as { code?: number; stdout?: string; stderr?: string; message?: string };
results.push({
command: cmd,
success: false,
exitCode: typeof err.code === 'number' ? err.code : 1,
stdout: (err.stdout || '').trim(),
stderr: (err.stderr || '').trim(),
error: err.message,
});
}
}
const allSucceeded = results.every((r) => r.success);
return { id, type, success: true, data: { success: allSucceeded, results } };
} catch (error) {
const message = error instanceof Error ? error.message : 'Failed to execute commands';
return { id, type, success: false, error: message };
}
}
case 'api:files/pick': {
const MAX_SIZE = 10 * 1024 * 1024;
const allowMany = (payload as { allowMany?: boolean })?.allowMany !== false;
+70 -51
View File
@@ -1,71 +1,90 @@
import type { DirectoryListResult, FileSearchQuery, FileSearchResult, FilesAPI } from '@openchamber/ui/lib/api/types';
import type {
CommandExecResult,
DirectoryListResult,
FileSearchQuery,
FileSearchResult,
FilesAPI,
} from '@openchamber/ui/lib/api/types';
// Use same endpoints as web - fetch interceptor handles URL rewriting
const normalizePath = (path: string): string => path.replace(/\\/g, '/');
import { sendBridgeMessage, sendBridgeMessageWithOptions } from './bridge';
const normalizePath = (value: string): string => value.replace(/\\/g, '/');
export const createVSCodeFilesAPI = (): FilesAPI => ({
async listDirectory(path: string): Promise<DirectoryListResult> {
const target = normalizePath(path);
const response = await fetch('/api/fs/list', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ path: target }),
});
const data = await sendBridgeMessage<{
directory?: string;
path?: string;
entries: Array<{ name: string; path: string; isDirectory: boolean }>;
}>('api:fs:list', { path: target });
if (!response.ok) {
const error = await response.json().catch(() => ({ error: response.statusText }));
throw new Error(error.error || 'Failed to list directory');
}
return response.json();
const directory = normalizePath(data?.directory || data?.path || target);
const entries = Array.isArray(data?.entries) ? data.entries : [];
return {
directory,
entries: entries.map((entry) => ({
name: entry.name,
path: normalizePath(entry.path),
isDirectory: Boolean(entry.isDirectory),
})),
};
},
async search(payload: FileSearchQuery): Promise<FileSearchResult[]> {
const response = await fetch('/api/fs/search', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
directory: normalizePath(payload.directory),
query: payload.query,
maxResults: payload.maxResults,
}),
const data = await sendBridgeMessage<{ files: Array<{ path: string; relativePath?: string }> }>('api:fs:search', {
directory: normalizePath(payload.directory),
query: payload.query,
limit: payload.maxResults,
});
if (!response.ok) {
const error = await response.json().catch(() => ({ error: response.statusText }));
throw new Error(error.error || 'Failed to search files');
}
const results = (await response.json()) as unknown;
if (!Array.isArray(results)) {
return [];
}
return results
.filter((item): item is FileSearchResult => !!item && typeof item === 'object' && typeof (item as { path?: string }).path === 'string')
.map((item) => ({
path: normalizePath((item as FileSearchResult).path),
score: (item as FileSearchResult).score,
preview: (item as FileSearchResult).preview,
const files = Array.isArray(data?.files) ? data.files : [];
return files
.filter((file) => file && typeof file.path === 'string')
.map((file) => ({
path: normalizePath(file.path),
preview: file.relativePath ? [normalizePath(file.relativePath)] : undefined,
}));
},
async createDirectory(path: string): Promise<{ success: boolean; path: string }> {
const target = normalizePath(path);
const response = await fetch('/api/fs/mkdir', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ path: target }),
});
if (!response.ok) {
const error = await response.json().catch(() => ({ error: response.statusText }));
throw new Error(error.error || 'Failed to create directory');
}
const result = await response.json();
const data = await sendBridgeMessage<{ success: boolean; path: string }>('api:fs:mkdir', { path: target });
return {
success: Boolean(result?.success),
path: typeof result?.path === 'string' ? normalizePath(result.path) : target,
success: Boolean(data?.success),
path: typeof data?.path === 'string' ? normalizePath(data.path) : target,
};
},
async readFile(path: string): Promise<{ content: string; path: string }> {
const target = normalizePath(path);
const data = await sendBridgeMessage<{ content: string; path: string }>('api:fs:read', { path: target });
return {
content: typeof data?.content === 'string' ? data.content : '',
path: typeof data?.path === 'string' ? normalizePath(data.path) : target,
};
},
async writeFile(path: string, content: string): Promise<{ success: boolean; path: string }> {
const target = normalizePath(path);
const data = await sendBridgeMessage<{ success: boolean; path: string }>('api:fs:write', { path: target, content });
return {
success: Boolean(data?.success),
path: typeof data?.path === 'string' ? normalizePath(data.path) : target,
};
},
async execCommands(commands: string[], cwd: string): Promise<{ success: boolean; results: CommandExecResult[] }> {
const targetCwd = normalizePath(cwd);
// Use extended timeout for command execution (5 minutes)
const data = await sendBridgeMessageWithOptions<{ success: boolean; results?: CommandExecResult[] }>('api:fs:exec', {
commands,
cwd: targetCwd,
}, { timeoutMs: 300000 });
return {
success: Boolean(data?.success),
results: Array.isArray(data?.results) ? data.results : [],
};
},
});