mirror of
https://github.com/AutoMaker-Org/automaker.git
synced 2026-03-17 22:13:08 +00:00
* fix(copilot): correct tool.execution_complete event handling The CopilotProvider was using incorrect event type and data structure for tool execution completion events from the @github/copilot-sdk, causing tool call outputs to be empty. Changes: - Update event type from 'tool.execution_end' to 'tool.execution_complete' - Fix data structure to use nested result.content instead of flat result - Fix error structure to use error.message instead of flat error - Add success field to match SDK event structure - Add tests for empty and missing result handling This aligns with the official @github/copilot-sdk v0.1.16 types defined in session-events.d.ts. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> * test(copilot): add edge case test for error with code field Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> * refactor(copilot): improve error handling and code quality Code review improvements: - Extract magic string '[ERROR]' to TOOL_ERROR_PREFIX constant - Add null-safe error handling with direct error variable assignment - Include error codes in error messages for better debugging - Add JSDoc documentation for tool.execution_complete handler - Update tests to verify error codes are displayed - Add missing tool_use_id assertion in error test These changes improve: - Code maintainability (no magic strings) - Debugging experience (error codes now visible) - Type safety (explicit null checks) - Test coverage (verify error code formatting) Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> * Changes from fix/bug-fixes-1-0 * test(copilot): add edge case test for error with code field Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> * Changes from fix/bug-fixes-1-0 * fix: Handle detached HEAD state in worktree discovery and recovery * fix: Remove unused isDevServerStarting prop and md: breakpoint classes * fix: Add missing dependency and sanitize persisted cache data * feat: Ensure NODE_ENV is set to test in vitest configs * feat: Configure Playwright to run only E2E tests * fix: Improve PR tracking and dev server lifecycle management * feat: Add settings-based defaults for planning mode, model config, and custom providers. Fixes #816 * feat: Add worktree and branch selector to graph view * fix: Add timeout and error handling for worktree HEAD ref resolution * fix: use absolute icon path and place icon outside asar on Linux The hicolor icon theme index only lists sizes up to 512x512, so an icon installed only at 1024x1024 is invisible to GNOME/KDE's theme resolver, causing both the app launcher and taskbar to show a generic icon. Additionally, BrowserWindow.icon cannot be read by the window manager when the file is inside app.asar. - extraResources: copy logo_larger.png to resources/ (outside asar) so it lands at /opt/Automaker/resources/logo_larger.png on install - linux.desktop.Icon: set to the absolute resources path, bypassing the hicolor theme lookup and its size constraints entirely - icon-manager.ts: on Linux production use process.resourcesPath so BrowserWindow receives a real filesystem path the WM can read directly Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com> * fix: use linux.desktop.entry for custom desktop Icon field electron-builder v26 rejects arbitrary keys in linux.desktop — the correct schema wraps custom .desktop overrides inside desktop.entry. Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com> * fix: set desktop name on Linux so taskbar uses the correct app icon Without app.setDesktopName(), the window manager cannot associate the running Electron process with automaker.desktop. GNOME/KDE fall back to _NET_WM_ICON which defaults to Electron's own bundled icon. Calling app.setDesktopName('automaker.desktop') before any window is created sets the _GTK_APPLICATION_ID hint and XDG app_id so the WM picks up the desktop entry's Icon for the taskbar. Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com> * Fix: memory and context views mobile friendly (#818) * Changes from fix/memory-and-context-mobile-friendly * fix: Improve file extension detection and add path traversal protection * refactor: Extract file extension utilities and add path traversal guards Code review improvements: - Extract isMarkdownFilename and isImageFilename to shared image-utils.ts - Remove duplicated code from context-view.tsx and memory-view.tsx - Add path traversal guard for context fixture utilities (matching memory) - Add 7 new tests for context fixture path traversal protection - Total 61 tests pass Addresses code review feedback from PR #813 Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> * test: Add e2e tests for profiles crud and board background persistence * Update apps/ui/playwright.config.ts Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com> * fix: Add robust test navigation handling and file filtering * fix: Format NODE_OPTIONS configuration on single line * test: Update profiles and board background persistence tests * test: Replace iPhone 13 Pro with Pixel 5 for mobile test consistency * Update apps/ui/src/components/views/context-view.tsx Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com> * chore: Remove test project directory * feat: Filter context files by type and improve mobile menu visibility --------- Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com> Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com> * fix: Improve test reliability and localhost handling * chore: Use explicit TEST_USE_EXTERNAL_BACKEND env var for server cleanup * feat: Add E2E/CI mock mode for provider factory and auth verification * feat: Add remoteBranch parameter to pull and rebase operations * chore: Enhance E2E testing setup with worker isolation and auth state management - Updated .gitignore to include worker-specific test fixtures. - Modified e2e-tests.yml to implement test sharding for improved CI performance. - Refactored global setup to authenticate once and save session state for reuse across tests. - Introduced worker-isolated fixture paths to prevent conflicts during parallel test execution. - Improved test navigation and loading handling for better reliability. - Updated various test files to utilize new auth state management and fixture paths. * fix: Update Playwright configuration and improve test reliability - Increased the number of workers in Playwright configuration for better parallelism in CI environments. - Enhanced the board background persistence test to ensure dropdown stability by waiting for the list to populate before interaction, improving test reliability. * chore: Simplify E2E test configuration and enhance mock implementations - Updated e2e-tests.yml to run tests in a single shard for streamlined CI execution. - Enhanced unit tests for worktree list handling by introducing a mock for execGitCommand, improving test reliability and coverage. - Refactored setup functions to better manage command mocks for git operations in tests. - Improved error handling in mkdirSafe function to account for undefined stats in certain environments. * refactor: Improve test configurations and enhance error handling - Updated Playwright configuration to clear VITE_SERVER_URL, ensuring the frontend uses the Vite proxy and preventing cookie domain mismatches. - Enhanced MergeRebaseDialog logic to normalize selectedBranch for better handling of various ref formats. - Improved global setup with a more robust backend health check, throwing an error if the backend is not healthy after retries. - Refactored project creation tests to handle file existence checks more reliably. - Added error handling for missing E2E source fixtures to guide setup process. - Enhanced memory navigation to handle sandbox dialog visibility more effectively. * refactor: Enhance Git command execution and improve test configurations - Updated Git command execution to merge environment paths correctly, ensuring proper command execution context. - Refactored the Git initialization process to handle errors more gracefully and ensure user configuration is set before creating the initial commit. - Improved test configurations by updating Playwright test identifiers for better clarity and consistency across different project states. - Enhanced cleanup functions in tests to handle directory removal more robustly, preventing errors during test execution. * fix: Resolve React hooks errors from duplicate instances in dependency tree * style: Format alias configuration for improved readability --------- Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> Co-authored-by: DhanushSantosh <dhanushsantoshs05@gmail.com> Co-authored-by: Claude Sonnet 4.6 <noreply@anthropic.com> Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com>
237 lines
8.4 KiB
TypeScript
237 lines
8.4 KiB
TypeScript
/**
|
|
* Shared git command execution utilities.
|
|
*
|
|
* This module provides the canonical `execGitCommand` helper and common
|
|
* git utilities used across services and routes. All consumers should
|
|
* import from here rather than defining their own copy.
|
|
*/
|
|
|
|
import fs from 'fs/promises';
|
|
import path from 'path';
|
|
import { spawnProcess } from '@automaker/platform';
|
|
import { createLogger } from '@automaker/utils';
|
|
|
|
const logger = createLogger('GitLib');
|
|
|
|
// Extended PATH so git is found when the process does not inherit a full shell PATH
|
|
// (e.g. Electron, some CI, or IDE-launched processes).
|
|
const pathSeparator = process.platform === 'win32' ? ';' : ':';
|
|
const extraPaths: string[] =
|
|
process.platform === 'win32'
|
|
? ([
|
|
process.env.LOCALAPPDATA && `${process.env.LOCALAPPDATA}\\Programs\\Git\\cmd`,
|
|
process.env.PROGRAMFILES && `${process.env.PROGRAMFILES}\\Git\\cmd`,
|
|
process.env['ProgramFiles(x86)'] && `${process.env['ProgramFiles(x86)']}\\Git\\cmd`,
|
|
].filter(Boolean) as string[])
|
|
: [
|
|
'/opt/homebrew/bin',
|
|
'/usr/local/bin',
|
|
'/usr/bin',
|
|
'/home/linuxbrew/.linuxbrew/bin',
|
|
process.env.HOME ? `${process.env.HOME}/.local/bin` : '',
|
|
].filter(Boolean);
|
|
|
|
const extendedPath = [process.env.PATH, ...extraPaths].filter(Boolean).join(pathSeparator);
|
|
const gitEnv = { ...process.env, PATH: extendedPath };
|
|
|
|
// ============================================================================
|
|
// Secure Command Execution
|
|
// ============================================================================
|
|
|
|
/**
|
|
* Execute git command with array arguments to prevent command injection.
|
|
* Uses spawnProcess from @automaker/platform for secure, cross-platform execution.
|
|
*
|
|
* @param args - Array of git command arguments (e.g., ['worktree', 'add', path])
|
|
* @param cwd - Working directory to execute the command in
|
|
* @param env - Optional additional environment variables to pass to the git process.
|
|
* These are merged on top of the current process environment. Pass
|
|
* `{ LC_ALL: 'C' }` to force git to emit English output regardless of the
|
|
* system locale so that text-based output parsing remains reliable.
|
|
* @param abortController - Optional AbortController to cancel the git process.
|
|
* When the controller is aborted the underlying process is sent SIGTERM and
|
|
* the returned promise rejects with an Error whose message is 'Process aborted'.
|
|
* @returns Promise resolving to stdout output
|
|
* @throws Error with stderr/stdout message if command fails. The thrown error
|
|
* also has `stdout` and `stderr` string properties for structured access.
|
|
*
|
|
* @example
|
|
* ```typescript
|
|
* // Safe: no injection possible
|
|
* await execGitCommand(['branch', '-D', branchName], projectPath);
|
|
*
|
|
* // Force English output for reliable text parsing:
|
|
* await execGitCommand(['rebase', '--', 'main'], worktreePath, { LC_ALL: 'C' });
|
|
*
|
|
* // With a process-level timeout:
|
|
* const controller = new AbortController();
|
|
* const timerId = setTimeout(() => controller.abort(), 30_000);
|
|
* try {
|
|
* await execGitCommand(['fetch', '--all', '--quiet'], cwd, undefined, controller);
|
|
* } finally {
|
|
* clearTimeout(timerId);
|
|
* }
|
|
*
|
|
* // Instead of unsafe:
|
|
* // await execAsync(`git branch -D ${branchName}`, { cwd });
|
|
* ```
|
|
*/
|
|
export async function execGitCommand(
|
|
args: string[],
|
|
cwd: string,
|
|
env?: Record<string, string>,
|
|
abortController?: AbortController
|
|
): Promise<string> {
|
|
const result = await spawnProcess({
|
|
command: 'git',
|
|
args,
|
|
cwd,
|
|
env:
|
|
env !== undefined
|
|
? {
|
|
...gitEnv,
|
|
...env,
|
|
PATH: [gitEnv.PATH, env.PATH].filter(Boolean).join(pathSeparator),
|
|
}
|
|
: gitEnv,
|
|
...(abortController !== undefined ? { abortController } : {}),
|
|
});
|
|
|
|
// spawnProcess returns { stdout, stderr, exitCode }
|
|
if (result.exitCode === 0) {
|
|
return result.stdout;
|
|
} else {
|
|
const errorMessage =
|
|
result.stderr || result.stdout || `Git command failed with code ${result.exitCode}`;
|
|
throw Object.assign(new Error(errorMessage), {
|
|
stdout: result.stdout,
|
|
stderr: result.stderr,
|
|
});
|
|
}
|
|
}
|
|
|
|
// ============================================================================
|
|
// Common Git Utilities
|
|
// ============================================================================
|
|
|
|
/**
|
|
* Get the current branch name for the given worktree.
|
|
*
|
|
* This is the canonical implementation shared across services. Services
|
|
* should import this rather than duplicating the logic locally.
|
|
*
|
|
* @param worktreePath - Path to the git worktree
|
|
* @returns The current branch name (trimmed)
|
|
*/
|
|
export async function getCurrentBranch(worktreePath: string): Promise<string> {
|
|
const branchOutput = await execGitCommand(['rev-parse', '--abbrev-ref', 'HEAD'], worktreePath);
|
|
return branchOutput.trim();
|
|
}
|
|
|
|
// ============================================================================
|
|
// Index Lock Recovery
|
|
// ============================================================================
|
|
|
|
/**
|
|
* Check whether an error message indicates a stale git index lock file.
|
|
*
|
|
* Git operations that write to the index (e.g. `git stash push`) will fail
|
|
* with "could not write index" or "Unable to create ... .lock" when a
|
|
* `.git/index.lock` file exists from a previously interrupted operation.
|
|
*
|
|
* @param errorMessage - The error string from a failed git command
|
|
* @returns true if the error looks like a stale index lock issue
|
|
*/
|
|
export function isIndexLockError(errorMessage: string): boolean {
|
|
const lower = errorMessage.toLowerCase();
|
|
return (
|
|
lower.includes('could not write index') ||
|
|
(lower.includes('unable to create') && lower.includes('index.lock')) ||
|
|
lower.includes('index.lock')
|
|
);
|
|
}
|
|
|
|
/**
|
|
* Attempt to remove a stale `.git/index.lock` file for the given worktree.
|
|
*
|
|
* Uses `git rev-parse --git-dir` to locate the correct `.git` directory,
|
|
* which works for both regular repositories and linked worktrees.
|
|
*
|
|
* @param worktreePath - Path to the git worktree (or main repo)
|
|
* @returns true if a lock file was found and removed, false otherwise
|
|
*/
|
|
export async function removeStaleIndexLock(worktreePath: string): Promise<boolean> {
|
|
try {
|
|
// Resolve the .git directory (handles worktrees correctly)
|
|
const gitDirRaw = await execGitCommand(['rev-parse', '--git-dir'], worktreePath);
|
|
const gitDir = path.resolve(worktreePath, gitDirRaw.trim());
|
|
const lockFilePath = path.join(gitDir, 'index.lock');
|
|
|
|
// Check if the lock file exists
|
|
try {
|
|
await fs.access(lockFilePath);
|
|
} catch {
|
|
// Lock file does not exist — nothing to remove
|
|
return false;
|
|
}
|
|
|
|
// Remove the stale lock file
|
|
await fs.unlink(lockFilePath);
|
|
logger.info('Removed stale index.lock file', { worktreePath, lockFilePath });
|
|
return true;
|
|
} catch (err) {
|
|
logger.warn('Failed to remove stale index.lock file', {
|
|
worktreePath,
|
|
error: err instanceof Error ? err.message : String(err),
|
|
});
|
|
return false;
|
|
}
|
|
}
|
|
|
|
/**
|
|
* Execute a git command with automatic retry when a stale index.lock is detected.
|
|
*
|
|
* If the command fails with an error indicating a locked index file, this
|
|
* helper will attempt to remove the stale `.git/index.lock` and retry the
|
|
* command exactly once.
|
|
*
|
|
* This is particularly useful for `git stash push` which writes to the
|
|
* index and commonly fails when a previous git operation was interrupted.
|
|
*
|
|
* @param args - Array of git command arguments
|
|
* @param cwd - Working directory to execute the command in
|
|
* @param env - Optional additional environment variables
|
|
* @returns Promise resolving to stdout output
|
|
* @throws The original error if retry also fails, or a non-lock error
|
|
*/
|
|
export async function execGitCommandWithLockRetry(
|
|
args: string[],
|
|
cwd: string,
|
|
env?: Record<string, string>
|
|
): Promise<string> {
|
|
try {
|
|
return await execGitCommand(args, cwd, env);
|
|
} catch (error: unknown) {
|
|
const err = error as { message?: string; stderr?: string };
|
|
const errorMessage = err.stderr || err.message || '';
|
|
|
|
if (!isIndexLockError(errorMessage)) {
|
|
throw error;
|
|
}
|
|
|
|
logger.info('Git command failed due to index lock, attempting cleanup and retry', {
|
|
cwd,
|
|
args: args.join(' '),
|
|
});
|
|
|
|
const removed = await removeStaleIndexLock(cwd);
|
|
if (!removed) {
|
|
// Could not remove the lock file — re-throw the original error
|
|
throw error;
|
|
}
|
|
|
|
// Retry the command once after removing the lock file
|
|
return await execGitCommand(args, cwd, env);
|
|
}
|
|
}
|