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

@@ -349,7 +349,9 @@ const ideationService = new IdeationService(events, settingsService, featureLoad
// Initialize DevServerService with event emitter for real-time log streaming
const devServerService = getDevServerService();
devServerService.setEventEmitter(events);
devServerService.initialize(DATA_DIR, events).catch((err) => {
logger.error('Failed to initialize DevServerService:', err);
});
// Initialize Notification Service with event emitter for real-time updates
const notificationService = getNotificationService();

View File

@@ -13,6 +13,27 @@ 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
// ============================================================================
@@ -65,7 +86,14 @@ export async function execGitCommand(
command: 'git',
args,
cwd,
...(env !== undefined ? { env } : {}),
env:
env !== undefined
? {
...gitEnv,
...env,
PATH: [gitEnv.PATH, env.PATH].filter(Boolean).join(pathSeparator),
}
: gitEnv,
...(abortController !== undefined ? { abortController } : {}),
});

View File

@@ -689,6 +689,145 @@ export interface ProviderByModelIdResult {
resolvedModel: string | undefined;
}
/** Result from resolveProviderContext */
export interface ProviderContextResult {
/** The provider configuration */
provider: ClaudeCompatibleProvider | undefined;
/** Credentials for API key resolution */
credentials: Credentials | undefined;
/** The resolved Claude model ID for SDK configuration */
resolvedModel: string | undefined;
/** The original model config from the provider if found */
modelConfig: import('@automaker/types').ProviderModel | undefined;
}
/**
* Checks if a provider is enabled.
* Providers with enabled: undefined are treated as enabled (default state).
* Only explicitly set enabled: false means the provider is disabled.
*/
function isProviderEnabled(provider: ClaudeCompatibleProvider): boolean {
return provider.enabled !== false;
}
/**
* Finds a model config in a provider's models array by ID (case-insensitive).
*/
function findModelInProvider(
provider: ClaudeCompatibleProvider,
modelId: string
): import('@automaker/types').ProviderModel | undefined {
return provider.models?.find(
(m) => m.id === modelId || m.id.toLowerCase() === modelId.toLowerCase()
);
}
/**
* Resolves the provider and Claude-compatible model configuration.
*
* This is the central logic for resolving provider context, supporting:
* 1. Explicit lookup by providerId (most reliable for persistence)
* 2. Fallback lookup by modelId across all enabled providers
* 3. Resolution of mapsToClaudeModel for SDK configuration
*
* @param settingsService - Settings service instance
* @param modelId - The model ID to resolve
* @param providerId - Optional explicit provider ID
* @param logPrefix - Prefix for log messages
* @returns Promise resolving to the provider context
*/
export async function resolveProviderContext(
settingsService: SettingsService,
modelId: string,
providerId?: string,
logPrefix = '[SettingsHelper]'
): Promise<ProviderContextResult> {
try {
const globalSettings = await settingsService.getGlobalSettings();
const credentials = await settingsService.getCredentials();
const providers = globalSettings.claudeCompatibleProviders || [];
logger.debug(
`${logPrefix} Resolving provider context: modelId="${modelId}", providerId="${providerId ?? 'none'}", providers count=${providers.length}`
);
let provider: ClaudeCompatibleProvider | undefined;
let modelConfig: import('@automaker/types').ProviderModel | undefined;
// 1. Try resolving by explicit providerId first (most reliable)
if (providerId) {
provider = providers.find((p) => p.id === providerId);
if (provider) {
if (!isProviderEnabled(provider)) {
logger.warn(
`${logPrefix} Explicitly requested provider "${provider.name}" (${providerId}) is disabled (enabled=${provider.enabled})`
);
} else {
logger.debug(
`${logPrefix} Found provider "${provider.name}" (${providerId}), enabled=${provider.enabled ?? 'undefined (treated as enabled)'}`
);
// Find the model config within this provider to check for mappings
modelConfig = findModelInProvider(provider, modelId);
if (!modelConfig && provider.models && provider.models.length > 0) {
logger.debug(
`${logPrefix} Model "${modelId}" not found in provider "${provider.name}". Available models: ${provider.models.map((m) => m.id).join(', ')}`
);
}
}
} else {
logger.warn(
`${logPrefix} Explicitly requested provider "${providerId}" not found. Available providers: ${providers.map((p) => p.id).join(', ')}`
);
}
}
// 2. Fallback to model-based lookup across all providers if modelConfig not found
// Note: We still search even if provider was found, to get the modelConfig for mapping
if (!modelConfig) {
for (const p of providers) {
if (!isProviderEnabled(p) || p.id === providerId) continue; // Skip disabled or already checked
const config = findModelInProvider(p, modelId);
if (config) {
// Only override provider if we didn't find one by explicit ID
if (!provider) {
provider = p;
}
modelConfig = config;
logger.debug(`${logPrefix} Found model "${modelId}" in provider "${p.name}" (fallback)`);
break;
}
}
}
// 3. Resolve the mapped Claude model if specified
let resolvedModel: string | undefined;
if (modelConfig?.mapsToClaudeModel) {
const { resolveModelString } = await import('@automaker/model-resolver');
resolvedModel = resolveModelString(modelConfig.mapsToClaudeModel);
logger.debug(
`${logPrefix} Model "${modelId}" maps to Claude model "${modelConfig.mapsToClaudeModel}" -> "${resolvedModel}"`
);
}
// Log final result for debugging
logger.debug(
`${logPrefix} Provider context resolved: provider=${provider?.name ?? 'none'}, modelConfig=${modelConfig ? 'found' : 'not found'}, resolvedModel=${resolvedModel ?? modelId}`
);
return { provider, credentials, resolvedModel, modelConfig };
} catch (error) {
logger.error(`${logPrefix} Failed to resolve provider context:`, error);
return {
provider: undefined,
credentials: undefined,
resolvedModel: undefined,
modelConfig: undefined,
};
}
}
/**
* Find a ClaudeCompatibleProvider by one of its model IDs.
* Searches through all enabled providers to find one that contains the specified model.

View File

@@ -188,6 +188,7 @@ export class ClaudeProvider extends BaseProvider {
async *executeQuery(options: ExecuteOptions): AsyncGenerator<ProviderMessage> {
// Validate that model doesn't have a provider prefix
// AgentService should strip prefixes before passing to providers
// Claude doesn't use a provider prefix, so we don't need to specify an expected provider
validateBareModelId(options.model, 'ClaudeProvider');
const {

View File

@@ -739,9 +739,9 @@ export class CodexProvider extends BaseProvider {
}
async *executeQuery(options: ExecuteOptions): AsyncGenerator<ProviderMessage> {
// Validate that model doesn't have a provider prefix
// Validate that model doesn't have a provider prefix (except codex- which should already be stripped)
// AgentService should strip prefixes before passing to providers
validateBareModelId(options.model, 'CodexProvider');
validateBareModelId(options.model, 'CodexProvider', 'codex');
try {
const mcpServers = options.mcpServers ?? {};

View File

@@ -76,13 +76,18 @@ interface SdkToolExecutionStartEvent extends SdkEvent {
};
}
interface SdkToolExecutionEndEvent extends SdkEvent {
type: 'tool.execution_end';
interface SdkToolExecutionCompleteEvent extends SdkEvent {
type: 'tool.execution_complete';
data: {
toolName: string;
toolCallId: string;
result?: string;
error?: string;
success: boolean;
result?: {
content: string;
};
error?: {
message: string;
code?: string;
};
};
}
@@ -94,6 +99,16 @@ interface SdkSessionErrorEvent extends SdkEvent {
};
}
// =============================================================================
// Constants
// =============================================================================
/**
* Prefix for error messages in tool results
* Consistent with GeminiProvider's error formatting
*/
const TOOL_ERROR_PREFIX = '[ERROR]' as const;
// =============================================================================
// Error Codes
// =============================================================================
@@ -357,12 +372,19 @@ export class CopilotProvider extends CliProvider {
};
}
case 'tool.execution_end': {
const toolResultEvent = sdkEvent as SdkToolExecutionEndEvent;
const isError = !!toolResultEvent.data.error;
const content = isError
? `[ERROR] ${toolResultEvent.data.error}`
: toolResultEvent.data.result || '';
/**
* Tool execution completed event
* Handles both successful results and errors from tool executions
* Error messages optionally include error codes for better debugging
*/
case 'tool.execution_complete': {
const toolResultEvent = sdkEvent as SdkToolExecutionCompleteEvent;
const error = toolResultEvent.data.error;
// Format error message with optional code for better debugging
const content = error
? `${TOOL_ERROR_PREFIX} ${error.message}${error.code ? ` (${error.code})` : ''}`
: toolResultEvent.data.result?.content || '';
return {
type: 'assistant',
@@ -628,7 +650,7 @@ export class CopilotProvider extends CliProvider {
sessionComplete = true;
pushEvent(event);
} else {
// Push all other events (tool.execution_start, tool.execution_end, assistant.message, etc.)
// Push all other events (tool.execution_start, tool.execution_complete, assistant.message, etc.)
pushEvent(event);
}
});

View File

@@ -843,9 +843,10 @@ export class CursorProvider extends CliProvider {
async *executeQuery(options: ExecuteOptions): AsyncGenerator<ProviderMessage> {
this.ensureCliDetected();
// Validate that model doesn't have a provider prefix
// Validate that model doesn't have a provider prefix (except cursor- which should already be stripped)
// AgentService should strip prefixes before passing to providers
validateBareModelId(options.model, 'CursorProvider');
// Note: Cursor's Gemini models (e.g., "gemini-3-pro") legitimately start with "gemini-"
validateBareModelId(options.model, 'CursorProvider', 'cursor');
if (!this.cliPath) {
throw this.createError(

View File

@@ -546,8 +546,8 @@ export class GeminiProvider extends CliProvider {
async *executeQuery(options: ExecuteOptions): AsyncGenerator<ProviderMessage> {
this.ensureCliDetected();
// Validate that model doesn't have a provider prefix
validateBareModelId(options.model, 'GeminiProvider');
// Validate that model doesn't have a provider prefix (except gemini- which should already be stripped)
validateBareModelId(options.model, 'GeminiProvider', 'gemini');
if (!this.cliPath) {
throw this.createError(

View File

@@ -0,0 +1,53 @@
/**
* Mock Provider - No-op AI provider for E2E and CI testing
*
* When AUTOMAKER_MOCK_AGENT=true, the server uses this provider instead of
* real backends (Claude, Codex, etc.) so tests never call external APIs.
*/
import type { ExecuteOptions } from '@automaker/types';
import { BaseProvider } from './base-provider.js';
import type { ProviderMessage, InstallationStatus, ModelDefinition } from './types.js';
const MOCK_TEXT = 'Mock agent output for testing.';
export class MockProvider extends BaseProvider {
getName(): string {
return 'mock';
}
async *executeQuery(_options: ExecuteOptions): AsyncGenerator<ProviderMessage> {
yield {
type: 'assistant',
message: {
role: 'assistant',
content: [{ type: 'text', text: MOCK_TEXT }],
},
};
yield {
type: 'result',
subtype: 'success',
};
}
async detectInstallation(): Promise<InstallationStatus> {
return {
installed: true,
method: 'sdk',
hasApiKey: true,
authenticated: true,
};
}
getAvailableModels(): ModelDefinition[] {
return [
{
id: 'mock-model',
name: 'Mock Model',
modelString: 'mock-model',
provider: 'mock',
description: 'Mock model for testing',
},
];
}
}

View File

@@ -67,6 +67,16 @@ export function registerProvider(name: string, registration: ProviderRegistratio
providerRegistry.set(name.toLowerCase(), registration);
}
/** Cached mock provider instance when AUTOMAKER_MOCK_AGENT is set (E2E/CI). */
let mockProviderInstance: BaseProvider | null = null;
function getMockProvider(): BaseProvider {
if (!mockProviderInstance) {
mockProviderInstance = new MockProvider();
}
return mockProviderInstance;
}
export class ProviderFactory {
/**
* Determine which provider to use for a given model
@@ -75,6 +85,9 @@ export class ProviderFactory {
* @returns Provider name (ModelProvider type)
*/
static getProviderNameForModel(model: string): ModelProvider {
if (process.env.AUTOMAKER_MOCK_AGENT === 'true') {
return 'claude' as ModelProvider; // Name only; getProviderForModel returns MockProvider
}
const lowerModel = model.toLowerCase();
// Get all registered providers sorted by priority (descending)
@@ -113,6 +126,9 @@ export class ProviderFactory {
modelId: string,
options: { throwOnDisconnected?: boolean } = {}
): BaseProvider {
if (process.env.AUTOMAKER_MOCK_AGENT === 'true') {
return getMockProvider();
}
const { throwOnDisconnected = true } = options;
const providerName = this.getProviderForModelName(modelId);
@@ -142,6 +158,9 @@ export class ProviderFactory {
* Get the provider name for a given model ID (without creating provider instance)
*/
static getProviderForModelName(modelId: string): string {
if (process.env.AUTOMAKER_MOCK_AGENT === 'true') {
return 'claude';
}
const lowerModel = modelId.toLowerCase();
// Get all registered providers sorted by priority (descending)
@@ -272,6 +291,7 @@ export class ProviderFactory {
// =============================================================================
// Import providers for registration side-effects
import { MockProvider } from './mock-provider.js';
import { ClaudeProvider } from './claude-provider.js';
import { CursorProvider } from './cursor-provider.js';
import { CodexProvider } from './codex-provider.js';

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);

View File

@@ -28,7 +28,7 @@ import * as secureFs from '../../lib/secure-fs.js';
import { validateWorkingDirectory, createAutoModeOptions } from '../../lib/sdk-options.js';
import {
getPromptCustomization,
getProviderByModelId,
resolveProviderContext,
getMCPServersFromSettings,
getDefaultMaxTurnsSetting,
} from '../../lib/settings-helpers.js';
@@ -226,8 +226,7 @@ export class AutoModeServiceFacade {
/**
* Shared agent-run helper used by both PipelineOrchestrator and ExecutionService.
*
* Resolves the model string, looks up the custom provider/credentials via
* getProviderByModelId, then delegates to agentExecutor.execute with the
* Resolves provider/model context, then delegates to agentExecutor.execute with the
* full payload. The opts parameter uses an index-signature union so it
* accepts both the typed ExecutionService opts object and the looser
* Record<string, unknown> used by PipelineOrchestrator without requiring
@@ -266,16 +265,19 @@ export class AutoModeServiceFacade {
| import('@automaker/types').ClaudeCompatibleProvider
| undefined;
let credentials: import('@automaker/types').Credentials | undefined;
let providerResolvedModel: string | undefined;
if (settingsService) {
const providerResult = await getProviderByModelId(
resolvedModel,
const providerId = opts?.providerId as string | undefined;
const result = await resolveProviderContext(
settingsService,
resolvedModel,
providerId,
'[AutoModeFacade]'
);
if (providerResult.provider) {
claudeCompatibleProvider = providerResult.provider;
credentials = providerResult.credentials;
}
claudeCompatibleProvider = result.provider;
credentials = result.credentials;
providerResolvedModel = result.resolvedModel;
}
// Build sdkOptions with proper maxTurns and allowedTools for auto-mode.
@@ -301,7 +303,7 @@ export class AutoModeServiceFacade {
const sdkOpts = createAutoModeOptions({
cwd: workDir,
model: resolvedModel,
model: providerResolvedModel || resolvedModel,
systemPrompt: opts?.systemPrompt,
abortController,
autoLoadClaudeMd,
@@ -313,8 +315,14 @@ export class AutoModeServiceFacade {
| undefined,
});
if (!sdkOpts) {
logger.error(
`[createRunAgentFn] sdkOpts is UNDEFINED! createAutoModeOptions type: ${typeof createAutoModeOptions}`
);
}
logger.info(
`[createRunAgentFn] Feature ${featureId}: model=${resolvedModel}, ` +
`[createRunAgentFn] Feature ${featureId}: model=${resolvedModel} (resolved=${providerResolvedModel || resolvedModel}), ` +
`maxTurns=${sdkOpts.maxTurns}, allowedTools=${(sdkOpts.allowedTools as string[])?.length ?? 'default'}, ` +
`provider=${provider.getName()}`
);

View File

@@ -13,6 +13,8 @@ import path from 'path';
import net from 'net';
import { createLogger } from '@automaker/utils';
import type { EventEmitter } from '../lib/events.js';
import fs from 'fs/promises';
import { constants } from 'fs';
const logger = createLogger('DevServerService');
@@ -110,6 +112,21 @@ export interface DevServerInfo {
urlDetected: boolean;
// Timer for URL detection timeout fallback
urlDetectionTimeout: NodeJS.Timeout | null;
// Custom command used to start the server
customCommand?: string;
}
/**
* Persistable subset of DevServerInfo for survival across server restarts
*/
interface PersistedDevServerInfo {
worktreePath: string;
allocatedPort: number;
port: number;
url: string;
startedAt: string;
urlDetected: boolean;
customCommand?: string;
}
// Port allocation starts at 3001 to avoid conflicts with common dev ports
@@ -121,8 +138,20 @@ const LIVERELOAD_PORTS = [35729, 35730, 35731] as const;
class DevServerService {
private runningServers: Map<string, DevServerInfo> = new Map();
private startingServers: Set<string> = new Set();
private allocatedPorts: Set<number> = new Set();
private emitter: EventEmitter | null = null;
private dataDir: string | null = null;
private saveQueue: Promise<void> = Promise.resolve();
/**
* Initialize the service with data directory for persistence
*/
async initialize(dataDir: string, emitter: EventEmitter): Promise<void> {
this.dataDir = dataDir;
this.emitter = emitter;
await this.loadState();
}
/**
* Set the event emitter for streaming log events
@@ -132,6 +161,131 @@ class DevServerService {
this.emitter = emitter;
}
/**
* Save the current state of running servers to disk
*/
private async saveState(): Promise<void> {
if (!this.dataDir) return;
// Queue the save operation to prevent concurrent writes
this.saveQueue = this.saveQueue
.then(async () => {
if (!this.dataDir) return;
try {
const statePath = path.join(this.dataDir, 'dev-servers.json');
const persistedInfo: PersistedDevServerInfo[] = Array.from(
this.runningServers.values()
).map((s) => ({
worktreePath: s.worktreePath,
allocatedPort: s.allocatedPort,
port: s.port,
url: s.url,
startedAt: s.startedAt.toISOString(),
urlDetected: s.urlDetected,
customCommand: s.customCommand,
}));
await fs.writeFile(statePath, JSON.stringify(persistedInfo, null, 2));
logger.debug(`Saved dev server state to ${statePath}`);
} catch (error) {
logger.error('Failed to save dev server state:', error);
}
})
.catch((error) => {
logger.error('Error in save queue:', error);
});
return this.saveQueue;
}
/**
* Load the state of running servers from disk
*/
private async loadState(): Promise<void> {
if (!this.dataDir) return;
try {
const statePath = path.join(this.dataDir, 'dev-servers.json');
try {
await fs.access(statePath, constants.F_OK);
} catch {
// File doesn't exist, which is fine
return;
}
const content = await fs.readFile(statePath, 'utf-8');
const rawParsed: unknown = JSON.parse(content);
if (!Array.isArray(rawParsed)) {
logger.warn('Dev server state file is not an array, skipping load');
return;
}
const persistedInfo: PersistedDevServerInfo[] = rawParsed.filter((entry: unknown) => {
if (entry === null || typeof entry !== 'object') {
logger.warn('Dropping invalid dev server entry (not an object):', entry);
return false;
}
const e = entry as Record<string, unknown>;
const valid =
typeof e.worktreePath === 'string' &&
e.worktreePath.length > 0 &&
typeof e.allocatedPort === 'number' &&
Number.isInteger(e.allocatedPort) &&
e.allocatedPort >= 1 &&
e.allocatedPort <= 65535 &&
typeof e.port === 'number' &&
Number.isInteger(e.port) &&
e.port >= 1 &&
e.port <= 65535 &&
typeof e.url === 'string' &&
typeof e.startedAt === 'string' &&
typeof e.urlDetected === 'boolean' &&
(e.customCommand === undefined || typeof e.customCommand === 'string');
if (!valid) {
logger.warn('Dropping malformed dev server entry:', e);
}
return valid;
}) as PersistedDevServerInfo[];
logger.info(`Loading ${persistedInfo.length} dev servers from state`);
for (const info of persistedInfo) {
// Check if the process is still running on the port
// Since we can't reliably re-attach to the process for output,
// we'll just check if the port is in use.
const portInUse = !(await this.isPortAvailable(info.port));
if (portInUse) {
logger.info(`Re-attached to dev server on port ${info.port} for ${info.worktreePath}`);
const serverInfo: DevServerInfo = {
...info,
startedAt: new Date(info.startedAt),
process: null, // Process object is lost, but we know it's running
scrollbackBuffer: '',
outputBuffer: '',
flushTimeout: null,
stopping: false,
urlDetectionTimeout: null,
};
this.runningServers.set(info.worktreePath, serverInfo);
this.allocatedPorts.add(info.allocatedPort);
} else {
logger.info(
`Dev server on port ${info.port} for ${info.worktreePath} is no longer running`
);
}
}
// Cleanup stale entries from the file if any
if (this.runningServers.size !== persistedInfo.length) {
await this.saveState();
}
} catch (error) {
logger.error('Failed to load dev server state:', error);
}
}
/**
* Prune a stale server entry whose process has exited without cleanup.
* Clears any pending timers, removes the port from allocatedPorts, deletes
@@ -148,6 +302,10 @@ class DevServerService {
// been mutated by detectUrlFromOutput to reflect the actual detected port.
this.allocatedPorts.delete(server.allocatedPort);
this.runningServers.delete(worktreePath);
// Persist state change
this.saveState().catch((err) => logger.error('Failed to save state in pruneStaleServer:', err));
if (this.emitter) {
this.emitter.emit('dev-server:stopped', {
worktreePath,
@@ -249,7 +407,7 @@ class DevServerService {
* - PHP: "Development Server (http://localhost:8000) started"
* - Generic: Any localhost URL with a port
*/
private detectUrlFromOutput(server: DevServerInfo, content: string): void {
private async detectUrlFromOutput(server: DevServerInfo, content: string): Promise<void> {
// Skip if URL already detected
if (server.urlDetected) {
return;
@@ -304,6 +462,11 @@ class DevServerService {
logger.info(`Detected server URL via ${description}: ${detectedUrl}`);
// Persist state change
await this.saveState().catch((err) =>
logger.error('Failed to save state in detectUrlFromOutput:', err)
);
// Emit URL update event
if (this.emitter) {
this.emitter.emit('dev-server:url-detected', {
@@ -346,6 +509,11 @@ class DevServerService {
logger.info(`Detected server port via ${description}: ${detectedPort}${detectedUrl}`);
// Persist state change
await this.saveState().catch((err) =>
logger.error('Failed to save state in detectUrlFromOutput Phase 2:', err)
);
// Emit URL update event
if (this.emitter) {
this.emitter.emit('dev-server:url-detected', {
@@ -365,7 +533,7 @@ class DevServerService {
* Handle incoming stdout/stderr data from dev server process
* Buffers data for scrollback replay and schedules throttled emission
*/
private handleProcessOutput(server: DevServerInfo, data: Buffer): void {
private async handleProcessOutput(server: DevServerInfo, data: Buffer): Promise<void> {
// Skip output if server is stopping
if (server.stopping) {
return;
@@ -374,7 +542,7 @@ class DevServerService {
const content = data.toString();
// Try to detect actual server URL from output
this.detectUrlFromOutput(server, content);
await this.detectUrlFromOutput(server, content);
// Append to scrollback buffer for replay on reconnect
this.appendToScrollback(server, content);
@@ -594,261 +762,305 @@ class DevServerService {
};
error?: string;
}> {
// Check if already running
if (this.runningServers.has(worktreePath)) {
const existing = this.runningServers.get(worktreePath)!;
return {
success: true,
result: {
worktreePath: existing.worktreePath,
port: existing.port,
url: existing.url,
message: `Dev server already running on port ${existing.port}`,
},
};
}
// Verify the worktree exists
if (!(await this.fileExists(worktreePath))) {
// Check if already running or starting
if (this.runningServers.has(worktreePath) || this.startingServers.has(worktreePath)) {
const existing = this.runningServers.get(worktreePath);
if (existing) {
return {
success: true,
result: {
worktreePath: existing.worktreePath,
port: existing.port,
url: existing.url,
message: `Dev server already running on port ${existing.port}`,
},
};
}
return {
success: false,
error: `Worktree path does not exist: ${worktreePath}`,
error: 'Dev server is already starting',
};
}
// Determine the dev command to use
let devCommand: { cmd: string; args: string[] };
this.startingServers.add(worktreePath);
// Normalize custom command: trim whitespace and treat empty strings as undefined
const normalizedCustomCommand = customCommand?.trim();
if (normalizedCustomCommand) {
// Use the provided custom command
devCommand = this.parseCustomCommand(normalizedCustomCommand);
if (!devCommand.cmd) {
return {
success: false,
error: 'Invalid custom command: command cannot be empty',
};
}
logger.debug(`Using custom command: ${normalizedCustomCommand}`);
} else {
// Check for package.json when auto-detecting
const packageJsonPath = path.join(worktreePath, 'package.json');
if (!(await this.fileExists(packageJsonPath))) {
return {
success: false,
error: `No package.json found in: ${worktreePath}`,
};
}
// Get dev command from package manager detection
const detectedCommand = await this.getDevCommand(worktreePath);
if (!detectedCommand) {
return {
success: false,
error: `Could not determine dev command for: ${worktreePath}`,
};
}
devCommand = detectedCommand;
}
// Find available port
let port: number;
try {
port = await this.findAvailablePort();
} catch (error) {
return {
success: false,
error: error instanceof Error ? error.message : 'Port allocation failed',
};
}
// Reserve the port (port was already force-killed in findAvailablePort)
this.allocatedPorts.add(port);
// Also kill common related ports (livereload, etc.)
// Some dev servers use fixed ports for HMR/livereload regardless of main port
for (const relatedPort of LIVERELOAD_PORTS) {
this.killProcessOnPort(relatedPort);
}
// Small delay to ensure related ports are freed
await new Promise((resolve) => setTimeout(resolve, 100));
logger.info(`Starting dev server on port ${port}`);
logger.debug(`Working directory (cwd): ${worktreePath}`);
logger.debug(`Command: ${devCommand.cmd} ${devCommand.args.join(' ')} with PORT=${port}`);
// Spawn the dev process with PORT environment variable
// FORCE_COLOR enables colored output even when not running in a TTY
const env = {
...process.env,
PORT: String(port),
FORCE_COLOR: '1',
// Some tools use these additional env vars for color detection
COLORTERM: 'truecolor',
TERM: 'xterm-256color',
};
const devProcess = spawn(devCommand.cmd, devCommand.args, {
cwd: worktreePath,
env,
stdio: ['ignore', 'pipe', 'pipe'],
detached: false,
});
// Track if process failed early using object to work around TypeScript narrowing
const status = { error: null as string | null, exited: false };
// Create server info early so we can reference it in handlers
// We'll add it to runningServers after verifying the process started successfully
const hostname = process.env.HOSTNAME || 'localhost';
const serverInfo: DevServerInfo = {
worktreePath,
allocatedPort: port, // Immutable: records which port we reserved; never changed after this point
port,
url: `http://${hostname}:${port}`, // Initial URL, may be updated by detectUrlFromOutput
process: devProcess,
startedAt: new Date(),
scrollbackBuffer: '',
outputBuffer: '',
flushTimeout: null,
stopping: false,
urlDetected: false, // Will be set to true when actual URL is detected from output
urlDetectionTimeout: null, // Will be set after server starts successfully
};
// Capture stdout with buffer management and event emission
if (devProcess.stdout) {
devProcess.stdout.on('data', (data: Buffer) => {
this.handleProcessOutput(serverInfo, data);
});
}
// Capture stderr with buffer management and event emission
if (devProcess.stderr) {
devProcess.stderr.on('data', (data: Buffer) => {
this.handleProcessOutput(serverInfo, data);
});
}
// Helper to clean up resources and emit stop event
const cleanupAndEmitStop = (exitCode: number | null, errorMessage?: string) => {
if (serverInfo.flushTimeout) {
clearTimeout(serverInfo.flushTimeout);
serverInfo.flushTimeout = null;
// Verify the worktree exists
if (!(await this.fileExists(worktreePath))) {
return {
success: false,
error: `Worktree path does not exist: ${worktreePath}`,
};
}
// Clear URL detection timeout to prevent stale fallback emission
if (serverInfo.urlDetectionTimeout) {
clearTimeout(serverInfo.urlDetectionTimeout);
serverInfo.urlDetectionTimeout = null;
// Determine the dev command to use
let devCommand: { cmd: string; args: string[] };
// Normalize custom command: trim whitespace and treat empty strings as undefined
const normalizedCustomCommand = customCommand?.trim();
if (normalizedCustomCommand) {
// Use the provided custom command
devCommand = this.parseCustomCommand(normalizedCustomCommand);
if (!devCommand.cmd) {
return {
success: false,
error: 'Invalid custom command: command cannot be empty',
};
}
logger.debug(`Using custom command: ${normalizedCustomCommand}`);
} else {
// Check for package.json when auto-detecting
const packageJsonPath = path.join(worktreePath, 'package.json');
if (!(await this.fileExists(packageJsonPath))) {
return {
success: false,
error: `No package.json found in: ${worktreePath}`,
};
}
// Get dev command from package manager detection
const detectedCommand = await this.getDevCommand(worktreePath);
if (!detectedCommand) {
return {
success: false,
error: `Could not determine dev command for: ${worktreePath}`,
};
}
devCommand = detectedCommand;
}
// Emit stopped event (only if not already stopping - prevents duplicate events)
if (this.emitter && !serverInfo.stopping) {
this.emitter.emit('dev-server:stopped', {
// Find available port
let port: number;
try {
port = await this.findAvailablePort();
} catch (error) {
return {
success: false,
error: error instanceof Error ? error.message : 'Port allocation failed',
};
}
// Reserve the port (port was already force-killed in findAvailablePort)
this.allocatedPorts.add(port);
// Also kill common related ports (livereload, etc.)
// Some dev servers use fixed ports for HMR/livereload regardless of main port
for (const relatedPort of LIVERELOAD_PORTS) {
this.killProcessOnPort(relatedPort);
}
// Small delay to ensure related ports are freed
await new Promise((resolve) => setTimeout(resolve, 100));
logger.info(`Starting dev server on port ${port}`);
logger.debug(`Working directory (cwd): ${worktreePath}`);
logger.debug(`Command: ${devCommand.cmd} ${devCommand.args.join(' ')} with PORT=${port}`);
// Emit starting only after preflight checks pass to avoid dangling starting state.
if (this.emitter) {
this.emitter.emit('dev-server:starting', {
worktreePath,
port: serverInfo.port, // Use the detected port (may differ from allocated port if detectUrlFromOutput updated it)
exitCode,
error: errorMessage,
timestamp: new Date().toISOString(),
});
}
this.allocatedPorts.delete(serverInfo.allocatedPort);
this.runningServers.delete(worktreePath);
};
devProcess.on('error', (error) => {
logger.error(`Process error:`, error);
status.error = error.message;
cleanupAndEmitStop(null, error.message);
});
devProcess.on('exit', (code) => {
logger.info(`Process for ${worktreePath} exited with code ${code}`);
status.exited = true;
cleanupAndEmitStop(code);
});
// Wait a moment to see if the process fails immediately
await new Promise((resolve) => setTimeout(resolve, 500));
if (status.error) {
return {
success: false,
error: `Failed to start dev server: ${status.error}`,
// Spawn the dev process with PORT environment variable
// FORCE_COLOR enables colored output even when not running in a TTY
const env = {
...process.env,
PORT: String(port),
FORCE_COLOR: '1',
// Some tools use these additional env vars for color detection
COLORTERM: 'truecolor',
TERM: 'xterm-256color',
};
}
if (status.exited) {
return {
success: false,
error: `Dev server process exited immediately. Check server logs for details.`,
};
}
// Server started successfully - add to running servers map
this.runningServers.set(worktreePath, serverInfo);
// Emit started event for WebSocket subscribers
if (this.emitter) {
this.emitter.emit('dev-server:started', {
worktreePath,
port,
url: serverInfo.url,
timestamp: new Date().toISOString(),
const devProcess = spawn(devCommand.cmd, devCommand.args, {
cwd: worktreePath,
env,
stdio: ['ignore', 'pipe', 'pipe'],
detached: false,
});
}
// Set up URL detection timeout fallback.
// If URL detection hasn't succeeded after URL_DETECTION_TIMEOUT_MS, check if
// the allocated port is actually in use (server probably started successfully)
// and emit a url-detected event with the allocated port as fallback.
// Also re-scan the scrollback buffer in case the URL was printed before
// our patterns could match (e.g., it was split across multiple data chunks).
serverInfo.urlDetectionTimeout = setTimeout(() => {
serverInfo.urlDetectionTimeout = null;
// Track if process failed early using object to work around TypeScript narrowing
const status = { error: null as string | null, exited: false };
// Only run fallback if server is still running and URL wasn't detected
if (serverInfo.stopping || serverInfo.urlDetected || !this.runningServers.has(worktreePath)) {
return;
// Create server info early so we can reference it in handlers
// We'll add it to runningServers after verifying the process started successfully
const fallbackHost = 'localhost';
const serverInfo: DevServerInfo = {
worktreePath,
allocatedPort: port, // Immutable: records which port we reserved; never changed after this point
port,
url: `http://${fallbackHost}:${port}`, // Initial URL, may be updated by detectUrlFromOutput
process: devProcess,
startedAt: new Date(),
scrollbackBuffer: '',
outputBuffer: '',
flushTimeout: null,
stopping: false,
urlDetected: false, // Will be set to true when actual URL is detected from output
urlDetectionTimeout: null, // Will be set after server starts successfully
customCommand: normalizedCustomCommand,
};
// Capture stdout with buffer management and event emission
if (devProcess.stdout) {
devProcess.stdout.on('data', (data: Buffer) => {
this.handleProcessOutput(serverInfo, data).catch((error: unknown) => {
logger.error('Failed to handle dev server stdout output:', error);
});
});
}
// Re-scan the entire scrollback buffer for URL patterns
// This catches cases where the URL was split across multiple output chunks
logger.info(`URL detection timeout for ${worktreePath}, re-scanning scrollback buffer`);
this.detectUrlFromOutput(serverInfo, serverInfo.scrollbackBuffer);
// Capture stderr with buffer management and event emission
if (devProcess.stderr) {
devProcess.stderr.on('data', (data: Buffer) => {
this.handleProcessOutput(serverInfo, data).catch((error: unknown) => {
logger.error('Failed to handle dev server stderr output:', error);
});
});
}
// If still not detected after full rescan, use the allocated port as fallback
if (!serverInfo.urlDetected) {
logger.info(`URL detection fallback: using allocated port ${port} for ${worktreePath}`);
const fallbackUrl = `http://${hostname}:${port}`;
serverInfo.url = fallbackUrl;
serverInfo.urlDetected = true;
// Helper to clean up resources and emit stop event
const cleanupAndEmitStop = (exitCode: number | null, errorMessage?: string) => {
if (serverInfo.flushTimeout) {
clearTimeout(serverInfo.flushTimeout);
serverInfo.flushTimeout = null;
}
if (this.emitter) {
this.emitter.emit('dev-server:url-detected', {
// Clear URL detection timeout to prevent stale fallback emission
if (serverInfo.urlDetectionTimeout) {
clearTimeout(serverInfo.urlDetectionTimeout);
serverInfo.urlDetectionTimeout = null;
}
// Emit stopped event (only if not already stopping - prevents duplicate events)
if (this.emitter && !serverInfo.stopping) {
this.emitter.emit('dev-server:stopped', {
worktreePath,
url: fallbackUrl,
port,
port: serverInfo.port, // Use the detected port (may differ from allocated port if detectUrlFromOutput updated it)
exitCode,
error: errorMessage,
timestamp: new Date().toISOString(),
});
}
}
}, URL_DETECTION_TIMEOUT_MS);
return {
success: true,
result: {
worktreePath,
port,
url: `http://${hostname}:${port}`,
message: `Dev server started on port ${port}`,
},
};
this.allocatedPorts.delete(serverInfo.allocatedPort);
this.runningServers.delete(worktreePath);
// Persist state change
this.saveState().catch((err) => logger.error('Failed to save state in cleanup:', err));
};
devProcess.on('error', (error) => {
logger.error(`Process error:`, error);
status.error = error.message;
cleanupAndEmitStop(null, error.message);
});
devProcess.on('exit', (code) => {
logger.info(`Process for ${worktreePath} exited with code ${code}`);
status.exited = true;
cleanupAndEmitStop(code);
});
// Wait a moment to see if the process fails immediately
await new Promise((resolve) => setTimeout(resolve, 500));
if (status.error) {
return {
success: false,
error: `Failed to start dev server: ${status.error}`,
};
}
if (status.exited) {
return {
success: false,
error: `Dev server process exited immediately. Check server logs for details.`,
};
}
// Server started successfully - add to running servers map
this.runningServers.set(worktreePath, serverInfo);
// Persist state change
await this.saveState().catch((err) =>
logger.error('Failed to save state in startDevServer:', err)
);
// Emit started event for WebSocket subscribers
if (this.emitter) {
this.emitter.emit('dev-server:started', {
worktreePath,
port,
url: serverInfo.url,
timestamp: new Date().toISOString(),
});
}
// Set up URL detection timeout fallback.
// If URL detection hasn't succeeded after URL_DETECTION_TIMEOUT_MS, check if
// the allocated port is actually in use (server probably started successfully)
// and emit a url-detected event with the allocated port as fallback.
// Also re-scan the scrollback buffer in case the URL was printed before
// our patterns could match (e.g., it was split across multiple data chunks).
serverInfo.urlDetectionTimeout = setTimeout(async () => {
serverInfo.urlDetectionTimeout = null;
// Only run fallback if server is still running and URL wasn't detected
if (
serverInfo.stopping ||
serverInfo.urlDetected ||
!this.runningServers.has(worktreePath)
) {
return;
}
// Re-scan the entire scrollback buffer for URL patterns
// This catches cases where the URL was split across multiple output chunks
logger.info(`URL detection timeout for ${worktreePath}, re-scanning scrollback buffer`);
await this.detectUrlFromOutput(serverInfo, serverInfo.scrollbackBuffer).catch((err) =>
logger.error('Failed to re-scan scrollback buffer:', err)
);
// If still not detected after full rescan, use the allocated port as fallback
if (!serverInfo.urlDetected) {
logger.info(`URL detection fallback: using allocated port ${port} for ${worktreePath}`);
const fallbackUrl = `http://${fallbackHost}:${port}`;
serverInfo.url = fallbackUrl;
serverInfo.urlDetected = true;
// Persist state change
await this.saveState().catch((err) =>
logger.error('Failed to save state in URL detection fallback:', err)
);
if (this.emitter) {
this.emitter.emit('dev-server:url-detected', {
worktreePath: serverInfo.worktreePath,
url: fallbackUrl,
port,
timestamp: new Date().toISOString(),
});
}
}
}, URL_DETECTION_TIMEOUT_MS);
return {
success: true,
result: {
worktreePath: serverInfo.worktreePath,
port: serverInfo.port,
url: serverInfo.url,
message: `Dev server started on port ${port}`,
},
};
} finally {
this.startingServers.delete(worktreePath);
}
}
/**
@@ -904,9 +1116,11 @@ class DevServerService {
});
}
// Kill the process
// Kill the process; persisted/re-attached entries may not have a process handle.
if (server.process && !server.process.killed) {
server.process.kill('SIGTERM');
} else {
this.killProcessOnPort(server.port);
}
// Free the originally-reserved port slot (allocatedPort is immutable and always
@@ -915,6 +1129,11 @@ class DevServerService {
this.allocatedPorts.delete(server.allocatedPort);
this.runningServers.delete(worktreePath);
// Persist state change
await this.saveState().catch((err) =>
logger.error('Failed to save state in stopDevServer:', err)
);
return {
success: true,
result: {

View File

@@ -214,7 +214,12 @@ ${feature.spec}
const branchName = feature.branchName;
if (!worktreePath && useWorktrees && branchName) {
worktreePath = await this.worktreeResolver.findWorktreeForBranch(projectPath, branchName);
if (worktreePath) logger.info(`Using worktree for branch "${branchName}": ${worktreePath}`);
if (!worktreePath) {
throw new Error(
`Worktree enabled but no worktree found for feature branch "${branchName}".`
);
}
logger.info(`Using worktree for branch "${branchName}": ${worktreePath}`);
}
const workDir = worktreePath ? path.resolve(worktreePath) : path.resolve(projectPath);
validateWorkingDirectory(workDir);
@@ -304,6 +309,7 @@ ${feature.spec}
useClaudeCodeSystemPrompt,
thinkingLevel: feature.thinkingLevel,
reasoningEffort: feature.reasoningEffort,
providerId: feature.providerId,
branchName: feature.branchName ?? null,
}
);
@@ -370,6 +376,7 @@ Please continue from where you left off and complete all remaining tasks. Use th
useClaudeCodeSystemPrompt,
thinkingLevel: feature.thinkingLevel,
reasoningEffort: feature.reasoningEffort,
providerId: feature.providerId,
branchName: feature.branchName ?? null,
}
);

View File

@@ -34,6 +34,7 @@ export type RunAgentFn = (
useClaudeCodeSystemPrompt?: boolean;
thinkingLevel?: ThinkingLevel;
reasoningEffort?: ReasoningEffort;
providerId?: string;
branchName?: string | null;
}
) => Promise<void>;

View File

@@ -135,6 +135,7 @@ export class PipelineOrchestrator {
thinkingLevel: feature.thinkingLevel,
reasoningEffort: feature.reasoningEffort,
status: currentStatus,
providerId: feature.providerId,
}
);
try {
@@ -503,8 +504,10 @@ export class PipelineOrchestrator {
requirePlanApproval: false,
useClaudeCodeSystemPrompt: context.useClaudeCodeSystemPrompt,
autoLoadClaudeMd: context.autoLoadClaudeMd,
thinkingLevel: context.feature.thinkingLevel,
reasoningEffort: context.feature.reasoningEffort,
status: context.feature.status,
providerId: context.feature.providerId,
}
);
}

View File

@@ -28,6 +28,8 @@ const logger = createLogger('PullService');
export interface PullOptions {
/** Remote name to pull from (defaults to 'origin') */
remote?: string;
/** Specific remote branch to pull (e.g. 'main'). When provided, overrides the tracking branch and fetches this branch from the remote. */
remoteBranch?: string;
/** When true, automatically stash local changes before pulling and reapply after */
stashIfNeeded?: boolean;
}
@@ -243,6 +245,7 @@ export async function performPull(
): Promise<PullResult> {
const targetRemote = options?.remote || 'origin';
const stashIfNeeded = options?.stashIfNeeded ?? false;
const targetRemoteBranch = options?.remoteBranch;
// 1. Get current branch name
let branchName: string;
@@ -313,24 +316,34 @@ export async function performPull(
}
// 7. Verify upstream tracking or remote branch exists
const upstreamStatus = await hasUpstreamOrRemoteBranch(worktreePath, branchName, targetRemote);
if (upstreamStatus === 'none') {
let stashRecoveryFailed = false;
if (didStash) {
const stashPopped = await tryPopStash(worktreePath);
stashRecoveryFailed = !stashPopped;
// Skip this check when a specific remote branch is provided - we always use
// explicit 'git pull <remote> <branch>' args in that case.
let upstreamStatus: UpstreamStatus = 'tracking';
if (!targetRemoteBranch) {
upstreamStatus = await hasUpstreamOrRemoteBranch(worktreePath, branchName, targetRemote);
if (upstreamStatus === 'none') {
let stashRecoveryFailed = false;
if (didStash) {
const stashPopped = await tryPopStash(worktreePath);
stashRecoveryFailed = !stashPopped;
}
return {
success: false,
error: `Branch '${branchName}' has no upstream branch on remote '${targetRemote}'. Push it first or set upstream with: git branch --set-upstream-to=${targetRemote}/${branchName}${stashRecoveryFailed ? ' Local changes remain stashed and need manual recovery (run: git stash pop).' : ''}`,
stashRecoveryFailed: stashRecoveryFailed ? stashRecoveryFailed : undefined,
};
}
return {
success: false,
error: `Branch '${branchName}' has no upstream branch on remote '${targetRemote}'. Push it first or set upstream with: git branch --set-upstream-to=${targetRemote}/${branchName}${stashRecoveryFailed ? ' Local changes remain stashed and need manual recovery (run: git stash pop).' : ''}`,
stashRecoveryFailed: stashRecoveryFailed ? stashRecoveryFailed : undefined,
};
}
// 8. Pull latest changes
// When a specific remote branch is requested, always use explicit remote + branch args.
// When the branch has a configured upstream tracking ref, let Git use it automatically.
// When only the remote branch exists (no tracking ref), explicitly specify remote and branch.
const pullArgs = upstreamStatus === 'tracking' ? ['pull'] : ['pull', targetRemote, branchName];
const pullArgs = targetRemoteBranch
? ['pull', targetRemote, targetRemoteBranch]
: upstreamStatus === 'tracking'
? ['pull']
: ['pull', targetRemote, branchName];
let pullConflict = false;
let pullConflictFiles: string[] = [];

View File

@@ -39,6 +39,18 @@ export interface WorktreeInfo {
* 3. Listing all worktrees with normalized paths
*/
export class WorktreeResolver {
private normalizeBranchName(branchName: string | null | undefined): string | null {
if (!branchName) return null;
let normalized = branchName.trim();
if (!normalized) return null;
normalized = normalized.replace(/^refs\/heads\//, '');
normalized = normalized.replace(/^refs\/remotes\/[^/]+\//, '');
normalized = normalized.replace(/^(origin|upstream)\//, '');
return normalized || null;
}
/**
* Get the current branch name for a git repository
*
@@ -64,6 +76,9 @@ export class WorktreeResolver {
*/
async findWorktreeForBranch(projectPath: string, branchName: string): Promise<string | null> {
try {
const normalizedTargetBranch = this.normalizeBranchName(branchName);
if (!normalizedTargetBranch) return null;
const { stdout } = await execAsync('git worktree list --porcelain', {
cwd: projectPath,
});
@@ -76,10 +91,10 @@ export class WorktreeResolver {
if (line.startsWith('worktree ')) {
currentPath = line.slice(9);
} else if (line.startsWith('branch ')) {
currentBranch = line.slice(7).replace('refs/heads/', '');
currentBranch = this.normalizeBranchName(line.slice(7));
} else if (line === '' && currentPath && currentBranch) {
// End of a worktree entry
if (currentBranch === branchName) {
if (currentBranch === normalizedTargetBranch) {
// Resolve to absolute path - git may return relative paths
// On Windows, this is critical for cwd to work correctly
// On all platforms, absolute paths ensure consistent behavior
@@ -91,7 +106,7 @@ export class WorktreeResolver {
}
// Check the last entry (if file doesn't end with newline)
if (currentPath && currentBranch && currentBranch === branchName) {
if (currentPath && currentBranch && currentBranch === normalizedTargetBranch) {
return this.resolvePath(projectPath, currentPath);
}
@@ -123,7 +138,7 @@ export class WorktreeResolver {
if (line.startsWith('worktree ')) {
currentPath = line.slice(9);
} else if (line.startsWith('branch ')) {
currentBranch = line.slice(7).replace('refs/heads/', '');
currentBranch = this.normalizeBranchName(line.slice(7));
} else if (line.startsWith('detached')) {
// Detached HEAD - branch is null
currentBranch = null;