Bug fixes and stability improvements (#815)

* 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>
This commit is contained in:
gsxdsm
2026-02-27 17:03:29 -08:00
committed by GitHub
parent 70d400793b
commit 0196911d59
234 changed files with 15881 additions and 2916 deletions

View File

@@ -70,6 +70,8 @@ export async function parseAndCreateFeatures(
priority: feature.priority || 2,
complexity: feature.complexity || 'moderate',
dependencies: feature.dependencies || [],
planningMode: 'skip',
requirePlanApproval: false,
createdAt: new Date().toISOString(),
updatedAt: new Date().toISOString(),
};

View File

@@ -25,7 +25,7 @@ export function createBacklogPlanRoutes(
);
router.post('/stop', createStopHandler());
router.get('/status', validatePathParams('projectPath'), createStatusHandler());
router.post('/apply', validatePathParams('projectPath'), createApplyHandler());
router.post('/apply', validatePathParams('projectPath'), createApplyHandler(settingsService));
router.post('/clear', validatePathParams('projectPath'), createClearHandler());
return router;

View File

@@ -3,13 +3,23 @@
*/
import type { Request, Response } from 'express';
import type { BacklogPlanResult } from '@automaker/types';
import { resolvePhaseModel } from '@automaker/model-resolver';
import type { BacklogPlanResult, PhaseModelEntry, PlanningMode } from '@automaker/types';
import { FeatureLoader } from '../../../services/feature-loader.js';
import type { SettingsService } from '../../../services/settings-service.js';
import { clearBacklogPlan, getErrorMessage, logError, logger } from '../common.js';
const featureLoader = new FeatureLoader();
export function createApplyHandler() {
function normalizePhaseModelEntry(
entry: PhaseModelEntry | string | undefined | null
): PhaseModelEntry | undefined {
if (!entry) return undefined;
if (typeof entry === 'string') return { model: entry };
return entry;
}
export function createApplyHandler(settingsService?: SettingsService) {
return async (req: Request, res: Response): Promise<void> => {
try {
const {
@@ -38,6 +48,23 @@ export function createApplyHandler() {
return;
}
let defaultPlanningMode: PlanningMode = 'skip';
let defaultRequirePlanApproval = false;
let defaultModelEntry: PhaseModelEntry | undefined;
if (settingsService) {
const globalSettings = await settingsService.getGlobalSettings();
const projectSettings = await settingsService.getProjectSettings(projectPath);
defaultPlanningMode = globalSettings.defaultPlanningMode ?? 'skip';
defaultRequirePlanApproval = globalSettings.defaultRequirePlanApproval ?? false;
defaultModelEntry = normalizePhaseModelEntry(
projectSettings.defaultFeatureModel ?? globalSettings.defaultFeatureModel
);
}
const resolvedDefaultModel = resolvePhaseModel(defaultModelEntry);
const appliedChanges: string[] = [];
// Load current features for dependency validation
@@ -88,6 +115,12 @@ export function createApplyHandler() {
if (!change.feature) continue;
try {
const effectivePlanningMode = change.feature.planningMode ?? defaultPlanningMode;
const effectiveRequirePlanApproval =
effectivePlanningMode === 'skip' || effectivePlanningMode === 'lite'
? false
: (change.feature.requirePlanApproval ?? defaultRequirePlanApproval);
// Create the new feature - use the AI-generated ID if provided
const newFeature = await featureLoader.create(projectPath, {
id: change.feature.id, // Use descriptive ID from AI if provided
@@ -97,6 +130,12 @@ export function createApplyHandler() {
dependencies: change.feature.dependencies,
priority: change.feature.priority,
status: 'backlog',
model: change.feature.model ?? resolvedDefaultModel.model,
thinkingLevel: change.feature.thinkingLevel ?? resolvedDefaultModel.thinkingLevel,
reasoningEffort: change.feature.reasoningEffort ?? resolvedDefaultModel.reasoningEffort,
providerId: change.feature.providerId ?? resolvedDefaultModel.providerId,
planningMode: effectivePlanningMode,
requirePlanApproval: effectiveRequirePlanApproval,
branchName,
});

View File

@@ -43,7 +43,11 @@ export function createUpdateHandler(featureLoader: FeatureLoader, events?: Event
// Get the current feature to detect status changes
const currentFeature = await featureLoader.get(projectPath, featureId);
const previousStatus = currentFeature?.status as FeatureStatus | undefined;
if (!currentFeature) {
res.status(404).json({ success: false, error: `Feature ${featureId} not found` });
return;
}
const previousStatus = currentFeature.status as FeatureStatus;
const newStatus = updates.status as FeatureStatus | undefined;
const updated = await featureLoader.update(

View File

@@ -3,16 +3,29 @@
*/
import type { Request, Response } from 'express';
import path from 'path';
import * as secureFs from '../../../lib/secure-fs.js';
import { PathNotAllowedError } from '@automaker/platform';
import { getErrorMessage, logError } from '../common.js';
// Optional files that are expected to not exist in new projects
// Don't log ENOENT errors for these to reduce noise
const OPTIONAL_FILES = ['categories.json', 'app_spec.txt'];
const OPTIONAL_FILES = ['categories.json', 'app_spec.txt', 'context-metadata.json'];
function isOptionalFile(filePath: string): boolean {
return OPTIONAL_FILES.some((optionalFile) => filePath.endsWith(optionalFile));
const basename = path.basename(filePath);
if (OPTIONAL_FILES.some((optionalFile) => basename === optionalFile)) {
return true;
}
// Context and memory files may not exist yet during create/delete or test races
if (filePath.includes('.automaker/context/') || filePath.includes('.automaker/memory/')) {
const name = path.basename(filePath);
const lower = name.toLowerCase();
if (lower.endsWith('.md') || lower.endsWith('.txt') || lower.endsWith('.markdown')) {
return true;
}
}
return false;
}
function isENOENT(error: unknown): boolean {
@@ -39,12 +52,14 @@ export function createReadHandler() {
return;
}
// Don't log ENOENT errors for optional files (expected to be missing in new projects)
const shouldLog = !(isENOENT(error) && isOptionalFile(req.body?.filePath || ''));
if (shouldLog) {
const filePath = req.body?.filePath || '';
const optionalMissing = isENOENT(error) && isOptionalFile(filePath);
if (!optionalMissing) {
logError(error, 'Read file failed');
}
res.status(500).json({ success: false, error: getErrorMessage(error) });
// Return 404 for missing optional files so clients can handle "not found"
const status = optionalMissing ? 404 : 500;
res.status(status).json({ success: false, error: getErrorMessage(error) });
}
};
}

View File

@@ -35,6 +35,16 @@ export function createStatHandler() {
return;
}
// File or directory does not exist - return 404 so UI can handle missing paths
const code =
error && typeof error === 'object' && 'code' in error
? (error as { code: string }).code
: '';
if (code === 'ENOENT') {
res.status(404).json({ success: false, error: 'File or directory not found' });
return;
}
logError(error, 'Get file stats failed');
res.status(500).json({ success: false, error: getErrorMessage(error) });
}

View File

@@ -38,7 +38,7 @@ import {
import {
getPromptCustomization,
getAutoLoadClaudeMdSetting,
getProviderByModelId,
resolveProviderContext,
} from '../../../lib/settings-helpers.js';
import {
trySetValidationRunning,
@@ -64,6 +64,8 @@ interface ValidateIssueRequestBody {
thinkingLevel?: ThinkingLevel;
/** Reasoning effort for Codex models (ignored for non-Codex models) */
reasoningEffort?: ReasoningEffort;
/** Optional Claude-compatible provider ID for custom providers (e.g., GLM, MiniMax) */
providerId?: string;
/** Comments to include in validation analysis */
comments?: GitHubComment[];
/** Linked pull requests for this issue */
@@ -87,6 +89,7 @@ async function runValidation(
events: EventEmitter,
abortController: AbortController,
settingsService?: SettingsService,
providerId?: string,
comments?: ValidationComment[],
linkedPRs?: ValidationLinkedPR[],
thinkingLevel?: ThinkingLevel,
@@ -176,7 +179,12 @@ ${basePrompt}`;
let credentials = await settingsService?.getCredentials();
if (settingsService) {
const providerResult = await getProviderByModelId(model, settingsService, '[ValidateIssue]');
const providerResult = await resolveProviderContext(
settingsService,
model,
providerId,
'[ValidateIssue]'
);
if (providerResult.provider) {
claudeCompatibleProvider = providerResult.provider;
providerResolvedModel = providerResult.resolvedModel;
@@ -312,10 +320,16 @@ export function createValidateIssueHandler(
model = 'opus',
thinkingLevel,
reasoningEffort,
providerId,
comments: rawComments,
linkedPRs: rawLinkedPRs,
} = req.body as ValidateIssueRequestBody;
const normalizedProviderId =
typeof providerId === 'string' && providerId.trim().length > 0
? providerId.trim()
: undefined;
// Transform GitHubComment[] to ValidationComment[] if provided
const validationComments: ValidationComment[] | undefined = rawComments?.map((c) => ({
author: c.author?.login || 'ghost',
@@ -364,12 +378,14 @@ export function createValidateIssueHandler(
isClaudeModel(model) ||
isCursorModel(model) ||
isCodexModel(model) ||
isOpencodeModel(model);
isOpencodeModel(model) ||
!!normalizedProviderId;
if (!isValidModel) {
res.status(400).json({
success: false,
error: 'Invalid model. Must be a Claude, Cursor, Codex, or OpenCode model ID (or alias).',
error:
'Invalid model. Must be a Claude, Cursor, Codex, or OpenCode model ID (or alias), or provide a valid providerId for custom Claude-compatible models.',
});
return;
}
@@ -398,6 +414,7 @@ export function createValidateIssueHandler(
events,
abortController,
settingsService,
normalizedProviderId,
validationComments,
validationLinkedPRs,
thinkingLevel,

View File

@@ -80,6 +80,12 @@ function containsAuthError(text: string): boolean {
export function createVerifyClaudeAuthHandler() {
return async (req: Request, res: Response): Promise<void> => {
try {
// In E2E/CI mock mode, skip real API calls
if (process.env.AUTOMAKER_MOCK_AGENT === 'true') {
res.json({ success: true, authenticated: true });
return;
}
// Get the auth method and optional API key from the request body
const { authMethod, apiKey } = req.body as {
authMethod?: 'cli' | 'api_key';

View File

@@ -82,6 +82,12 @@ function isRateLimitError(text: string): boolean {
export function createVerifyCodexAuthHandler() {
return async (req: Request, res: Response): Promise<void> => {
// In E2E/CI mock mode, skip real API calls
if (process.env.AUTOMAKER_MOCK_AGENT === 'true') {
res.json({ success: true, authenticated: true });
return;
}
const { authMethod, apiKey } = req.body as {
authMethod?: 'cli' | 'api_key';
apiKey?: string;

View File

@@ -44,13 +44,79 @@ export function createInitGitHandler() {
}
// Initialize git with 'main' as the default branch (matching GitHub's standard since 2020)
// and create an initial empty commit
await execAsync(
`git init --initial-branch=main && git commit --allow-empty -m "Initial commit"`,
{
cwd: projectPath,
// Run commands sequentially so failures can be handled and partial state cleaned up.
let gitDirCreated = false;
try {
// Step 1: initialize the repository
try {
await execAsync(`git init --initial-branch=main`, { cwd: projectPath });
} catch (initError: unknown) {
const stderr =
initError && typeof initError === 'object' && 'stderr' in initError
? String((initError as { stderr?: string }).stderr)
: '';
// Idempotent: if .git was created by a concurrent request or a stale lock exists,
// treat as "repo already exists" instead of failing
if (
/could not lock config file.*File exists|fatal: could not set 'core\.repositoryformatversion'/.test(
stderr
)
) {
try {
await secureFs.access(gitDirPath);
res.json({
success: true,
result: {
initialized: false,
message: 'Git repository already exists',
},
});
return;
} catch {
// .git still missing, rethrow original error
}
}
throw initError;
}
);
gitDirCreated = true;
// Step 2: ensure user.name and user.email are set so the commit can succeed.
// Check the global/system config first; only set locally if missing.
let userName = '';
let userEmail = '';
try {
({ stdout: userName } = await execAsync(`git config user.name`, { cwd: projectPath }));
} catch {
// not set globally will configure locally below
}
try {
({ stdout: userEmail } = await execAsync(`git config user.email`, {
cwd: projectPath,
}));
} catch {
// not set globally will configure locally below
}
if (!userName.trim()) {
await execAsync(`git config user.name "Automaker"`, { cwd: projectPath });
}
if (!userEmail.trim()) {
await execAsync(`git config user.email "automaker@localhost"`, { cwd: projectPath });
}
// Step 3: create the initial empty commit
await execAsync(`git commit --allow-empty -m "Initial commit"`, { cwd: projectPath });
} catch (error: unknown) {
// Clean up the partial .git directory so subsequent runs behave deterministically
if (gitDirCreated) {
try {
await secureFs.rm(gitDirPath, { recursive: true, force: true });
} catch {
// best-effort cleanup; ignore errors
}
}
throw error;
}
res.json({
success: true,

View File

@@ -6,12 +6,11 @@
*/
import type { Request, Response } from 'express';
import { exec, execFile } from 'child_process';
import { execFile } from 'child_process';
import { promisify } from 'util';
import { getErrorMessage, logWorktreeError } from '../common.js';
import { getErrorMessage, logWorktreeError, execGitCommand } from '../common.js';
import { getRemotesWithBranch } from '../../../services/worktree-service.js';
const execAsync = promisify(exec);
const execFileAsync = promisify(execFile);
interface BranchInfo {
@@ -36,18 +35,18 @@ export function createListBranchesHandler() {
return;
}
// Get current branch
const { stdout: currentBranchOutput } = await execAsync('git rev-parse --abbrev-ref HEAD', {
cwd: worktreePath,
});
// Get current branch (execGitCommand avoids spawning /bin/sh; works in sandboxed CI)
const currentBranchOutput = await execGitCommand(
['rev-parse', '--abbrev-ref', 'HEAD'],
worktreePath
);
const currentBranch = currentBranchOutput.trim();
// List all local branches
// Use double quotes around the format string for cross-platform compatibility
// Single quotes are preserved literally on Windows; double quotes work on both
const { stdout: branchesOutput } = await execAsync('git branch --format="%(refname:short)"', {
cwd: worktreePath,
});
const branchesOutput = await execGitCommand(
['branch', '--format=%(refname:short)'],
worktreePath
);
const branches: BranchInfo[] = branchesOutput
.trim()
@@ -68,18 +67,15 @@ export function createListBranchesHandler() {
try {
// Fetch latest remote refs (silently, don't fail if offline)
try {
await execAsync('git fetch --all --quiet', {
cwd: worktreePath,
timeout: 10000, // 10 second timeout
});
await execGitCommand(['fetch', '--all', '--quiet'], worktreePath);
} catch {
// Ignore fetch errors - we'll use cached remote refs
}
// List remote branches
const { stdout: remoteBranchesOutput } = await execAsync(
'git branch -r --format="%(refname:short)"',
{ cwd: worktreePath }
const remoteBranchesOutput = await execGitCommand(
['branch', '-r', '--format=%(refname:short)'],
worktreePath
);
const localBranchNames = new Set(branches.map((b) => b.name));
@@ -118,9 +114,7 @@ export function createListBranchesHandler() {
// Check if any remotes are configured for this repository
let hasAnyRemotes = false;
try {
const { stdout: remotesOutput } = await execAsync('git remote', {
cwd: worktreePath,
});
const remotesOutput = await execGitCommand(['remote'], worktreePath);
hasAnyRemotes = remotesOutput.trim().length > 0;
} catch {
// If git remote fails, assume no remotes

View File

@@ -13,7 +13,14 @@ import { promisify } from 'util';
import path from 'path';
import * as secureFs from '../../../lib/secure-fs.js';
import { isGitRepo } from '@automaker/git-utils';
import { getErrorMessage, logError, normalizePath, execEnv, isGhCliAvailable } from '../common.js';
import {
getErrorMessage,
logError,
normalizePath,
execEnv,
isGhCliAvailable,
execGitCommand,
} from '../common.js';
import {
readAllWorktreeMetadata,
updateWorktreePRInfo,
@@ -29,6 +36,22 @@ import {
const execAsync = promisify(exec);
const logger = createLogger('Worktree');
/** True when git (or shell) could not be spawned (e.g. ENOENT in sandboxed CI). */
function isSpawnENOENT(error: unknown): boolean {
if (!error || typeof error !== 'object') return false;
const e = error as { code?: string; errno?: number; syscall?: string };
// Accept ENOENT with or without syscall so wrapped/reexported errors are handled.
// Node may set syscall to 'spawn' or 'spawn git' (or other command name).
if (e.code === 'ENOENT' || e.errno === -2) {
return (
e.syscall === 'spawn' ||
(typeof e.syscall === 'string' && e.syscall.startsWith('spawn')) ||
e.syscall === undefined
);
}
return false;
}
/**
* Cache for GitHub remote status per project path.
* This prevents repeated "no git remotes found" warnings when polling
@@ -77,11 +100,8 @@ async function detectConflictState(worktreePath: string): Promise<{
conflictFiles?: string[];
}> {
try {
// Find the canonical .git directory for this worktree
const { stdout: gitDirRaw } = await execAsync('git rev-parse --git-dir', {
cwd: worktreePath,
timeout: 15000,
});
// Find the canonical .git directory for this worktree (execGitCommand avoids /bin/sh in CI)
const gitDirRaw = await execGitCommand(['rev-parse', '--git-dir'], worktreePath);
const gitDir = path.resolve(worktreePath, gitDirRaw.trim());
// Check for merge, rebase, and cherry-pick state files/directories
@@ -121,10 +141,10 @@ async function detectConflictState(worktreePath: string): Promise<{
// Get list of conflicted files using machine-readable git status
let conflictFiles: string[] = [];
try {
const { stdout: statusOutput } = await execAsync('git diff --name-only --diff-filter=U', {
cwd: worktreePath,
timeout: 15000,
});
const statusOutput = await execGitCommand(
['diff', '--name-only', '--diff-filter=U'],
worktreePath
);
conflictFiles = statusOutput
.trim()
.split('\n')
@@ -146,13 +166,69 @@ async function detectConflictState(worktreePath: string): Promise<{
async function getCurrentBranch(cwd: string): Promise<string> {
try {
const { stdout } = await execAsync('git branch --show-current', { cwd });
const stdout = await execGitCommand(['branch', '--show-current'], cwd);
return stdout.trim();
} catch {
return '';
}
}
function normalizeBranchFromHeadRef(headRef: string): string | null {
let normalized = headRef.trim();
const prefixes = ['refs/heads/', 'refs/remotes/origin/', 'refs/remotes/', 'refs/'];
for (const prefix of prefixes) {
if (normalized.startsWith(prefix)) {
normalized = normalized.slice(prefix.length);
break;
}
}
// Return the full branch name, including any slashes (e.g., "feature/my-branch")
return normalized || null;
}
/**
* Attempt to recover the branch name for a worktree in detached HEAD state.
* This happens during rebase operations where git detaches HEAD from the branch.
* We look at git state files (rebase-merge/head-name, rebase-apply/head-name)
* to determine which branch the operation is targeting.
*
* Note: merge conflicts do NOT detach HEAD, so `git worktree list --porcelain`
* still includes the `branch` line for merge conflicts. This recovery is
* specifically for rebase and cherry-pick operations.
*/
async function recoverBranchForDetachedWorktree(worktreePath: string): Promise<string | null> {
try {
const gitDirRaw = await execGitCommand(['rev-parse', '--git-dir'], worktreePath);
const gitDir = path.resolve(worktreePath, gitDirRaw.trim());
// During a rebase, the original branch is stored in rebase-merge/head-name
try {
const headNamePath = path.join(gitDir, 'rebase-merge', 'head-name');
const headName = (await secureFs.readFile(headNamePath, 'utf-8')) as string;
const branch = normalizeBranchFromHeadRef(headName);
if (branch) return branch;
} catch {
// Not a rebase-merge
}
// rebase-apply also stores the original branch in head-name
try {
const headNamePath = path.join(gitDir, 'rebase-apply', 'head-name');
const headName = (await secureFs.readFile(headNamePath, 'utf-8')) as string;
const branch = normalizeBranchFromHeadRef(headName);
if (branch) return branch;
} catch {
// Not a rebase-apply
}
return null;
} catch {
return null;
}
}
/**
* Scan the .worktrees directory to discover worktrees that may exist on disk
* but are not registered with git (e.g., created externally or corrupted state).
@@ -204,22 +280,36 @@ async function scanWorktreesDirectory(
});
} else {
// Try to get branch from HEAD if branch --show-current fails (detached HEAD)
let headBranch: string | null = null;
try {
const { stdout: headRef } = await execAsync('git rev-parse --abbrev-ref HEAD', {
cwd: worktreePath,
});
const headBranch = headRef.trim();
if (headBranch && headBranch !== 'HEAD') {
logger.info(
`Discovered worktree in .worktrees/ not in git worktree list: ${entry.name} (branch: ${headBranch})`
);
discovered.push({
path: normalizedPath,
branch: headBranch,
});
const headRef = await execGitCommand(
['rev-parse', '--abbrev-ref', 'HEAD'],
worktreePath
);
const ref = headRef.trim();
if (ref && ref !== 'HEAD') {
headBranch = ref;
}
} catch {
// Can't determine branch, skip this directory
} catch (error) {
// Can't determine branch from HEAD ref (including timeout) - fall back to detached HEAD recovery
logger.debug(
`Failed to resolve HEAD ref for ${worktreePath}: ${getErrorMessage(error)}`
);
}
// If HEAD is detached (rebase/merge in progress), try recovery from git state files
if (!headBranch) {
headBranch = await recoverBranchForDetachedWorktree(worktreePath);
}
if (headBranch) {
logger.info(
`Discovered worktree in .worktrees/ not in git worktree list: ${entry.name} (branch: ${headBranch})`
);
discovered.push({
path: normalizedPath,
branch: headBranch,
});
}
}
}
@@ -378,15 +468,14 @@ export function createListHandler() {
// Get current branch in main directory
const currentBranch = await getCurrentBranch(projectPath);
// Get actual worktrees from git
const { stdout } = await execAsync('git worktree list --porcelain', {
cwd: projectPath,
});
// Get actual worktrees from git (execGitCommand avoids /bin/sh in sandboxed CI)
const stdout = await execGitCommand(['worktree', 'list', '--porcelain'], projectPath);
const worktrees: WorktreeInfo[] = [];
const removedWorktrees: Array<{ path: string; branch: string }> = [];
let hasMissingWorktree = false;
const lines = stdout.split('\n');
let current: { path?: string; branch?: string } = {};
let current: { path?: string; branch?: string; isDetached?: boolean } = {};
let isFirst = true;
// First pass: detect removed worktrees
@@ -395,8 +484,11 @@ export function createListHandler() {
current.path = normalizePath(line.slice(9));
} else if (line.startsWith('branch ')) {
current.branch = line.slice(7).replace('refs/heads/', '');
} else if (line.startsWith('detached')) {
// Worktree is in detached HEAD state (e.g., during rebase)
current.isDetached = true;
} else if (line === '') {
if (current.path && current.branch) {
if (current.path) {
const isMainWorktree = isFirst;
// Check if the worktree directory actually exists
// Skip checking/pruning the main worktree (projectPath itself)
@@ -407,14 +499,19 @@ export function createListHandler() {
} catch {
worktreeExists = false;
}
if (!isMainWorktree && !worktreeExists) {
hasMissingWorktree = true;
// Worktree directory doesn't exist - it was manually deleted
removedWorktrees.push({
path: current.path,
branch: current.branch,
});
} else {
// Worktree exists (or is main worktree), add it to the list
// Only add to removed list if we know the branch name
if (current.branch) {
removedWorktrees.push({
path: current.path,
branch: current.branch,
});
}
} else if (current.branch) {
// Normal case: worktree with a known branch
worktrees.push({
path: current.path,
branch: current.branch,
@@ -423,16 +520,29 @@ export function createListHandler() {
hasWorktree: true,
});
isFirst = false;
} else if (current.isDetached && worktreeExists) {
// Detached HEAD (e.g., rebase in progress) - try to recover branch name.
// This is critical: without this, worktrees undergoing rebase/merge
// operations would silently disappear from the UI.
const recoveredBranch = await recoverBranchForDetachedWorktree(current.path);
worktrees.push({
path: current.path,
branch: recoveredBranch || `(detached)`,
isMain: isMainWorktree,
isCurrent: false,
hasWorktree: true,
});
isFirst = false;
}
}
current = {};
}
}
// Prune removed worktrees from git (only if any were detected)
if (removedWorktrees.length > 0) {
// Prune removed worktrees from git (only if any missing worktrees were detected)
if (hasMissingWorktree) {
try {
await execAsync('git worktree prune', { cwd: projectPath });
await execGitCommand(['worktree', 'prune'], projectPath);
} catch {
// Prune failed, but we'll still report the removed worktrees
}
@@ -461,9 +571,7 @@ export function createListHandler() {
if (includeDetails) {
for (const worktree of worktrees) {
try {
const { stdout: statusOutput } = await execAsync('git status --porcelain', {
cwd: worktree.path,
});
const statusOutput = await execGitCommand(['status', '--porcelain'], worktree.path);
const changedFiles = statusOutput
.trim()
.split('\n')
@@ -492,7 +600,7 @@ export function createListHandler() {
}
}
// Assign PR info to each worktree, preferring fresh GitHub data over cached metadata.
// Assign PR info to each worktree.
// Only fetch GitHub PRs if includeDetails is requested (performance optimization).
// Uses --state all to detect merged/closed PRs, limited to 1000 recent PRs.
const githubPRs = includeDetails
@@ -510,14 +618,27 @@ export function createListHandler() {
const metadata = allMetadata.get(worktree.branch);
const githubPR = githubPRs.get(worktree.branch);
if (githubPR) {
// Prefer fresh GitHub data (it has the current state)
const metadataPR = metadata?.pr;
// Preserve explicit user-selected PR tracking from metadata when it differs
// from branch-derived GitHub PR lookup. This allows "Change PR Number" to
// persist instead of being overwritten by gh pr list for the branch.
const hasManualOverride =
!!metadataPR && !!githubPR && metadataPR.number !== githubPR.number;
if (hasManualOverride) {
worktree.pr = metadataPR;
} else if (githubPR) {
// Use fresh GitHub data when there is no explicit override.
worktree.pr = githubPR;
// Sync metadata with GitHub state when:
// 1. No metadata exists for this PR (PR created externally)
// 2. State has changed (e.g., merged/closed on GitHub)
const needsSync = !metadata?.pr || metadata.pr.state !== githubPR.state;
// Sync metadata when missing or stale so fallback data stays current.
const needsSync =
!metadataPR ||
metadataPR.number !== githubPR.number ||
metadataPR.state !== githubPR.state ||
metadataPR.title !== githubPR.title ||
metadataPR.url !== githubPR.url ||
metadataPR.createdAt !== githubPR.createdAt;
if (needsSync) {
// Fire and forget - don't block the response
updateWorktreePRInfo(projectPath, worktree.branch, githubPR).catch((err) => {
@@ -526,9 +647,9 @@ export function createListHandler() {
);
});
}
} else if (metadata?.pr && metadata.pr.state === 'OPEN') {
} else if (metadataPR && metadataPR.state === 'OPEN') {
// Fall back to stored metadata only if the PR is still OPEN
worktree.pr = metadata.pr;
worktree.pr = metadataPR;
}
}
@@ -538,6 +659,26 @@ export function createListHandler() {
removedWorktrees: removedWorktrees.length > 0 ? removedWorktrees : undefined,
});
} catch (error) {
// When git is unavailable (e.g. sandboxed E2E, PATH without git), return minimal list so UI still loads
if (isSpawnENOENT(error)) {
const projectPathFromBody = (req.body as { projectPath?: string })?.projectPath;
const mainPath = projectPathFromBody ? normalizePath(projectPathFromBody) : undefined;
if (mainPath) {
res.json({
success: true,
worktrees: [
{
path: mainPath,
branch: 'main',
isMain: true,
isCurrent: true,
hasWorktree: true,
},
],
});
return;
}
}
logError(error, 'List worktrees failed');
res.status(500).json({ success: false, error: getErrorMessage(error) });
}

View File

@@ -23,9 +23,11 @@ import type { PullResult } from '../../../services/pull-service.js';
export function createPullHandler() {
return async (req: Request, res: Response): Promise<void> => {
try {
const { worktreePath, remote, stashIfNeeded } = req.body as {
const { worktreePath, remote, remoteBranch, stashIfNeeded } = req.body as {
worktreePath: string;
remote?: string;
/** Specific remote branch to pull (e.g. 'main'). When provided, pulls this branch from the remote regardless of tracking config. */
remoteBranch?: string;
/** When true, automatically stash local changes before pulling and reapply after */
stashIfNeeded?: boolean;
};
@@ -39,7 +41,7 @@ export function createPullHandler() {
}
// Execute the pull via the service
const result = await performPull(worktreePath, { remote, stashIfNeeded });
const result = await performPull(worktreePath, { remote, remoteBranch, stashIfNeeded });
// Map service result to HTTP response
mapResultToResponse(res, result);