mirror of
https://github.com/AutoMaker-Org/automaker.git
synced 2026-03-26 00:53:08 +00:00
Compare commits
11 Commits
feature/pu
...
2f071a1ba3
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
2f071a1ba3 | ||
|
|
1d732916f1 | ||
|
|
629fd24d9f | ||
|
|
72cb942788 | ||
|
|
91bff21d58 | ||
|
|
dfa719079f | ||
|
|
28becb177b | ||
|
|
f785f1204b | ||
|
|
f3edfbf24e | ||
|
|
3ddf26f666 | ||
|
|
c81ea768a7 |
@@ -209,9 +209,10 @@ COPY libs ./libs
|
||||
COPY apps/ui ./apps/ui
|
||||
|
||||
# Build packages in dependency order, then build UI
|
||||
# VITE_SERVER_URL tells the UI where to find the API server
|
||||
# Use ARG to allow overriding at build time: --build-arg VITE_SERVER_URL=http://api.example.com
|
||||
ARG VITE_SERVER_URL=http://localhost:3008
|
||||
# When VITE_SERVER_URL is empty, the UI uses relative URLs (e.g., /api/...) which nginx proxies
|
||||
# to the server container. This avoids CORS issues entirely in Docker Compose setups.
|
||||
# Override at build time if needed: --build-arg VITE_SERVER_URL=http://api.example.com
|
||||
ARG VITE_SERVER_URL=
|
||||
ENV VITE_SKIP_ELECTRON=true
|
||||
ENV VITE_SERVER_URL=${VITE_SERVER_URL}
|
||||
RUN npm run build:packages && npm run build --workspace=apps/ui
|
||||
|
||||
@@ -267,6 +267,26 @@ app.use(
|
||||
// CORS configuration
|
||||
// When using credentials (cookies), origin cannot be '*'
|
||||
// We dynamically allow the requesting origin for local development
|
||||
|
||||
// Check if origin is a local/private network address
|
||||
function isLocalOrigin(origin: string): boolean {
|
||||
try {
|
||||
const url = new URL(origin);
|
||||
const hostname = url.hostname;
|
||||
return (
|
||||
hostname === 'localhost' ||
|
||||
hostname === '127.0.0.1' ||
|
||||
hostname === '[::1]' ||
|
||||
hostname === '0.0.0.0' ||
|
||||
hostname.startsWith('192.168.') ||
|
||||
hostname.startsWith('10.') ||
|
||||
/^172\.(1[6-9]|2[0-9]|3[0-1])\./.test(hostname)
|
||||
);
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
app.use(
|
||||
cors({
|
||||
origin: (origin, callback) => {
|
||||
@@ -277,35 +297,25 @@ app.use(
|
||||
}
|
||||
|
||||
// If CORS_ORIGIN is set, use it (can be comma-separated list)
|
||||
const allowedOrigins = process.env.CORS_ORIGIN?.split(',').map((o) => o.trim());
|
||||
if (allowedOrigins && allowedOrigins.length > 0 && allowedOrigins[0] !== '*') {
|
||||
if (allowedOrigins.includes(origin)) {
|
||||
callback(null, origin);
|
||||
} else {
|
||||
callback(new Error('Not allowed by CORS'));
|
||||
const allowedOrigins = process.env.CORS_ORIGIN?.split(',')
|
||||
.map((o) => o.trim())
|
||||
.filter(Boolean);
|
||||
if (allowedOrigins && allowedOrigins.length > 0) {
|
||||
if (allowedOrigins.includes('*')) {
|
||||
callback(null, true);
|
||||
return;
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
// For local development, allow all localhost/loopback origins (any port)
|
||||
try {
|
||||
const url = new URL(origin);
|
||||
const hostname = url.hostname;
|
||||
|
||||
if (
|
||||
hostname === 'localhost' ||
|
||||
hostname === '127.0.0.1' ||
|
||||
hostname === '::1' ||
|
||||
hostname === '0.0.0.0' ||
|
||||
hostname.startsWith('192.168.') ||
|
||||
hostname.startsWith('10.') ||
|
||||
hostname.startsWith('172.')
|
||||
) {
|
||||
if (allowedOrigins.includes(origin)) {
|
||||
callback(null, origin);
|
||||
return;
|
||||
}
|
||||
} catch {
|
||||
// Ignore URL parsing errors
|
||||
// Fall through to local network check below
|
||||
}
|
||||
|
||||
// Allow all localhost/loopback/private network origins (any port)
|
||||
if (isLocalOrigin(origin)) {
|
||||
callback(null, origin);
|
||||
return;
|
||||
}
|
||||
|
||||
// Reject other origins by default for security
|
||||
|
||||
37
apps/server/src/lib/exec-utils.ts
Normal file
37
apps/server/src/lib/exec-utils.ts
Normal file
@@ -0,0 +1,37 @@
|
||||
/**
|
||||
* Shared execution utilities
|
||||
*
|
||||
* Common helpers for spawning child processes with the correct environment.
|
||||
* Used by both route handlers and service layers.
|
||||
*/
|
||||
|
||||
import { createLogger } from '@automaker/utils';
|
||||
|
||||
const logger = createLogger('ExecUtils');
|
||||
|
||||
// Extended PATH to include common tool installation locations
|
||||
export const extendedPath = [
|
||||
process.env.PATH,
|
||||
'/opt/homebrew/bin',
|
||||
'/usr/local/bin',
|
||||
'/home/linuxbrew/.linuxbrew/bin',
|
||||
`${process.env.HOME}/.local/bin`,
|
||||
]
|
||||
.filter(Boolean)
|
||||
.join(':');
|
||||
|
||||
export const execEnv = {
|
||||
...process.env,
|
||||
PATH: extendedPath,
|
||||
};
|
||||
|
||||
export function getErrorMessage(error: unknown): string {
|
||||
if (error instanceof Error) {
|
||||
return error.message;
|
||||
}
|
||||
return String(error);
|
||||
}
|
||||
|
||||
export function logError(error: unknown, context: string): void {
|
||||
logger.error(`${context}:`, error);
|
||||
}
|
||||
@@ -367,6 +367,11 @@ export interface CreateSdkOptionsConfig {
|
||||
|
||||
/** Extended thinking level for Claude models */
|
||||
thinkingLevel?: ThinkingLevel;
|
||||
|
||||
/** Optional user-configured max turns override (from settings).
|
||||
* When provided, overrides the preset MAX_TURNS for the use case.
|
||||
* Range: 1-2000. */
|
||||
maxTurns?: number;
|
||||
}
|
||||
|
||||
// Re-export MCP types from @automaker/types for convenience
|
||||
@@ -403,7 +408,7 @@ export function createSpecGenerationOptions(config: CreateSdkOptionsConfig): Opt
|
||||
// See: https://github.com/AutoMaker-Org/automaker/issues/149
|
||||
permissionMode: 'default',
|
||||
model: getModelForUseCase('spec', config.model),
|
||||
maxTurns: MAX_TURNS.maximum,
|
||||
maxTurns: config.maxTurns ?? MAX_TURNS.maximum,
|
||||
cwd: config.cwd,
|
||||
allowedTools: [...TOOL_PRESETS.specGeneration],
|
||||
...claudeMdOptions,
|
||||
@@ -437,7 +442,7 @@ export function createFeatureGenerationOptions(config: CreateSdkOptionsConfig):
|
||||
// Override permissionMode - feature generation only needs read-only tools
|
||||
permissionMode: 'default',
|
||||
model: getModelForUseCase('features', config.model),
|
||||
maxTurns: MAX_TURNS.quick,
|
||||
maxTurns: config.maxTurns ?? MAX_TURNS.quick,
|
||||
cwd: config.cwd,
|
||||
allowedTools: [...TOOL_PRESETS.readOnly],
|
||||
...claudeMdOptions,
|
||||
@@ -468,7 +473,7 @@ export function createSuggestionsOptions(config: CreateSdkOptionsConfig): Option
|
||||
return {
|
||||
...getBaseOptions(),
|
||||
model: getModelForUseCase('suggestions', config.model),
|
||||
maxTurns: MAX_TURNS.extended,
|
||||
maxTurns: config.maxTurns ?? MAX_TURNS.extended,
|
||||
cwd: config.cwd,
|
||||
allowedTools: [...TOOL_PRESETS.readOnly],
|
||||
...claudeMdOptions,
|
||||
@@ -506,7 +511,7 @@ export function createChatOptions(config: CreateSdkOptionsConfig): Options {
|
||||
return {
|
||||
...getBaseOptions(),
|
||||
model: getModelForUseCase('chat', effectiveModel),
|
||||
maxTurns: MAX_TURNS.standard,
|
||||
maxTurns: config.maxTurns ?? MAX_TURNS.standard,
|
||||
cwd: config.cwd,
|
||||
allowedTools: [...TOOL_PRESETS.chat],
|
||||
...claudeMdOptions,
|
||||
@@ -541,7 +546,7 @@ export function createAutoModeOptions(config: CreateSdkOptionsConfig): Options {
|
||||
return {
|
||||
...getBaseOptions(),
|
||||
model: getModelForUseCase('auto', config.model),
|
||||
maxTurns: MAX_TURNS.maximum,
|
||||
maxTurns: config.maxTurns ?? MAX_TURNS.maximum,
|
||||
cwd: config.cwd,
|
||||
allowedTools: [...TOOL_PRESETS.fullAccess],
|
||||
...claudeMdOptions,
|
||||
|
||||
@@ -33,9 +33,16 @@ import {
|
||||
|
||||
const logger = createLogger('SettingsHelper');
|
||||
|
||||
/** Default number of agent turns used when no value is configured. */
|
||||
export const DEFAULT_MAX_TURNS = 1000;
|
||||
|
||||
/** Upper bound for the max-turns clamp; values above this are capped here. */
|
||||
export const MAX_ALLOWED_TURNS = 2000;
|
||||
|
||||
/**
|
||||
* Get the autoLoadClaudeMd setting, with project settings taking precedence over global.
|
||||
* Returns false if settings service is not available.
|
||||
* Falls back to global settings and defaults to true when unset.
|
||||
* Returns true if settings service is not available.
|
||||
*
|
||||
* @param projectPath - Path to the project
|
||||
* @param settingsService - Optional settings service instance
|
||||
@@ -48,8 +55,8 @@ export async function getAutoLoadClaudeMdSetting(
|
||||
logPrefix = '[SettingsHelper]'
|
||||
): Promise<boolean> {
|
||||
if (!settingsService) {
|
||||
logger.info(`${logPrefix} SettingsService not available, autoLoadClaudeMd disabled`);
|
||||
return false;
|
||||
logger.info(`${logPrefix} SettingsService not available, autoLoadClaudeMd defaulting to true`);
|
||||
return true;
|
||||
}
|
||||
|
||||
try {
|
||||
@@ -64,7 +71,7 @@ export async function getAutoLoadClaudeMdSetting(
|
||||
|
||||
// Fall back to global settings
|
||||
const globalSettings = await settingsService.getGlobalSettings();
|
||||
const result = globalSettings.autoLoadClaudeMd ?? false;
|
||||
const result = globalSettings.autoLoadClaudeMd ?? true;
|
||||
logger.info(`${logPrefix} autoLoadClaudeMd from global settings: ${result}`);
|
||||
return result;
|
||||
} catch (error) {
|
||||
@@ -73,6 +80,41 @@ export async function getAutoLoadClaudeMdSetting(
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the default max turns setting from global settings.
|
||||
*
|
||||
* Reads the user's configured `defaultMaxTurns` setting, which controls the maximum
|
||||
* number of agent turns (tool-call round-trips) for feature execution.
|
||||
*
|
||||
* @param settingsService - Settings service instance (may be null)
|
||||
* @param logPrefix - Logging prefix for debugging
|
||||
* @returns The user's configured max turns, or {@link DEFAULT_MAX_TURNS} as default
|
||||
*/
|
||||
export async function getDefaultMaxTurnsSetting(
|
||||
settingsService?: SettingsService | null,
|
||||
logPrefix = '[SettingsHelper]'
|
||||
): Promise<number> {
|
||||
if (!settingsService) {
|
||||
logger.info(
|
||||
`${logPrefix} SettingsService not available, using default maxTurns=${DEFAULT_MAX_TURNS}`
|
||||
);
|
||||
return DEFAULT_MAX_TURNS;
|
||||
}
|
||||
|
||||
try {
|
||||
const globalSettings = await settingsService.getGlobalSettings();
|
||||
const raw = globalSettings.defaultMaxTurns;
|
||||
const result = Number.isFinite(raw) ? (raw as number) : DEFAULT_MAX_TURNS;
|
||||
// Clamp to valid range
|
||||
const clamped = Math.max(1, Math.min(MAX_ALLOWED_TURNS, Math.floor(result)));
|
||||
logger.debug(`${logPrefix} defaultMaxTurns from global settings: ${clamped}`);
|
||||
return clamped;
|
||||
} catch (error) {
|
||||
logger.error(`${logPrefix} Failed to load defaultMaxTurns setting:`, error);
|
||||
return DEFAULT_MAX_TURNS;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Filters out CLAUDE.md from context files when autoLoadClaudeMd is enabled
|
||||
* and rebuilds the formatted prompt without it.
|
||||
|
||||
@@ -180,7 +180,7 @@ export class ClaudeProvider extends BaseProvider {
|
||||
model,
|
||||
cwd,
|
||||
systemPrompt,
|
||||
maxTurns = 100,
|
||||
maxTurns = 1000,
|
||||
allowedTools,
|
||||
abortController,
|
||||
conversationHistory,
|
||||
|
||||
@@ -33,7 +33,6 @@ import {
|
||||
supportsReasoningEffort,
|
||||
validateBareModelId,
|
||||
calculateReasoningTimeout,
|
||||
DEFAULT_TIMEOUT_MS,
|
||||
type CodexApprovalPolicy,
|
||||
type CodexSandboxMode,
|
||||
type CodexAuthStatus,
|
||||
@@ -98,7 +97,7 @@ const TEXT_ENCODING = 'utf-8';
|
||||
*
|
||||
* @see calculateReasoningTimeout from @automaker/types
|
||||
*/
|
||||
const CODEX_CLI_TIMEOUT_MS = DEFAULT_TIMEOUT_MS;
|
||||
const CODEX_CLI_TIMEOUT_MS = 120000; // 2 minutes — matches CLI provider base timeout
|
||||
const CODEX_FEATURE_GENERATION_BASE_TIMEOUT_MS = 300000; // 5 minutes for feature generation
|
||||
const SYSTEM_PROMPT_SEPARATOR = '\n\n';
|
||||
const CODEX_INSTRUCTIONS_DIR = '.codex';
|
||||
@@ -738,6 +737,16 @@ export class CodexProvider extends BaseProvider {
|
||||
);
|
||||
const baseSystemPrompt = resolveSystemPrompt(options.systemPrompt);
|
||||
const resolvedMaxTurns = resolveMaxTurns(options.maxTurns);
|
||||
if (resolvedMaxTurns === null && options.maxTurns === undefined) {
|
||||
logger.warn(
|
||||
`[executeQuery] maxTurns not provided — Codex CLI will use its internal default. ` +
|
||||
`This may cause premature completion. Model: ${options.model}`
|
||||
);
|
||||
} else {
|
||||
logger.info(
|
||||
`[executeQuery] maxTurns: requested=${options.maxTurns}, resolved=${resolvedMaxTurns}, model=${options.model}`
|
||||
);
|
||||
}
|
||||
const resolvedAllowedTools = options.allowedTools ?? Array.from(DEFAULT_ALLOWED_TOOLS);
|
||||
const restrictTools = !hasMcpServers || options.mcpUnrestrictedTools === false;
|
||||
const wantsOutputSchema = Boolean(
|
||||
|
||||
@@ -19,10 +19,11 @@ export function createAnalyzeProjectHandler(autoModeService: AutoModeServiceComp
|
||||
return;
|
||||
}
|
||||
|
||||
// Start analysis in background
|
||||
autoModeService.analyzeProject(projectPath).catch((error) => {
|
||||
logger.error(`[AutoMode] Project analysis error:`, error);
|
||||
});
|
||||
// Kick off analysis in the background; attach a rejection handler so
|
||||
// unhandled-promise warnings don't surface and errors are at least logged.
|
||||
// Synchronous throws (e.g. "not implemented") still propagate here.
|
||||
const analysisPromise = autoModeService.analyzeProject(projectPath);
|
||||
analysisPromise.catch((err) => logError(err, 'Background analyzeProject failed'));
|
||||
|
||||
res.json({ success: true, message: 'Project analysis started' });
|
||||
} catch (error) {
|
||||
|
||||
@@ -24,7 +24,9 @@ export function createWriteHandler() {
|
||||
|
||||
// Ensure parent directory exists (symlink-safe)
|
||||
await mkdirSafe(path.dirname(path.resolve(filePath)));
|
||||
await secureFs.writeFile(filePath, content, 'utf-8');
|
||||
// Default content to empty string if undefined/null to prevent writing
|
||||
// "undefined" as literal text (e.g. when content field is missing from request)
|
||||
await secureFs.writeFile(filePath, content ?? '', 'utf-8');
|
||||
|
||||
res.json({ success: true });
|
||||
} catch (error) {
|
||||
|
||||
@@ -9,6 +9,8 @@ import { createCheckGitHubRemoteHandler } from './routes/check-github-remote.js'
|
||||
import { createListIssuesHandler } from './routes/list-issues.js';
|
||||
import { createListPRsHandler } from './routes/list-prs.js';
|
||||
import { createListCommentsHandler } from './routes/list-comments.js';
|
||||
import { createListPRReviewCommentsHandler } from './routes/list-pr-review-comments.js';
|
||||
import { createResolvePRCommentHandler } from './routes/resolve-pr-comment.js';
|
||||
import { createValidateIssueHandler } from './routes/validate-issue.js';
|
||||
import {
|
||||
createValidationStatusHandler,
|
||||
@@ -29,6 +31,16 @@ export function createGitHubRoutes(
|
||||
router.post('/issues', validatePathParams('projectPath'), createListIssuesHandler());
|
||||
router.post('/prs', validatePathParams('projectPath'), createListPRsHandler());
|
||||
router.post('/issue-comments', validatePathParams('projectPath'), createListCommentsHandler());
|
||||
router.post(
|
||||
'/pr-review-comments',
|
||||
validatePathParams('projectPath'),
|
||||
createListPRReviewCommentsHandler()
|
||||
);
|
||||
router.post(
|
||||
'/resolve-pr-comment',
|
||||
validatePathParams('projectPath'),
|
||||
createResolvePRCommentHandler()
|
||||
);
|
||||
router.post(
|
||||
'/validate-issue',
|
||||
validatePathParams('projectPath'),
|
||||
|
||||
@@ -1,38 +1,14 @@
|
||||
/**
|
||||
* Common utilities for GitHub routes
|
||||
*
|
||||
* Re-exports shared utilities from lib/exec-utils so route consumers
|
||||
* can continue importing from this module unchanged.
|
||||
*/
|
||||
|
||||
import { exec } from 'child_process';
|
||||
import { promisify } from 'util';
|
||||
import { createLogger } from '@automaker/utils';
|
||||
|
||||
const logger = createLogger('GitHub');
|
||||
|
||||
export const execAsync = promisify(exec);
|
||||
|
||||
// Extended PATH to include common tool installation locations
|
||||
export const extendedPath = [
|
||||
process.env.PATH,
|
||||
'/opt/homebrew/bin',
|
||||
'/usr/local/bin',
|
||||
'/home/linuxbrew/.linuxbrew/bin',
|
||||
`${process.env.HOME}/.local/bin`,
|
||||
]
|
||||
.filter(Boolean)
|
||||
.join(':');
|
||||
|
||||
export const execEnv = {
|
||||
...process.env,
|
||||
PATH: extendedPath,
|
||||
};
|
||||
|
||||
export function getErrorMessage(error: unknown): string {
|
||||
if (error instanceof Error) {
|
||||
return error.message;
|
||||
}
|
||||
return String(error);
|
||||
}
|
||||
|
||||
export function logError(error: unknown, context: string): void {
|
||||
logger.error(`${context}:`, error);
|
||||
}
|
||||
// Re-export shared utilities from the canonical location
|
||||
export { extendedPath, execEnv, getErrorMessage, logError } from '../../../lib/exec-utils.js';
|
||||
|
||||
@@ -0,0 +1,72 @@
|
||||
/**
|
||||
* POST /pr-review-comments endpoint - Fetch review comments for a GitHub PR
|
||||
*
|
||||
* Fetches both regular PR comments and inline code review comments
|
||||
* for a specific pull request, providing file path and line context.
|
||||
*/
|
||||
|
||||
import type { Request, Response } from 'express';
|
||||
import { getErrorMessage, logError } from './common.js';
|
||||
import { checkGitHubRemote } from './check-github-remote.js';
|
||||
import {
|
||||
fetchPRReviewComments,
|
||||
fetchReviewThreadResolvedStatus,
|
||||
type PRReviewComment,
|
||||
type ListPRReviewCommentsResult,
|
||||
} from '../../../services/pr-review-comments.service.js';
|
||||
|
||||
// Re-export types so existing callers continue to work
|
||||
export type { PRReviewComment, ListPRReviewCommentsResult };
|
||||
// Re-export service functions so existing callers continue to work
|
||||
export { fetchPRReviewComments, fetchReviewThreadResolvedStatus };
|
||||
|
||||
interface ListPRReviewCommentsRequest {
|
||||
projectPath: string;
|
||||
prNumber: number;
|
||||
}
|
||||
|
||||
export function createListPRReviewCommentsHandler() {
|
||||
return async (req: Request, res: Response): Promise<void> => {
|
||||
try {
|
||||
const { projectPath, prNumber } = req.body as ListPRReviewCommentsRequest;
|
||||
|
||||
if (!projectPath) {
|
||||
res.status(400).json({ success: false, error: 'projectPath is required' });
|
||||
return;
|
||||
}
|
||||
|
||||
if (!prNumber || typeof prNumber !== 'number') {
|
||||
res
|
||||
.status(400)
|
||||
.json({ success: false, error: 'prNumber is required and must be a number' });
|
||||
return;
|
||||
}
|
||||
|
||||
// Check if this is a GitHub repo and get owner/repo
|
||||
const remoteStatus = await checkGitHubRemote(projectPath);
|
||||
if (!remoteStatus.hasGitHubRemote || !remoteStatus.owner || !remoteStatus.repo) {
|
||||
res.status(400).json({
|
||||
success: false,
|
||||
error: 'Project does not have a GitHub remote',
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
const comments = await fetchPRReviewComments(
|
||||
projectPath,
|
||||
remoteStatus.owner,
|
||||
remoteStatus.repo,
|
||||
prNumber
|
||||
);
|
||||
|
||||
res.json({
|
||||
success: true,
|
||||
comments,
|
||||
totalCount: comments.length,
|
||||
});
|
||||
} catch (error) {
|
||||
logError(error, 'Fetch PR review comments failed');
|
||||
res.status(500).json({ success: false, error: getErrorMessage(error) });
|
||||
}
|
||||
};
|
||||
}
|
||||
66
apps/server/src/routes/github/routes/resolve-pr-comment.ts
Normal file
66
apps/server/src/routes/github/routes/resolve-pr-comment.ts
Normal file
@@ -0,0 +1,66 @@
|
||||
/**
|
||||
* POST /resolve-pr-comment endpoint - Resolve or unresolve a GitHub PR review thread
|
||||
*
|
||||
* Uses the GitHub GraphQL API to resolve or unresolve a review thread
|
||||
* identified by its GraphQL node ID (threadId).
|
||||
*/
|
||||
|
||||
import type { Request, Response } from 'express';
|
||||
import { getErrorMessage, logError } from './common.js';
|
||||
import { checkGitHubRemote } from './check-github-remote.js';
|
||||
import { executeReviewThreadMutation } from '../../../services/github-pr-comment.service.js';
|
||||
|
||||
export interface ResolvePRCommentResult {
|
||||
success: boolean;
|
||||
isResolved?: boolean;
|
||||
error?: string;
|
||||
}
|
||||
|
||||
interface ResolvePRCommentRequest {
|
||||
projectPath: string;
|
||||
threadId: string;
|
||||
resolve: boolean;
|
||||
}
|
||||
|
||||
export function createResolvePRCommentHandler() {
|
||||
return async (req: Request, res: Response): Promise<void> => {
|
||||
try {
|
||||
const { projectPath, threadId, resolve } = req.body as ResolvePRCommentRequest;
|
||||
|
||||
if (!projectPath) {
|
||||
res.status(400).json({ success: false, error: 'projectPath is required' });
|
||||
return;
|
||||
}
|
||||
|
||||
if (!threadId) {
|
||||
res.status(400).json({ success: false, error: 'threadId is required' });
|
||||
return;
|
||||
}
|
||||
|
||||
if (typeof resolve !== 'boolean') {
|
||||
res.status(400).json({ success: false, error: 'resolve must be a boolean' });
|
||||
return;
|
||||
}
|
||||
|
||||
// Check if this is a GitHub repo
|
||||
const remoteStatus = await checkGitHubRemote(projectPath);
|
||||
if (!remoteStatus.hasGitHubRemote) {
|
||||
res.status(400).json({
|
||||
success: false,
|
||||
error: 'Project does not have a GitHub remote',
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
const result = await executeReviewThreadMutation(projectPath, threadId, resolve);
|
||||
|
||||
res.json({
|
||||
success: true,
|
||||
isResolved: result.isResolved,
|
||||
});
|
||||
} catch (error) {
|
||||
logError(error, 'Resolve PR comment failed');
|
||||
res.status(500).json({ success: false, error: getErrorMessage(error) });
|
||||
}
|
||||
};
|
||||
}
|
||||
@@ -67,6 +67,8 @@ import { createAbortOperationHandler } from './routes/abort-operation.js';
|
||||
import { createContinueOperationHandler } from './routes/continue-operation.js';
|
||||
import { createStageFilesHandler } from './routes/stage-files.js';
|
||||
import { createCheckChangesHandler } from './routes/check-changes.js';
|
||||
import { createSetTrackingHandler } from './routes/set-tracking.js';
|
||||
import { createSyncHandler } from './routes/sync.js';
|
||||
import type { SettingsService } from '../../services/settings-service.js';
|
||||
|
||||
export function createWorktreeRoutes(
|
||||
@@ -118,6 +120,18 @@ export function createWorktreeRoutes(
|
||||
requireValidWorktree,
|
||||
createPullHandler()
|
||||
);
|
||||
router.post(
|
||||
'/sync',
|
||||
validatePathParams('worktreePath'),
|
||||
requireValidWorktree,
|
||||
createSyncHandler()
|
||||
);
|
||||
router.post(
|
||||
'/set-tracking',
|
||||
validatePathParams('worktreePath'),
|
||||
requireValidWorktree,
|
||||
createSetTrackingHandler()
|
||||
);
|
||||
router.post(
|
||||
'/checkout-branch',
|
||||
validatePathParams('worktreePath'),
|
||||
|
||||
@@ -4,7 +4,8 @@
|
||||
* This endpoint handles worktree creation with proper checks:
|
||||
* 1. First checks if git already has a worktree for the branch (anywhere)
|
||||
* 2. If found, returns the existing worktree (no error)
|
||||
* 3. Only creates a new worktree if none exists for the branch
|
||||
* 3. Syncs the base branch from its remote tracking branch (fast-forward only)
|
||||
* 4. Only creates a new worktree if none exists for the branch
|
||||
*/
|
||||
|
||||
import type { Request, Response } from 'express';
|
||||
@@ -27,6 +28,10 @@ import { execGitCommand } from '../../../lib/git.js';
|
||||
import { trackBranch } from './branch-tracking.js';
|
||||
import { createLogger } from '@automaker/utils';
|
||||
import { runInitScript } from '../../../services/init-script-service.js';
|
||||
import {
|
||||
syncBaseBranch,
|
||||
type BaseBranchSyncResult,
|
||||
} from '../../../services/branch-sync-service.js';
|
||||
|
||||
const logger = createLogger('Worktree');
|
||||
|
||||
@@ -193,6 +198,52 @@ export function createCreateHandler(events: EventEmitter, settingsService?: Sett
|
||||
logger.warn(`Failed to fetch from remotes: ${getErrorMessage(fetchErr)}`);
|
||||
}
|
||||
|
||||
// Sync the base branch with its remote tracking branch (fast-forward only).
|
||||
// This ensures the new worktree starts from an up-to-date state rather than
|
||||
// a potentially stale local copy. If the sync fails or the branch has diverged,
|
||||
// we proceed with the local copy and inform the user.
|
||||
const effectiveBase = baseBranch || 'HEAD';
|
||||
let syncResult: BaseBranchSyncResult = { attempted: false, synced: false };
|
||||
|
||||
// Only sync if the base is a real branch (not 'HEAD')
|
||||
// Pass skipFetch=true because we already fetched all remotes above.
|
||||
if (effectiveBase !== 'HEAD') {
|
||||
logger.info(`Syncing base branch '${effectiveBase}' before creating worktree`);
|
||||
syncResult = await syncBaseBranch(projectPath, effectiveBase, true);
|
||||
if (syncResult.attempted) {
|
||||
if (syncResult.synced) {
|
||||
logger.info(`Base branch sync result: ${syncResult.message}`);
|
||||
} else {
|
||||
logger.warn(`Base branch sync result: ${syncResult.message}`);
|
||||
}
|
||||
}
|
||||
} else {
|
||||
// When using HEAD, try to sync the currently checked-out branch
|
||||
// Pass skipFetch=true because we already fetched all remotes above.
|
||||
try {
|
||||
const currentBranch = await execGitCommand(
|
||||
['rev-parse', '--abbrev-ref', 'HEAD'],
|
||||
projectPath
|
||||
);
|
||||
const trimmedBranch = currentBranch.trim();
|
||||
if (trimmedBranch && trimmedBranch !== 'HEAD') {
|
||||
logger.info(
|
||||
`Syncing current branch '${trimmedBranch}' (HEAD) before creating worktree`
|
||||
);
|
||||
syncResult = await syncBaseBranch(projectPath, trimmedBranch, true);
|
||||
if (syncResult.attempted) {
|
||||
if (syncResult.synced) {
|
||||
logger.info(`HEAD branch sync result: ${syncResult.message}`);
|
||||
} else {
|
||||
logger.warn(`HEAD branch sync result: ${syncResult.message}`);
|
||||
}
|
||||
}
|
||||
}
|
||||
} catch {
|
||||
// Could not determine HEAD branch — skip sync
|
||||
}
|
||||
}
|
||||
|
||||
// Check if branch exists (using array arguments to prevent injection)
|
||||
let branchExists = false;
|
||||
try {
|
||||
@@ -226,6 +277,19 @@ export function createCreateHandler(events: EventEmitter, settingsService?: Sett
|
||||
// normalizePath converts to forward slashes for API consistency
|
||||
const absoluteWorktreePath = path.resolve(worktreePath);
|
||||
|
||||
// Get the commit hash the new worktree is based on for logging
|
||||
let baseCommitHash: string | undefined;
|
||||
try {
|
||||
const hash = await execGitCommand(['rev-parse', '--short', 'HEAD'], absoluteWorktreePath);
|
||||
baseCommitHash = hash.trim();
|
||||
} catch {
|
||||
// Non-critical — just for logging
|
||||
}
|
||||
|
||||
if (baseCommitHash) {
|
||||
logger.info(`New worktree for '${branchName}' based on commit ${baseCommitHash}`);
|
||||
}
|
||||
|
||||
// Copy configured files into the new worktree before responding
|
||||
// This runs synchronously to ensure files are in place before any init script
|
||||
try {
|
||||
@@ -247,6 +311,17 @@ export function createCreateHandler(events: EventEmitter, settingsService?: Sett
|
||||
path: normalizePath(absoluteWorktreePath),
|
||||
branch: branchName,
|
||||
isNew: !branchExists,
|
||||
baseCommitHash,
|
||||
...(syncResult.attempted
|
||||
? {
|
||||
syncResult: {
|
||||
synced: syncResult.synced,
|
||||
remote: syncResult.remote,
|
||||
message: syncResult.message,
|
||||
diverged: syncResult.diverged,
|
||||
},
|
||||
}
|
||||
: {}),
|
||||
},
|
||||
});
|
||||
|
||||
|
||||
@@ -5,6 +5,7 @@
|
||||
import type { Request, Response } from 'express';
|
||||
import { exec } from 'child_process';
|
||||
import { promisify } from 'util';
|
||||
import fs from 'fs/promises';
|
||||
import { isGitRepo } from '@automaker/git-utils';
|
||||
import { getErrorMessage, logError, isValidBranchName } from '../common.js';
|
||||
import { execGitCommand } from '../../../lib/git.js';
|
||||
@@ -46,20 +47,79 @@ export function createDeleteHandler() {
|
||||
});
|
||||
branchName = stdout.trim();
|
||||
} catch {
|
||||
// Could not get branch name
|
||||
// Could not get branch name - worktree directory may already be gone
|
||||
logger.debug('Could not determine branch for worktree, directory may be missing');
|
||||
}
|
||||
|
||||
// Remove the worktree (using array arguments to prevent injection)
|
||||
let removeSucceeded = false;
|
||||
try {
|
||||
await execGitCommand(['worktree', 'remove', worktreePath, '--force'], projectPath);
|
||||
} catch {
|
||||
// Try with prune if remove fails
|
||||
await execGitCommand(['worktree', 'prune'], projectPath);
|
||||
removeSucceeded = true;
|
||||
} catch (removeError) {
|
||||
// `git worktree remove` can fail if the directory is already missing
|
||||
// or in a bad state. Try pruning stale worktree entries as a fallback.
|
||||
logger.debug('git worktree remove failed, trying prune', {
|
||||
error: getErrorMessage(removeError),
|
||||
});
|
||||
try {
|
||||
await execGitCommand(['worktree', 'prune'], projectPath);
|
||||
|
||||
// Verify the specific worktree is no longer registered after prune.
|
||||
// `git worktree prune` exits 0 even if worktreePath was never registered,
|
||||
// so we must explicitly check the worktree list to avoid false positives.
|
||||
const { stdout: listOut } = await execAsync('git worktree list --porcelain', {
|
||||
cwd: projectPath,
|
||||
});
|
||||
// Parse porcelain output and check for an exact path match.
|
||||
// Using substring .includes() can produce false positives when one
|
||||
// worktree path is a prefix of another (e.g. /foo vs /foobar).
|
||||
const stillRegistered = listOut
|
||||
.split('\n')
|
||||
.filter((line) => line.startsWith('worktree '))
|
||||
.map((line) => line.slice('worktree '.length).trim())
|
||||
.some((registeredPath) => registeredPath === worktreePath);
|
||||
if (stillRegistered) {
|
||||
// Prune didn't clean up our entry - treat as failure
|
||||
throw removeError;
|
||||
}
|
||||
removeSucceeded = true;
|
||||
} catch (pruneError) {
|
||||
// If pruneError is the original removeError re-thrown, propagate it
|
||||
if (pruneError === removeError) {
|
||||
throw removeError;
|
||||
}
|
||||
logger.warn('git worktree prune also failed', {
|
||||
error: getErrorMessage(pruneError),
|
||||
});
|
||||
// If both remove and prune fail, still try to return success
|
||||
// if the worktree directory no longer exists (it may have been
|
||||
// manually deleted already).
|
||||
let dirExists = false;
|
||||
try {
|
||||
await fs.access(worktreePath);
|
||||
dirExists = true;
|
||||
} catch {
|
||||
// Directory doesn't exist
|
||||
}
|
||||
if (dirExists) {
|
||||
// Directory still exists - this is a real failure
|
||||
throw removeError;
|
||||
}
|
||||
// Directory is gone, treat as success
|
||||
removeSucceeded = true;
|
||||
}
|
||||
}
|
||||
|
||||
// Optionally delete the branch
|
||||
// Optionally delete the branch (only if worktree was successfully removed)
|
||||
let branchDeleted = false;
|
||||
if (deleteBranch && branchName && branchName !== 'main' && branchName !== 'master') {
|
||||
if (
|
||||
removeSucceeded &&
|
||||
deleteBranch &&
|
||||
branchName &&
|
||||
branchName !== 'main' &&
|
||||
branchName !== 'master'
|
||||
) {
|
||||
// Validate branch name to prevent command injection
|
||||
if (!isValidBranchName(branchName)) {
|
||||
logger.warn(`Invalid branch name detected, skipping deletion: ${branchName}`);
|
||||
|
||||
@@ -6,7 +6,7 @@
|
||||
*/
|
||||
|
||||
import type { Request, Response } from 'express';
|
||||
import { exec } from 'child_process';
|
||||
import { execFile } from 'child_process';
|
||||
import { promisify } from 'util';
|
||||
import { existsSync } from 'fs';
|
||||
import { join } from 'path';
|
||||
@@ -20,7 +20,7 @@ import { getErrorMessage, logError } from '../common.js';
|
||||
import { getPhaseModelWithOverrides } from '../../../lib/settings-helpers.js';
|
||||
|
||||
const logger = createLogger('GenerateCommitMessage');
|
||||
const execAsync = promisify(exec);
|
||||
const execFileAsync = promisify(execFile);
|
||||
|
||||
/** Timeout for AI provider calls in milliseconds (30 seconds) */
|
||||
const AI_TIMEOUT_MS = 30_000;
|
||||
@@ -33,20 +33,39 @@ async function* withTimeout<T>(
|
||||
generator: AsyncIterable<T>,
|
||||
timeoutMs: number
|
||||
): AsyncGenerator<T, void, unknown> {
|
||||
let timerId: ReturnType<typeof setTimeout> | undefined;
|
||||
|
||||
const timeoutPromise = new Promise<never>((_, reject) => {
|
||||
setTimeout(() => reject(new Error(`AI provider timed out after ${timeoutMs}ms`)), timeoutMs);
|
||||
timerId = setTimeout(
|
||||
() => reject(new Error(`AI provider timed out after ${timeoutMs}ms`)),
|
||||
timeoutMs
|
||||
);
|
||||
});
|
||||
|
||||
const iterator = generator[Symbol.asyncIterator]();
|
||||
let done = false;
|
||||
|
||||
while (!done) {
|
||||
const result = await Promise.race([iterator.next(), timeoutPromise]);
|
||||
if (result.done) {
|
||||
done = true;
|
||||
} else {
|
||||
yield result.value;
|
||||
try {
|
||||
while (!done) {
|
||||
const result = await Promise.race([iterator.next(), timeoutPromise]).catch(async (err) => {
|
||||
// Capture the original error, then attempt to close the iterator.
|
||||
// If iterator.return() throws, log it but rethrow the original error
|
||||
// so the timeout error (not the teardown error) is preserved.
|
||||
try {
|
||||
await iterator.return?.();
|
||||
} catch (teardownErr) {
|
||||
logger.warn('Error during iterator cleanup after timeout:', teardownErr);
|
||||
}
|
||||
throw err;
|
||||
});
|
||||
if (result.done) {
|
||||
done = true;
|
||||
} else {
|
||||
yield result.value;
|
||||
}
|
||||
}
|
||||
} finally {
|
||||
clearTimeout(timerId);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -117,14 +136,14 @@ export function createGenerateCommitMessageHandler(
|
||||
let diff = '';
|
||||
try {
|
||||
// First try to get staged changes
|
||||
const { stdout: stagedDiff } = await execAsync('git diff --cached', {
|
||||
const { stdout: stagedDiff } = await execFileAsync('git', ['diff', '--cached'], {
|
||||
cwd: worktreePath,
|
||||
maxBuffer: 1024 * 1024 * 5, // 5MB buffer
|
||||
});
|
||||
|
||||
// If no staged changes, get unstaged changes
|
||||
if (!stagedDiff.trim()) {
|
||||
const { stdout: unstagedDiff } = await execAsync('git diff', {
|
||||
const { stdout: unstagedDiff } = await execFileAsync('git', ['diff'], {
|
||||
cwd: worktreePath,
|
||||
maxBuffer: 1024 * 1024 * 5, // 5MB buffer
|
||||
});
|
||||
@@ -213,14 +232,16 @@ export function createGenerateCommitMessageHandler(
|
||||
}
|
||||
}
|
||||
} else if (msg.type === 'result' && msg.subtype === 'success' && msg.result) {
|
||||
// Use result if available (some providers return final text here)
|
||||
responseText = msg.result;
|
||||
// Use result text if longer than accumulated text (consistent with simpleQuery pattern)
|
||||
if (msg.result.length > responseText.length) {
|
||||
responseText = msg.result;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const message = responseText.trim();
|
||||
|
||||
if (!message || message.trim().length === 0) {
|
||||
if (!message) {
|
||||
logger.warn('Received empty response from model');
|
||||
const response: GenerateCommitMessageErrorResponse = {
|
||||
success: false,
|
||||
|
||||
@@ -30,6 +30,8 @@ const MAX_DIFF_SIZE = 15_000;
|
||||
|
||||
const PR_DESCRIPTION_SYSTEM_PROMPT = `You are a pull request description generator. Your task is to create a clear, well-structured PR title and description based on the git diff and branch information provided.
|
||||
|
||||
IMPORTANT: Do NOT include any conversational text, explanations, or preamble. Do NOT say things like "I'll analyze..." or "Here is...". Output ONLY the structured format below and nothing else.
|
||||
|
||||
Output your response in EXACTLY this format (including the markers):
|
||||
---TITLE---
|
||||
<a concise PR title, 50-72 chars, imperative mood>
|
||||
@@ -41,6 +43,7 @@ Output your response in EXACTLY this format (including the markers):
|
||||
<Detailed list of what was changed and why>
|
||||
|
||||
Rules:
|
||||
- Your ENTIRE response must start with ---TITLE--- and contain nothing before it
|
||||
- The title should be concise and descriptive (50-72 characters)
|
||||
- Use imperative mood for the title (e.g., "Add dark mode toggle" not "Added dark mode toggle")
|
||||
- The description should explain WHAT changed and WHY
|
||||
@@ -50,7 +53,9 @@ Rules:
|
||||
- Focus on the user-facing impact when possible
|
||||
- If there are breaking changes, mention them prominently
|
||||
- The diff may include both committed changes and uncommitted working directory changes. Treat all changes as part of the PR since uncommitted changes will be committed when the PR is created
|
||||
- Do NOT distinguish between committed and uncommitted changes in the output - describe all changes as a unified set of PR changes`;
|
||||
- Do NOT distinguish between committed and uncommitted changes in the output - describe all changes as a unified set of PR changes
|
||||
- EXCLUDE any files that are gitignored (e.g., node_modules, dist, build, .env files, lock files, generated files, binary artifacts, coverage reports, cache directories). These should not be mentioned in the description even if they appear in the diff
|
||||
- Focus only on meaningful source code changes that are tracked by git and relevant to reviewers`;
|
||||
|
||||
/**
|
||||
* Wraps an async generator with a timeout.
|
||||
@@ -397,7 +402,10 @@ export function createGeneratePRDescriptionHandler(
|
||||
}
|
||||
}
|
||||
} else if (msg.type === 'result' && msg.subtype === 'success' && msg.result) {
|
||||
responseText = msg.result;
|
||||
// Use result text if longer than accumulated text (consistent with simpleQuery pattern)
|
||||
if (msg.result.length > responseText.length) {
|
||||
responseText = msg.result;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -413,7 +421,9 @@ export function createGeneratePRDescriptionHandler(
|
||||
return;
|
||||
}
|
||||
|
||||
// Parse the response to extract title and body
|
||||
// Parse the response to extract title and body.
|
||||
// The model may include conversational preamble before the structured markers,
|
||||
// so we search for the markers anywhere in the response, not just at the start.
|
||||
let title = '';
|
||||
let body = '';
|
||||
|
||||
@@ -424,14 +434,46 @@ export function createGeneratePRDescriptionHandler(
|
||||
title = titleMatch[1].trim();
|
||||
body = bodyMatch[1].trim();
|
||||
} else {
|
||||
// Fallback: treat first line as title, rest as body
|
||||
const lines = fullResponse.split('\n');
|
||||
title = lines[0].trim();
|
||||
body = lines.slice(1).join('\n').trim();
|
||||
// Fallback: try to extract meaningful content, skipping any conversational preamble.
|
||||
// Common preamble patterns start with "I'll", "I will", "Here", "Let me", "Based on", etc.
|
||||
const lines = fullResponse.split('\n').filter((line) => line.trim().length > 0);
|
||||
|
||||
// Skip lines that look like conversational preamble
|
||||
let startIndex = 0;
|
||||
for (let i = 0; i < lines.length; i++) {
|
||||
const line = lines[i].trim();
|
||||
// Check if this line looks like conversational AI preamble
|
||||
if (
|
||||
/^(I'll|I will|Here('s| is| are)|Let me|Based on|Looking at|Analyzing|Sure|OK|Okay|Of course)/i.test(
|
||||
line
|
||||
) ||
|
||||
/^(The following|Below is|This (is|will)|After (analyzing|reviewing|looking))/i.test(
|
||||
line
|
||||
)
|
||||
) {
|
||||
startIndex = i + 1;
|
||||
continue;
|
||||
}
|
||||
break;
|
||||
}
|
||||
|
||||
// Use remaining lines after skipping preamble
|
||||
const contentLines = lines.slice(startIndex);
|
||||
if (contentLines.length > 0) {
|
||||
title = contentLines[0].trim();
|
||||
body = contentLines.slice(1).join('\n').trim();
|
||||
} else {
|
||||
// If all lines were filtered as preamble, use the original first non-empty line
|
||||
title = lines[0]?.trim() || '';
|
||||
body = lines.slice(1).join('\n').trim();
|
||||
}
|
||||
}
|
||||
|
||||
// Clean up title - remove any markdown or quotes
|
||||
title = title.replace(/^#+\s*/, '').replace(/^["']|["']$/g, '');
|
||||
// Clean up title - remove any markdown headings, quotes, or marker artifacts
|
||||
title = title
|
||||
.replace(/^#+\s*/, '')
|
||||
.replace(/^["']|["']$/g, '')
|
||||
.replace(/^---\w+---\s*/, '');
|
||||
|
||||
logger.info(`Generated PR title: ${title.substring(0, 100)}...`);
|
||||
|
||||
|
||||
@@ -1,24 +1,24 @@
|
||||
/**
|
||||
* POST /push endpoint - Push a worktree branch to remote
|
||||
*
|
||||
* Git business logic is delegated to push-service.ts.
|
||||
*
|
||||
* Note: Git repository validation (isGitRepo, hasCommits) is handled by
|
||||
* the requireValidWorktree middleware in index.ts
|
||||
*/
|
||||
|
||||
import type { Request, Response } from 'express';
|
||||
import { exec } from 'child_process';
|
||||
import { promisify } from 'util';
|
||||
import { getErrorMessage, logError } from '../common.js';
|
||||
|
||||
const execAsync = promisify(exec);
|
||||
import { performPush } from '../../../services/push-service.js';
|
||||
|
||||
export function createPushHandler() {
|
||||
return async (req: Request, res: Response): Promise<void> => {
|
||||
try {
|
||||
const { worktreePath, force, remote } = req.body as {
|
||||
const { worktreePath, force, remote, autoResolve } = req.body as {
|
||||
worktreePath: string;
|
||||
force?: boolean;
|
||||
remote?: string;
|
||||
autoResolve?: boolean;
|
||||
};
|
||||
|
||||
if (!worktreePath) {
|
||||
@@ -29,34 +29,28 @@ export function createPushHandler() {
|
||||
return;
|
||||
}
|
||||
|
||||
// Get branch name
|
||||
const { stdout: branchOutput } = await execAsync('git rev-parse --abbrev-ref HEAD', {
|
||||
cwd: worktreePath,
|
||||
});
|
||||
const branchName = branchOutput.trim();
|
||||
const result = await performPush(worktreePath, { remote, force, autoResolve });
|
||||
|
||||
// Use specified remote or default to 'origin'
|
||||
const targetRemote = remote || 'origin';
|
||||
|
||||
// Push the branch
|
||||
const forceFlag = force ? '--force' : '';
|
||||
try {
|
||||
await execAsync(`git push -u ${targetRemote} ${branchName} ${forceFlag}`, {
|
||||
cwd: worktreePath,
|
||||
});
|
||||
} catch {
|
||||
// Try setting upstream
|
||||
await execAsync(`git push --set-upstream ${targetRemote} ${branchName} ${forceFlag}`, {
|
||||
cwd: worktreePath,
|
||||
if (!result.success) {
|
||||
const statusCode = isClientError(result.error ?? '') ? 400 : 500;
|
||||
res.status(statusCode).json({
|
||||
success: false,
|
||||
error: result.error,
|
||||
diverged: result.diverged,
|
||||
hasConflicts: result.hasConflicts,
|
||||
conflictFiles: result.conflictFiles,
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
res.json({
|
||||
success: true,
|
||||
result: {
|
||||
branch: branchName,
|
||||
pushed: true,
|
||||
message: `Successfully pushed ${branchName} to ${targetRemote}`,
|
||||
branch: result.branch,
|
||||
pushed: result.pushed,
|
||||
diverged: result.diverged,
|
||||
autoResolved: result.autoResolved,
|
||||
message: result.message,
|
||||
},
|
||||
});
|
||||
} catch (error) {
|
||||
@@ -65,3 +59,15 @@ export function createPushHandler() {
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Determine whether an error message represents a client error (400)
|
||||
* vs a server error (500).
|
||||
*/
|
||||
function isClientError(errorMessage: string): boolean {
|
||||
return (
|
||||
errorMessage.includes('detached HEAD') ||
|
||||
errorMessage.includes('rejected') ||
|
||||
errorMessage.includes('diverged')
|
||||
);
|
||||
}
|
||||
|
||||
76
apps/server/src/routes/worktree/routes/set-tracking.ts
Normal file
76
apps/server/src/routes/worktree/routes/set-tracking.ts
Normal file
@@ -0,0 +1,76 @@
|
||||
/**
|
||||
* POST /set-tracking endpoint - Set the upstream tracking branch for a worktree
|
||||
*
|
||||
* Sets `git branch --set-upstream-to=<remote>/<branch>` for the current branch.
|
||||
*
|
||||
* Note: Git repository validation (isGitRepo, hasCommits) is handled by
|
||||
* the requireValidWorktree middleware in index.ts
|
||||
*/
|
||||
|
||||
import type { Request, Response } from 'express';
|
||||
import { execGitCommand } from '@automaker/git-utils';
|
||||
import { getErrorMessage, logError } from '../common.js';
|
||||
import { getCurrentBranch } from '../../../lib/git.js';
|
||||
|
||||
export function createSetTrackingHandler() {
|
||||
return async (req: Request, res: Response): Promise<void> => {
|
||||
try {
|
||||
const { worktreePath, remote, branch } = req.body as {
|
||||
worktreePath: string;
|
||||
remote: string;
|
||||
branch?: string;
|
||||
};
|
||||
|
||||
if (!worktreePath) {
|
||||
res.status(400).json({ success: false, error: 'worktreePath required' });
|
||||
return;
|
||||
}
|
||||
|
||||
if (!remote) {
|
||||
res.status(400).json({ success: false, error: 'remote required' });
|
||||
return;
|
||||
}
|
||||
|
||||
// Get current branch if not provided
|
||||
let targetBranch = branch;
|
||||
if (!targetBranch) {
|
||||
try {
|
||||
targetBranch = await getCurrentBranch(worktreePath);
|
||||
} catch (err) {
|
||||
res.status(400).json({
|
||||
success: false,
|
||||
error: `Failed to get current branch: ${getErrorMessage(err)}`,
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
if (targetBranch === 'HEAD') {
|
||||
res.status(400).json({
|
||||
success: false,
|
||||
error: 'Cannot set tracking in detached HEAD state.',
|
||||
});
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
// Set upstream tracking (pass local branch name as final arg to be explicit)
|
||||
await execGitCommand(
|
||||
['branch', '--set-upstream-to', `${remote}/${targetBranch}`, targetBranch],
|
||||
worktreePath
|
||||
);
|
||||
|
||||
res.json({
|
||||
success: true,
|
||||
result: {
|
||||
branch: targetBranch,
|
||||
remote,
|
||||
upstream: `${remote}/${targetBranch}`,
|
||||
message: `Set tracking branch to ${remote}/${targetBranch}`,
|
||||
},
|
||||
});
|
||||
} catch (error) {
|
||||
logError(error, 'Set tracking branch failed');
|
||||
res.status(500).json({ success: false, error: getErrorMessage(error) });
|
||||
}
|
||||
};
|
||||
}
|
||||
66
apps/server/src/routes/worktree/routes/sync.ts
Normal file
66
apps/server/src/routes/worktree/routes/sync.ts
Normal file
@@ -0,0 +1,66 @@
|
||||
/**
|
||||
* POST /sync endpoint - Pull then push a worktree branch
|
||||
*
|
||||
* Performs a full sync operation: pull latest from remote, then push
|
||||
* local commits. Handles divergence automatically.
|
||||
*
|
||||
* Git business logic is delegated to sync-service.ts.
|
||||
*
|
||||
* Note: Git repository validation (isGitRepo, hasCommits) is handled by
|
||||
* the requireValidWorktree middleware in index.ts
|
||||
*/
|
||||
|
||||
import type { Request, Response } from 'express';
|
||||
import { getErrorMessage, logError } from '../common.js';
|
||||
import { performSync } from '../../../services/sync-service.js';
|
||||
|
||||
export function createSyncHandler() {
|
||||
return async (req: Request, res: Response): Promise<void> => {
|
||||
try {
|
||||
const { worktreePath, remote } = req.body as {
|
||||
worktreePath: string;
|
||||
remote?: string;
|
||||
};
|
||||
|
||||
if (!worktreePath) {
|
||||
res.status(400).json({
|
||||
success: false,
|
||||
error: 'worktreePath required',
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
const result = await performSync(worktreePath, { remote });
|
||||
|
||||
if (!result.success) {
|
||||
const statusCode = result.hasConflicts ? 409 : 500;
|
||||
res.status(statusCode).json({
|
||||
success: false,
|
||||
error: result.error,
|
||||
hasConflicts: result.hasConflicts,
|
||||
conflictFiles: result.conflictFiles,
|
||||
conflictSource: result.conflictSource,
|
||||
pulled: result.pulled,
|
||||
pushed: result.pushed,
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
res.json({
|
||||
success: true,
|
||||
result: {
|
||||
branch: result.branch,
|
||||
pulled: result.pulled,
|
||||
pushed: result.pushed,
|
||||
isFastForward: result.isFastForward,
|
||||
isMerge: result.isMerge,
|
||||
autoResolved: result.autoResolved,
|
||||
message: result.message,
|
||||
},
|
||||
});
|
||||
} catch (error) {
|
||||
logError(error, 'Sync worktree failed');
|
||||
res.status(500).json({ success: false, error: getErrorMessage(error) });
|
||||
}
|
||||
};
|
||||
}
|
||||
@@ -38,6 +38,8 @@ export type {
|
||||
|
||||
const logger = createLogger('AgentExecutor');
|
||||
|
||||
const DEFAULT_MAX_TURNS = 1000;
|
||||
|
||||
export class AgentExecutor {
|
||||
private static readonly WRITE_DEBOUNCE_MS = 500;
|
||||
private static readonly STREAM_HEARTBEAT_MS = 15_000;
|
||||
@@ -99,10 +101,22 @@ export class AgentExecutor {
|
||||
workDir,
|
||||
false
|
||||
);
|
||||
const resolvedMaxTurns = sdkOptions?.maxTurns ?? DEFAULT_MAX_TURNS;
|
||||
if (sdkOptions?.maxTurns == null) {
|
||||
logger.info(
|
||||
`[execute] Feature ${featureId}: sdkOptions.maxTurns is not set, defaulting to ${resolvedMaxTurns}. ` +
|
||||
`Model: ${effectiveBareModel}`
|
||||
);
|
||||
} else {
|
||||
logger.info(
|
||||
`[execute] Feature ${featureId}: maxTurns=${resolvedMaxTurns}, model=${effectiveBareModel}`
|
||||
);
|
||||
}
|
||||
|
||||
const executeOptions: ExecuteOptions = {
|
||||
prompt: promptContent,
|
||||
model: effectiveBareModel,
|
||||
maxTurns: sdkOptions?.maxTurns,
|
||||
maxTurns: resolvedMaxTurns,
|
||||
cwd: workDir,
|
||||
allowedTools: sdkOptions?.allowedTools as string[] | undefined,
|
||||
abortController,
|
||||
@@ -279,6 +293,17 @@ export class AgentExecutor {
|
||||
throw new Error(AgentExecutor.sanitizeProviderError(msg.error));
|
||||
} else if (msg.type === 'result' && msg.subtype === 'success') scheduleWrite();
|
||||
}
|
||||
} finally {
|
||||
clearInterval(streamHeartbeat);
|
||||
if (writeTimeout) clearTimeout(writeTimeout);
|
||||
if (rawWriteTimeout) clearTimeout(rawWriteTimeout);
|
||||
|
||||
const streamElapsedMs = Date.now() - streamStartTime;
|
||||
logger.info(
|
||||
`[execute] Stream ended for feature ${featureId} after ${Math.round(streamElapsedMs / 1000)}s. ` +
|
||||
`aborted=${aborted}, specDetected=${specDetected}, responseLength=${responseText.length}`
|
||||
);
|
||||
|
||||
await writeToFile();
|
||||
if (enableRawOutput && rawOutputLines.length > 0) {
|
||||
try {
|
||||
@@ -288,10 +313,6 @@ export class AgentExecutor {
|
||||
/* ignore */
|
||||
}
|
||||
}
|
||||
} finally {
|
||||
clearInterval(streamHeartbeat);
|
||||
if (writeTimeout) clearTimeout(writeTimeout);
|
||||
if (rawWriteTimeout) clearTimeout(rawWriteTimeout);
|
||||
}
|
||||
return { responseText, specDetected, tasksCompleted, aborted };
|
||||
}
|
||||
@@ -351,8 +372,13 @@ export class AgentExecutor {
|
||||
taskPrompts.taskExecution.taskPromptTemplate,
|
||||
userFeedback
|
||||
);
|
||||
const taskMaxTurns = sdkOptions?.maxTurns ?? DEFAULT_MAX_TURNS;
|
||||
logger.info(
|
||||
`[executeTasksLoop] Feature ${featureId}, task ${task.id} (${taskIndex + 1}/${tasks.length}): ` +
|
||||
`maxTurns=${taskMaxTurns} (sdkOptions.maxTurns=${sdkOptions?.maxTurns ?? 'undefined'})`
|
||||
);
|
||||
const taskStream = provider.executeQuery(
|
||||
this.buildExecOpts(options, taskPrompt, Math.min(sdkOptions?.maxTurns ?? 100, 100))
|
||||
this.buildExecOpts(options, taskPrompt, taskMaxTurns)
|
||||
);
|
||||
let taskOutput = '',
|
||||
taskStartDetected = false,
|
||||
@@ -571,7 +597,7 @@ export class AgentExecutor {
|
||||
});
|
||||
let revText = '';
|
||||
for await (const msg of provider.executeQuery(
|
||||
this.buildExecOpts(options, revPrompt, sdkOptions?.maxTurns ?? 100)
|
||||
this.buildExecOpts(options, revPrompt, sdkOptions?.maxTurns ?? DEFAULT_MAX_TURNS)
|
||||
)) {
|
||||
if (msg.type === 'assistant' && msg.message?.content)
|
||||
for (const b of msg.message.content)
|
||||
@@ -657,7 +683,7 @@ export class AgentExecutor {
|
||||
return { responseText, tasksCompleted };
|
||||
}
|
||||
|
||||
private buildExecOpts(o: AgentExecutionOptions, prompt: string, maxTurns?: number) {
|
||||
private buildExecOpts(o: AgentExecutionOptions, prompt: string, maxTurns: number) {
|
||||
return {
|
||||
prompt,
|
||||
model: o.effectiveBareModel,
|
||||
@@ -689,7 +715,7 @@ export class AgentExecutor {
|
||||
.replace(/\{\{approvedPlan\}\}/g, planContent);
|
||||
let responseText = initialResponseText;
|
||||
for await (const msg of provider.executeQuery(
|
||||
this.buildExecOpts(options, contPrompt, options.sdkOptions?.maxTurns)
|
||||
this.buildExecOpts(options, contPrompt, options.sdkOptions?.maxTurns ?? DEFAULT_MAX_TURNS)
|
||||
)) {
|
||||
if (msg.type === 'assistant' && msg.message?.content)
|
||||
for (const b of msg.message.content) {
|
||||
|
||||
@@ -28,6 +28,7 @@ import {
|
||||
getSubagentsConfiguration,
|
||||
getCustomSubagents,
|
||||
getProviderByModelId,
|
||||
getDefaultMaxTurnsSetting,
|
||||
} from '../lib/settings-helpers.js';
|
||||
|
||||
interface Message {
|
||||
@@ -437,6 +438,9 @@ export class AgentService {
|
||||
const modelForSdk = providerResolvedModel || model;
|
||||
const sessionModelForSdk = providerResolvedModel ? undefined : session.model;
|
||||
|
||||
// Read user-configured max turns from settings
|
||||
const userMaxTurns = await getDefaultMaxTurnsSetting(this.settingsService, '[AgentService]');
|
||||
|
||||
const sdkOptions = createChatOptions({
|
||||
cwd: effectiveWorkDir,
|
||||
model: modelForSdk,
|
||||
@@ -445,6 +449,7 @@ export class AgentService {
|
||||
abortController: session.abortController!,
|
||||
autoLoadClaudeMd,
|
||||
thinkingLevel: effectiveThinkingLevel, // Pass thinking level for Claude models
|
||||
maxTurns: userMaxTurns, // User-configured max turns from settings
|
||||
mcpServers: Object.keys(mcpServers).length > 0 ? mcpServers : undefined,
|
||||
});
|
||||
|
||||
|
||||
@@ -20,8 +20,13 @@ import { resolveModelString } from '@automaker/model-resolver';
|
||||
import { createLogger, loadContextFiles, classifyError } from '@automaker/utils';
|
||||
import { getFeatureDir } from '@automaker/platform';
|
||||
import * as secureFs from '../../lib/secure-fs.js';
|
||||
import { validateWorkingDirectory } from '../../lib/sdk-options.js';
|
||||
import { getPromptCustomization, getProviderByModelId } from '../../lib/settings-helpers.js';
|
||||
import { validateWorkingDirectory, createAutoModeOptions } from '../../lib/sdk-options.js';
|
||||
import {
|
||||
getPromptCustomization,
|
||||
getProviderByModelId,
|
||||
getMCPServersFromSettings,
|
||||
getDefaultMaxTurnsSetting,
|
||||
} from '../../lib/settings-helpers.js';
|
||||
import { execGitCommand } from '@automaker/git-utils';
|
||||
import { TypedEventBus } from '../typed-event-bus.js';
|
||||
import { ConcurrencyManager } from '../concurrency-manager.js';
|
||||
@@ -234,6 +239,45 @@ export class AutoModeServiceFacade {
|
||||
}
|
||||
}
|
||||
|
||||
// Build sdkOptions with proper maxTurns and allowedTools for auto-mode.
|
||||
// Without this, maxTurns would be undefined, causing providers to use their
|
||||
// internal defaults which may be much lower than intended (e.g., Codex CLI's
|
||||
// default turn limit can cause feature runs to stop prematurely).
|
||||
const autoLoadClaudeMd = opts?.autoLoadClaudeMd ?? false;
|
||||
let mcpServers: Record<string, unknown> | undefined;
|
||||
try {
|
||||
if (settingsService) {
|
||||
const servers = await getMCPServersFromSettings(settingsService, '[AutoModeFacade]');
|
||||
if (Object.keys(servers).length > 0) {
|
||||
mcpServers = servers;
|
||||
}
|
||||
}
|
||||
} catch {
|
||||
// MCP servers are optional - continue without them
|
||||
}
|
||||
|
||||
// Read user-configured max turns from settings
|
||||
const userMaxTurns = await getDefaultMaxTurnsSetting(settingsService, '[AutoModeFacade]');
|
||||
|
||||
const sdkOpts = createAutoModeOptions({
|
||||
cwd: workDir,
|
||||
model: resolvedModel,
|
||||
systemPrompt: opts?.systemPrompt,
|
||||
abortController,
|
||||
autoLoadClaudeMd,
|
||||
thinkingLevel: opts?.thinkingLevel,
|
||||
maxTurns: userMaxTurns,
|
||||
mcpServers: mcpServers as
|
||||
| Record<string, import('@automaker/types').McpServerConfig>
|
||||
| undefined,
|
||||
});
|
||||
|
||||
logger.info(
|
||||
`[createRunAgentFn] Feature ${featureId}: model=${resolvedModel}, ` +
|
||||
`maxTurns=${sdkOpts.maxTurns}, allowedTools=${(sdkOpts.allowedTools as string[])?.length ?? 'default'}, ` +
|
||||
`provider=${provider.getName()}`
|
||||
);
|
||||
|
||||
await agentExecutor.execute(
|
||||
{
|
||||
workDir,
|
||||
@@ -254,6 +298,15 @@ export class AutoModeServiceFacade {
|
||||
effectiveBareModel,
|
||||
credentials,
|
||||
claudeCompatibleProvider,
|
||||
mcpServers,
|
||||
sdkOptions: {
|
||||
maxTurns: sdkOpts.maxTurns,
|
||||
allowedTools: sdkOpts.allowedTools as string[] | undefined,
|
||||
systemPrompt: sdkOpts.systemPrompt,
|
||||
settingSources: sdkOpts.settingSources as
|
||||
| Array<'user' | 'project' | 'local'>
|
||||
| undefined,
|
||||
},
|
||||
},
|
||||
{
|
||||
waitForApproval: (fId, projPath) => planApprovalService.waitForApproval(fId, projPath),
|
||||
@@ -702,16 +755,19 @@ export class AutoModeServiceFacade {
|
||||
}
|
||||
}
|
||||
|
||||
this.eventBus.emitAutoModeEvent('auto_mode_feature_complete', {
|
||||
featureId,
|
||||
featureName: feature?.title,
|
||||
branchName: feature?.branchName ?? null,
|
||||
passes: allPassed,
|
||||
message: allPassed
|
||||
? 'All verification checks passed'
|
||||
: `Verification failed: ${results.find((r) => !r.passed)?.check || 'Unknown'}`,
|
||||
projectPath: this.projectPath,
|
||||
});
|
||||
const runningEntryForVerify = this.concurrencyManager.getRunningFeature(featureId);
|
||||
if (runningEntryForVerify?.isAutoMode) {
|
||||
this.eventBus.emitAutoModeEvent('auto_mode_feature_complete', {
|
||||
featureId,
|
||||
featureName: feature?.title,
|
||||
branchName: feature?.branchName ?? null,
|
||||
passes: allPassed,
|
||||
message: allPassed
|
||||
? 'All verification checks passed'
|
||||
: `Verification failed: ${results.find((r) => !r.passed)?.check || 'Unknown'}`,
|
||||
projectPath: this.projectPath,
|
||||
});
|
||||
}
|
||||
|
||||
return allPassed;
|
||||
}
|
||||
@@ -761,14 +817,17 @@ export class AutoModeServiceFacade {
|
||||
await execGitCommand(['commit', '-m', commitMessage], workDir);
|
||||
const hash = await execGitCommand(['rev-parse', 'HEAD'], workDir);
|
||||
|
||||
this.eventBus.emitAutoModeEvent('auto_mode_feature_complete', {
|
||||
featureId,
|
||||
featureName: feature?.title,
|
||||
branchName: feature?.branchName ?? null,
|
||||
passes: true,
|
||||
message: `Changes committed: ${hash.trim().substring(0, 8)}`,
|
||||
projectPath: this.projectPath,
|
||||
});
|
||||
const runningEntryForCommit = this.concurrencyManager.getRunningFeature(featureId);
|
||||
if (runningEntryForCommit?.isAutoMode) {
|
||||
this.eventBus.emitAutoModeEvent('auto_mode_feature_complete', {
|
||||
featureId,
|
||||
featureName: feature?.title,
|
||||
branchName: feature?.branchName ?? null,
|
||||
passes: true,
|
||||
message: `Changes committed: ${hash.trim().substring(0, 8)}`,
|
||||
projectPath: this.projectPath,
|
||||
});
|
||||
}
|
||||
|
||||
return hash.trim();
|
||||
} catch (error) {
|
||||
@@ -851,7 +910,7 @@ export class AutoModeServiceFacade {
|
||||
if (feature) {
|
||||
title = feature.title;
|
||||
description = feature.description;
|
||||
branchName = feature.branchName;
|
||||
branchName = feature.branchName ?? undefined;
|
||||
}
|
||||
} catch {
|
||||
// Silently ignore
|
||||
@@ -1081,10 +1140,31 @@ export class AutoModeServiceFacade {
|
||||
// ===========================================================================
|
||||
|
||||
/**
|
||||
* Save execution state for recovery
|
||||
* Save execution state for recovery.
|
||||
*
|
||||
* Uses the active auto-loop config for each worktree so that the persisted
|
||||
* state reflects the real branch and maxConcurrency values rather than the
|
||||
* hard-coded fallbacks (null / DEFAULT_MAX_CONCURRENCY).
|
||||
*/
|
||||
private async saveExecutionState(): Promise<void> {
|
||||
return this.saveExecutionStateForProject(null, DEFAULT_MAX_CONCURRENCY);
|
||||
const projectWorktrees = this.autoLoopCoordinator
|
||||
.getActiveWorktrees()
|
||||
.filter((w) => w.projectPath === this.projectPath);
|
||||
|
||||
if (projectWorktrees.length === 0) {
|
||||
// No active auto loops — save with defaults as a best-effort fallback.
|
||||
return this.saveExecutionStateForProject(null, DEFAULT_MAX_CONCURRENCY);
|
||||
}
|
||||
|
||||
// Save state for every active worktree using its real config values.
|
||||
for (const { branchName } of projectWorktrees) {
|
||||
const config = this.autoLoopCoordinator.getAutoLoopConfigForProject(
|
||||
this.projectPath,
|
||||
branchName
|
||||
);
|
||||
const maxConcurrency = config?.maxConcurrency ?? DEFAULT_MAX_CONCURRENCY;
|
||||
await this.saveExecutionStateForProject(branchName, maxConcurrency);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -159,7 +159,7 @@ export class GlobalAutoModeService {
|
||||
if (feature) {
|
||||
title = feature.title;
|
||||
description = feature.description;
|
||||
branchName = feature.branchName;
|
||||
branchName = feature.branchName ?? undefined;
|
||||
}
|
||||
} catch {
|
||||
// Silently ignore
|
||||
|
||||
426
apps/server/src/services/branch-sync-service.ts
Normal file
426
apps/server/src/services/branch-sync-service.ts
Normal file
@@ -0,0 +1,426 @@
|
||||
/**
|
||||
* branch-sync-service - Sync a local base branch with its remote tracking branch
|
||||
*
|
||||
* Provides logic to detect remote tracking branches, check whether a branch
|
||||
* is checked out in any worktree, and fast-forward a local branch to match
|
||||
* its remote counterpart. Extracted from the worktree create route so
|
||||
* the git logic is decoupled from HTTP request/response handling.
|
||||
*/
|
||||
|
||||
import { createLogger, getErrorMessage } from '@automaker/utils';
|
||||
import { execGitCommand } from '../lib/git.js';
|
||||
|
||||
const logger = createLogger('BranchSyncService');
|
||||
|
||||
/** Timeout for git fetch operations (30 seconds) */
|
||||
const FETCH_TIMEOUT_MS = 30_000;
|
||||
|
||||
// ============================================================================
|
||||
// Types
|
||||
// ============================================================================
|
||||
|
||||
/**
|
||||
* Result of attempting to sync a base branch with its remote.
|
||||
*/
|
||||
export interface BaseBranchSyncResult {
|
||||
/** Whether the sync was attempted */
|
||||
attempted: boolean;
|
||||
/** Whether the sync succeeded */
|
||||
synced: boolean;
|
||||
/** Whether the ref was resolved (but not synced, e.g. remote ref, tag, or commit hash) */
|
||||
resolved?: boolean;
|
||||
/** The remote that was synced from (e.g. 'origin') */
|
||||
remote?: string;
|
||||
/** The commit hash the base branch points to after sync */
|
||||
commitHash?: string;
|
||||
/** Human-readable message about the sync result */
|
||||
message?: string;
|
||||
/** Whether the branch had diverged (local commits ahead of remote) */
|
||||
diverged?: boolean;
|
||||
/** Whether the user can proceed with a stale local copy */
|
||||
canProceedWithStale?: boolean;
|
||||
}
|
||||
|
||||
// ============================================================================
|
||||
// Helpers
|
||||
// ============================================================================
|
||||
|
||||
/**
|
||||
* Detect the remote tracking branch for a given local branch.
|
||||
*
|
||||
* @param projectPath - Path to the git repository
|
||||
* @param branchName - Local branch name to check (e.g. 'main')
|
||||
* @returns Object with remote name and remote branch, or null if no tracking branch
|
||||
*/
|
||||
export async function getTrackingBranch(
|
||||
projectPath: string,
|
||||
branchName: string
|
||||
): Promise<{ remote: string; remoteBranch: string } | null> {
|
||||
try {
|
||||
// git rev-parse --abbrev-ref <branch>@{upstream} returns e.g. "origin/main"
|
||||
const upstream = await execGitCommand(
|
||||
['rev-parse', '--abbrev-ref', `${branchName}@{upstream}`],
|
||||
projectPath
|
||||
);
|
||||
const trimmed = upstream.trim();
|
||||
if (!trimmed) return null;
|
||||
|
||||
// First, attempt to determine the remote name explicitly via git config
|
||||
// so that remotes whose names contain slashes are handled correctly.
|
||||
let remote: string | null = null;
|
||||
try {
|
||||
const configRemote = await execGitCommand(
|
||||
['config', '--get', `branch.${branchName}.remote`],
|
||||
projectPath
|
||||
);
|
||||
const configRemoteTrimmed = configRemote.trim();
|
||||
if (configRemoteTrimmed) {
|
||||
remote = configRemoteTrimmed;
|
||||
}
|
||||
} catch {
|
||||
// git config lookup failed — will fall back to string splitting below
|
||||
}
|
||||
|
||||
if (remote) {
|
||||
// Strip the known remote prefix (plus the separating '/') to get the remote branch.
|
||||
// The upstream string is expected to be "<remote>/<remoteBranch>".
|
||||
const prefix = `${remote}/`;
|
||||
if (trimmed.startsWith(prefix)) {
|
||||
return {
|
||||
remote,
|
||||
remoteBranch: trimmed.substring(prefix.length),
|
||||
};
|
||||
}
|
||||
// Upstream doesn't start with the expected prefix — fall through to split
|
||||
}
|
||||
|
||||
// Fall back: split on the FIRST slash, which favors the common case of
|
||||
// single-name remotes with slash-containing branch names (e.g.
|
||||
// "origin/feature/foo" → remote="origin", remoteBranch="feature/foo").
|
||||
// Remotes with slashes in their names are uncommon and are already handled
|
||||
// by the git-config lookup above; this fallback only runs when that lookup
|
||||
// fails, so optimizing for single-name remotes is the safer default.
|
||||
const slashIndex = trimmed.indexOf('/');
|
||||
if (slashIndex > 0) {
|
||||
return {
|
||||
remote: trimmed.substring(0, slashIndex),
|
||||
remoteBranch: trimmed.substring(slashIndex + 1),
|
||||
};
|
||||
}
|
||||
return null;
|
||||
} catch {
|
||||
// No upstream tracking branch configured
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Check whether a branch is checked out in ANY worktree (main or linked).
|
||||
* Uses `git worktree list --porcelain` to enumerate all worktrees and
|
||||
* checks if any of them has the given branch as their HEAD.
|
||||
*
|
||||
* Returns the absolute path of the worktree where the branch is checked out,
|
||||
* or null if the branch is not checked out anywhere. Callers can use the
|
||||
* returned path to run commands (e.g. `git merge`) inside the correct worktree.
|
||||
*
|
||||
* This prevents using `git update-ref` on a branch that is checked out in
|
||||
* a linked worktree, which would desync that worktree's HEAD.
|
||||
*/
|
||||
export async function isBranchCheckedOut(
|
||||
projectPath: string,
|
||||
branchName: string
|
||||
): Promise<string | null> {
|
||||
try {
|
||||
const stdout = await execGitCommand(['worktree', 'list', '--porcelain'], projectPath);
|
||||
const lines = stdout.split('\n');
|
||||
let currentWorktreePath: string | null = null;
|
||||
let currentBranch: string | null = null;
|
||||
|
||||
for (const line of lines) {
|
||||
if (line.startsWith('worktree ')) {
|
||||
currentWorktreePath = line.slice(9);
|
||||
} else if (line.startsWith('branch ')) {
|
||||
currentBranch = line.slice(7).replace('refs/heads/', '');
|
||||
} else if (line === '') {
|
||||
// End of a worktree entry — check for match, then reset for the next
|
||||
if (currentBranch === branchName && currentWorktreePath) {
|
||||
return currentWorktreePath;
|
||||
}
|
||||
currentWorktreePath = null;
|
||||
currentBranch = null;
|
||||
}
|
||||
}
|
||||
|
||||
// Check the last entry (if output doesn't end with a blank line)
|
||||
if (currentBranch === branchName && currentWorktreePath) {
|
||||
return currentWorktreePath;
|
||||
}
|
||||
|
||||
return null;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Build a BaseBranchSyncResult for cases where we proceed with a stale local copy.
|
||||
* Extracts the repeated pattern of getting the short commit hash with a fallback.
|
||||
*/
|
||||
export async function buildStaleResult(
|
||||
projectPath: string,
|
||||
branchName: string,
|
||||
remote: string | undefined,
|
||||
message: string,
|
||||
extra?: Partial<BaseBranchSyncResult>
|
||||
): Promise<BaseBranchSyncResult> {
|
||||
let commitHash: string | undefined;
|
||||
try {
|
||||
const hash = await execGitCommand(['rev-parse', '--short', branchName], projectPath);
|
||||
commitHash = hash.trim();
|
||||
} catch {
|
||||
/* ignore — commit hash is non-critical */
|
||||
}
|
||||
return {
|
||||
attempted: true,
|
||||
synced: false,
|
||||
remote,
|
||||
commitHash,
|
||||
message,
|
||||
canProceedWithStale: true,
|
||||
...extra,
|
||||
};
|
||||
}
|
||||
|
||||
// ============================================================================
|
||||
// Main Sync Function
|
||||
// ============================================================================
|
||||
|
||||
/**
|
||||
* Sync a local base branch with its remote tracking branch using fast-forward only.
|
||||
*
|
||||
* This function:
|
||||
* 1. Detects the remote tracking branch for the given local branch
|
||||
* 2. Fetches latest from that remote (unless skipFetch is true)
|
||||
* 3. Attempts a fast-forward-only update of the local branch
|
||||
* 4. If the branch has diverged, reports the divergence and allows proceeding with stale copy
|
||||
* 5. If no remote tracking branch exists, skips silently
|
||||
*
|
||||
* @param projectPath - Path to the git repository
|
||||
* @param branchName - The local branch name to sync (e.g. 'main')
|
||||
* @param skipFetch - When true, skip the internal git fetch (caller has already fetched)
|
||||
* @returns Sync result with status information
|
||||
*/
|
||||
export async function syncBaseBranch(
|
||||
projectPath: string,
|
||||
branchName: string,
|
||||
skipFetch = false
|
||||
): Promise<BaseBranchSyncResult> {
|
||||
// Check if the branch exists as a local branch (under refs/heads/).
|
||||
// This correctly handles branch names containing slashes (e.g. "feature/abc",
|
||||
// "fix/issue-123") which are valid local branch names, not remote refs.
|
||||
let existsLocally = false;
|
||||
try {
|
||||
await execGitCommand(['rev-parse', '--verify', `refs/heads/${branchName}`], projectPath);
|
||||
existsLocally = true;
|
||||
} catch {
|
||||
existsLocally = false;
|
||||
}
|
||||
|
||||
if (!existsLocally) {
|
||||
// Not a local branch — check if it's a valid ref (remote ref, tag, or commit hash).
|
||||
// No synchronization is performed here; we only resolve the ref to a commit hash.
|
||||
try {
|
||||
const commitHash = await execGitCommand(['rev-parse', '--short', branchName], projectPath);
|
||||
return {
|
||||
attempted: false,
|
||||
synced: false,
|
||||
resolved: true,
|
||||
commitHash: commitHash.trim(),
|
||||
message: `Ref '${branchName}' resolved (not a local branch; no sync performed)`,
|
||||
};
|
||||
} catch {
|
||||
return {
|
||||
attempted: false,
|
||||
synced: false,
|
||||
message: `Ref '${branchName}' not found`,
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
// Detect remote tracking branch
|
||||
const tracking = await getTrackingBranch(projectPath, branchName);
|
||||
if (!tracking) {
|
||||
// No remote tracking branch — skip silently
|
||||
logger.info(`Branch '${branchName}' has no remote tracking branch, skipping sync`);
|
||||
try {
|
||||
const commitHash = await execGitCommand(['rev-parse', '--short', branchName], projectPath);
|
||||
return {
|
||||
attempted: false,
|
||||
synced: false,
|
||||
commitHash: commitHash.trim(),
|
||||
message: `Branch '${branchName}' has no remote tracking branch`,
|
||||
};
|
||||
} catch {
|
||||
return {
|
||||
attempted: false,
|
||||
synced: false,
|
||||
message: `Branch '${branchName}' has no remote tracking branch`,
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
logger.info(
|
||||
`Syncing base branch '${branchName}' from ${tracking.remote}/${tracking.remoteBranch}`
|
||||
);
|
||||
|
||||
// Fetch the specific remote unless the caller has already performed a fetch
|
||||
// (e.g. via `git fetch --all`) and passed skipFetch=true to avoid redundant work.
|
||||
if (!skipFetch) {
|
||||
try {
|
||||
const fetchController = new AbortController();
|
||||
const fetchTimer = setTimeout(() => fetchController.abort(), FETCH_TIMEOUT_MS);
|
||||
try {
|
||||
await execGitCommand(
|
||||
['fetch', tracking.remote, tracking.remoteBranch, '--quiet'],
|
||||
projectPath,
|
||||
undefined,
|
||||
fetchController
|
||||
);
|
||||
} finally {
|
||||
clearTimeout(fetchTimer);
|
||||
}
|
||||
} catch (fetchErr) {
|
||||
// Fetch failed — network error, auth error, etc.
|
||||
// Allow proceeding with stale local copy
|
||||
const errMsg = getErrorMessage(fetchErr);
|
||||
logger.warn(`Failed to fetch ${tracking.remote}/${tracking.remoteBranch}: ${errMsg}`);
|
||||
return buildStaleResult(
|
||||
projectPath,
|
||||
branchName,
|
||||
tracking.remote,
|
||||
`Failed to fetch from remote: ${errMsg}. Proceeding with local copy.`
|
||||
);
|
||||
}
|
||||
} else {
|
||||
logger.info(`Skipping fetch for '${branchName}' (caller already fetched from remotes)`);
|
||||
}
|
||||
|
||||
// Check if the local branch is behind, ahead, or diverged from the remote
|
||||
const remoteRef = `${tracking.remote}/${tracking.remoteBranch}`;
|
||||
try {
|
||||
// Count commits ahead and behind
|
||||
const revListOutput = await execGitCommand(
|
||||
['rev-list', '--left-right', '--count', `${branchName}...${remoteRef}`],
|
||||
projectPath
|
||||
);
|
||||
const parts = revListOutput.trim().split(/\s+/);
|
||||
const ahead = parseInt(parts[0], 10) || 0;
|
||||
const behind = parseInt(parts[1], 10) || 0;
|
||||
|
||||
if (ahead === 0 && behind === 0) {
|
||||
// Already up to date
|
||||
const commitHash = await execGitCommand(['rev-parse', '--short', branchName], projectPath);
|
||||
logger.info(`Branch '${branchName}' is already up to date with ${remoteRef}`);
|
||||
return {
|
||||
attempted: true,
|
||||
synced: true,
|
||||
remote: tracking.remote,
|
||||
commitHash: commitHash.trim(),
|
||||
message: `Branch '${branchName}' is already up to date`,
|
||||
};
|
||||
}
|
||||
|
||||
if (ahead > 0 && behind > 0) {
|
||||
// Branch has diverged — cannot fast-forward
|
||||
logger.warn(
|
||||
`Branch '${branchName}' has diverged from ${remoteRef} (${ahead} ahead, ${behind} behind)`
|
||||
);
|
||||
return buildStaleResult(
|
||||
projectPath,
|
||||
branchName,
|
||||
tracking.remote,
|
||||
`Branch '${branchName}' has diverged from ${remoteRef} (${ahead} commit(s) ahead, ${behind} behind). Using local copy to avoid overwriting local commits.`,
|
||||
{ diverged: true }
|
||||
);
|
||||
}
|
||||
|
||||
if (ahead > 0 && behind === 0) {
|
||||
// Local is ahead — nothing to pull, already has everything from remote plus more
|
||||
const commitHash = await execGitCommand(['rev-parse', '--short', branchName], projectPath);
|
||||
logger.info(`Branch '${branchName}' is ${ahead} commit(s) ahead of ${remoteRef}`);
|
||||
return {
|
||||
attempted: true,
|
||||
synced: true,
|
||||
remote: tracking.remote,
|
||||
commitHash: commitHash.trim(),
|
||||
message: `Branch '${branchName}' is ${ahead} commit(s) ahead of remote`,
|
||||
};
|
||||
}
|
||||
|
||||
// behind > 0 && ahead === 0 — can fast-forward
|
||||
logger.info(
|
||||
`Branch '${branchName}' is ${behind} commit(s) behind ${remoteRef}, fast-forwarding`
|
||||
);
|
||||
|
||||
// Determine whether the branch is currently checked out (returns the
|
||||
// worktree path where it is checked out, or null if not checked out)
|
||||
const worktreePath = await isBranchCheckedOut(projectPath, branchName);
|
||||
|
||||
if (worktreePath) {
|
||||
// Branch is checked out in a worktree — use git merge --ff-only
|
||||
// Run the merge inside the worktree that has the branch checked out
|
||||
try {
|
||||
await execGitCommand(['merge', '--ff-only', remoteRef], worktreePath);
|
||||
} catch (mergeErr) {
|
||||
const errMsg = getErrorMessage(mergeErr);
|
||||
logger.warn(`Fast-forward merge failed for '${branchName}': ${errMsg}`);
|
||||
return buildStaleResult(
|
||||
projectPath,
|
||||
branchName,
|
||||
tracking.remote,
|
||||
`Fast-forward merge failed: ${errMsg}. Proceeding with local copy.`
|
||||
);
|
||||
}
|
||||
} else {
|
||||
// Branch is NOT checked out — use git update-ref to fast-forward without checkout
|
||||
// This is safe because we already verified the branch is strictly behind (ahead === 0)
|
||||
try {
|
||||
const remoteCommit = await execGitCommand(['rev-parse', remoteRef], projectPath);
|
||||
await execGitCommand(
|
||||
['update-ref', `refs/heads/${branchName}`, remoteCommit.trim()],
|
||||
projectPath
|
||||
);
|
||||
} catch (updateErr) {
|
||||
const errMsg = getErrorMessage(updateErr);
|
||||
logger.warn(`update-ref failed for '${branchName}': ${errMsg}`);
|
||||
return buildStaleResult(
|
||||
projectPath,
|
||||
branchName,
|
||||
tracking.remote,
|
||||
`Failed to fast-forward branch: ${errMsg}. Proceeding with local copy.`
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
// Successfully fast-forwarded
|
||||
const commitHash = await execGitCommand(['rev-parse', '--short', branchName], projectPath);
|
||||
logger.info(`Successfully synced '${branchName}' to ${commitHash.trim()} from ${remoteRef}`);
|
||||
return {
|
||||
attempted: true,
|
||||
synced: true,
|
||||
remote: tracking.remote,
|
||||
commitHash: commitHash.trim(),
|
||||
message: `Fast-forwarded '${branchName}' by ${behind} commit(s) from ${remoteRef}`,
|
||||
};
|
||||
} catch (err) {
|
||||
// Unexpected error during rev-list or merge — proceed with stale
|
||||
const errMsg = getErrorMessage(err);
|
||||
logger.warn(`Unexpected error syncing '${branchName}': ${errMsg}`);
|
||||
return buildStaleResult(
|
||||
projectPath,
|
||||
branchName,
|
||||
tracking.remote,
|
||||
`Sync failed: ${errMsg}. Proceeding with local copy.`
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -19,6 +19,10 @@ const logger = createLogger('DevServerService');
|
||||
// Maximum scrollback buffer size (characters) - matches TerminalService pattern
|
||||
const MAX_SCROLLBACK_SIZE = 50000; // ~50KB per dev server
|
||||
|
||||
// Timeout (ms) before falling back to the allocated port if URL detection hasn't succeeded.
|
||||
// This handles cases where the dev server output format is not recognized by any pattern.
|
||||
const URL_DETECTION_TIMEOUT_MS = 30_000;
|
||||
|
||||
// URL patterns for detecting full URLs from dev server output.
|
||||
// Defined once at module level to avoid reallocation on every call to detectUrlFromOutput.
|
||||
// Ordered from most specific (framework-specific) to least specific.
|
||||
@@ -88,6 +92,8 @@ const OUTPUT_BATCH_SIZE = 4096; // Smaller batches for lower latency
|
||||
|
||||
export interface DevServerInfo {
|
||||
worktreePath: string;
|
||||
/** The port originally reserved by findAvailablePort() – never mutated after startDevServer sets it */
|
||||
allocatedPort: number;
|
||||
port: number;
|
||||
url: string;
|
||||
process: ChildProcess | null;
|
||||
@@ -102,6 +108,8 @@ export interface DevServerInfo {
|
||||
stopping: boolean;
|
||||
// Flag to indicate if URL has been detected from output
|
||||
urlDetected: boolean;
|
||||
// Timer for URL detection timeout fallback
|
||||
urlDetectionTimeout: NodeJS.Timeout | null;
|
||||
}
|
||||
|
||||
// Port allocation starts at 3001 to avoid conflicts with common dev ports
|
||||
@@ -124,6 +132,32 @@ class DevServerService {
|
||||
this.emitter = emitter;
|
||||
}
|
||||
|
||||
/**
|
||||
* Prune a stale server entry whose process has exited without cleanup.
|
||||
* Clears any pending timers, removes the port from allocatedPorts, deletes
|
||||
* the entry from runningServers, and emits the "dev-server:stopped" event
|
||||
* so all callers consistently notify the frontend when pruning entries.
|
||||
*
|
||||
* @param worktreePath - The key used in runningServers
|
||||
* @param server - The DevServerInfo entry to prune
|
||||
*/
|
||||
private pruneStaleServer(worktreePath: string, server: DevServerInfo): void {
|
||||
if (server.flushTimeout) clearTimeout(server.flushTimeout);
|
||||
if (server.urlDetectionTimeout) clearTimeout(server.urlDetectionTimeout);
|
||||
// Use allocatedPort (immutable) to free the reserved slot; server.port may have
|
||||
// been mutated by detectUrlFromOutput to reflect the actual detected port.
|
||||
this.allocatedPorts.delete(server.allocatedPort);
|
||||
this.runningServers.delete(worktreePath);
|
||||
if (this.emitter) {
|
||||
this.emitter.emit('dev-server:stopped', {
|
||||
worktreePath,
|
||||
port: server.port, // Report the externally-visible (detected) port
|
||||
exitCode: server.process?.exitCode ?? null,
|
||||
timestamp: new Date().toISOString(),
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Append data to scrollback buffer with size limit enforcement
|
||||
* Evicts oldest data when buffer exceeds MAX_SCROLLBACK_SIZE
|
||||
@@ -253,6 +287,12 @@ class DevServerService {
|
||||
server.url = detectedUrl;
|
||||
server.urlDetected = true;
|
||||
|
||||
// Clear the URL detection timeout since we found the URL
|
||||
if (server.urlDetectionTimeout) {
|
||||
clearTimeout(server.urlDetectionTimeout);
|
||||
server.urlDetectionTimeout = null;
|
||||
}
|
||||
|
||||
// Update the port to match the detected URL's actual port
|
||||
const detectedPort = this.extractPortFromUrl(detectedUrl);
|
||||
if (detectedPort && detectedPort !== server.port) {
|
||||
@@ -291,6 +331,12 @@ class DevServerService {
|
||||
server.url = detectedUrl;
|
||||
server.urlDetected = true;
|
||||
|
||||
// Clear the URL detection timeout since we found the port
|
||||
if (server.urlDetectionTimeout) {
|
||||
clearTimeout(server.urlDetectionTimeout);
|
||||
server.urlDetectionTimeout = null;
|
||||
}
|
||||
|
||||
if (detectedPort !== server.port) {
|
||||
logger.info(
|
||||
`Port mismatch: allocated ${server.port}, detected ${detectedPort} from ${description}`
|
||||
@@ -660,6 +706,7 @@ class DevServerService {
|
||||
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,
|
||||
@@ -669,6 +716,7 @@ class DevServerService {
|
||||
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
|
||||
@@ -692,18 +740,24 @@ class DevServerService {
|
||||
serverInfo.flushTimeout = null;
|
||||
}
|
||||
|
||||
// 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,
|
||||
port,
|
||||
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(port);
|
||||
this.allocatedPorts.delete(serverInfo.allocatedPort);
|
||||
this.runningServers.delete(worktreePath);
|
||||
};
|
||||
|
||||
@@ -749,6 +803,43 @@ class DevServerService {
|
||||
});
|
||||
}
|
||||
|
||||
// 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;
|
||||
|
||||
// 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`);
|
||||
this.detectUrlFromOutput(serverInfo, serverInfo.scrollbackBuffer);
|
||||
|
||||
// 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;
|
||||
|
||||
if (this.emitter) {
|
||||
this.emitter.emit('dev-server:url-detected', {
|
||||
worktreePath,
|
||||
url: fallbackUrl,
|
||||
port,
|
||||
timestamp: new Date().toISOString(),
|
||||
});
|
||||
}
|
||||
}
|
||||
}, URL_DETECTION_TIMEOUT_MS);
|
||||
|
||||
return {
|
||||
success: true,
|
||||
result: {
|
||||
@@ -794,6 +885,12 @@ class DevServerService {
|
||||
server.flushTimeout = null;
|
||||
}
|
||||
|
||||
// Clean up URL detection timeout
|
||||
if (server.urlDetectionTimeout) {
|
||||
clearTimeout(server.urlDetectionTimeout);
|
||||
server.urlDetectionTimeout = null;
|
||||
}
|
||||
|
||||
// Clear any pending output buffer
|
||||
server.outputBuffer = '';
|
||||
|
||||
@@ -812,8 +909,10 @@ class DevServerService {
|
||||
server.process.kill('SIGTERM');
|
||||
}
|
||||
|
||||
// Free the port
|
||||
this.allocatedPorts.delete(server.port);
|
||||
// Free the originally-reserved port slot (allocatedPort is immutable and always
|
||||
// matches what was added to allocatedPorts in startDevServer; server.port may
|
||||
// have been updated by detectUrlFromOutput to the actual detected port).
|
||||
this.allocatedPorts.delete(server.allocatedPort);
|
||||
this.runningServers.delete(worktreePath);
|
||||
|
||||
return {
|
||||
@@ -827,6 +926,7 @@ class DevServerService {
|
||||
|
||||
/**
|
||||
* List all running dev servers
|
||||
* Also verifies that each server's process is still alive, removing stale entries
|
||||
*/
|
||||
listDevServers(): {
|
||||
success: boolean;
|
||||
@@ -836,14 +936,37 @@ class DevServerService {
|
||||
port: number;
|
||||
url: string;
|
||||
urlDetected: boolean;
|
||||
startedAt: string;
|
||||
}>;
|
||||
};
|
||||
} {
|
||||
// Prune any servers whose process has died without us being notified
|
||||
// This handles edge cases where the process exited but the 'exit' event was missed
|
||||
const stalePaths: string[] = [];
|
||||
for (const [worktreePath, server] of this.runningServers) {
|
||||
// Check if exitCode is a number (not null/undefined) - indicates process has exited
|
||||
if (server.process && typeof server.process.exitCode === 'number') {
|
||||
logger.info(
|
||||
`Pruning stale server entry for ${worktreePath} (process exited with code ${server.process.exitCode})`
|
||||
);
|
||||
stalePaths.push(worktreePath);
|
||||
}
|
||||
}
|
||||
for (const stalePath of stalePaths) {
|
||||
const server = this.runningServers.get(stalePath);
|
||||
if (server) {
|
||||
// Delegate to the shared helper so timers, ports, and the stopped event
|
||||
// are all handled consistently with isRunning and getServerInfo.
|
||||
this.pruneStaleServer(stalePath, server);
|
||||
}
|
||||
}
|
||||
|
||||
const servers = Array.from(this.runningServers.values()).map((s) => ({
|
||||
worktreePath: s.worktreePath,
|
||||
port: s.port,
|
||||
url: s.url,
|
||||
urlDetected: s.urlDetected,
|
||||
startedAt: s.startedAt.toISOString(),
|
||||
}));
|
||||
|
||||
return {
|
||||
@@ -853,17 +976,33 @@ class DevServerService {
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if a worktree has a running dev server
|
||||
* Check if a worktree has a running dev server.
|
||||
* Also prunes stale entries where the process has exited.
|
||||
*/
|
||||
isRunning(worktreePath: string): boolean {
|
||||
return this.runningServers.has(worktreePath);
|
||||
const server = this.runningServers.get(worktreePath);
|
||||
if (!server) return false;
|
||||
// Prune stale entry if the process has exited
|
||||
if (server.process && typeof server.process.exitCode === 'number') {
|
||||
this.pruneStaleServer(worktreePath, server);
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get info for a specific worktree's dev server
|
||||
* Get info for a specific worktree's dev server.
|
||||
* Also prunes stale entries where the process has exited.
|
||||
*/
|
||||
getServerInfo(worktreePath: string): DevServerInfo | undefined {
|
||||
return this.runningServers.get(worktreePath);
|
||||
const server = this.runningServers.get(worktreePath);
|
||||
if (!server) return undefined;
|
||||
// Prune stale entry if the process has exited
|
||||
if (server.process && typeof server.process.exitCode === 'number') {
|
||||
this.pruneStaleServer(worktreePath, server);
|
||||
return undefined;
|
||||
}
|
||||
return server;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -891,6 +1030,15 @@ class DevServerService {
|
||||
};
|
||||
}
|
||||
|
||||
// Prune stale entry if the process has been killed or has exited
|
||||
if (server.process && (server.process.killed || server.process.exitCode != null)) {
|
||||
this.pruneStaleServer(worktreePath, server);
|
||||
return {
|
||||
success: false,
|
||||
error: `No dev server running for worktree: ${worktreePath}`,
|
||||
};
|
||||
}
|
||||
|
||||
return {
|
||||
success: true,
|
||||
result: {
|
||||
|
||||
@@ -170,13 +170,15 @@ export class EventHookService {
|
||||
|
||||
// Build context for variable substitution
|
||||
// Use loaded featureName (from feature.title) or fall back to payload.featureName
|
||||
// Only populate error/errorType for error triggers - don't leak success messages into error fields
|
||||
const isErrorTrigger = trigger === 'feature_error' || trigger === 'auto_mode_error';
|
||||
const context: HookContext = {
|
||||
featureId: payload.featureId,
|
||||
featureName: featureName || payload.featureName,
|
||||
projectPath: payload.projectPath,
|
||||
projectName: payload.projectPath ? this.extractProjectName(payload.projectPath) : undefined,
|
||||
error: payload.error || payload.message,
|
||||
errorType: payload.errorType,
|
||||
error: isErrorTrigger ? payload.error || payload.message : undefined,
|
||||
errorType: isErrorTrigger ? payload.errorType : undefined,
|
||||
timestamp: new Date().toISOString(),
|
||||
eventType: trigger,
|
||||
};
|
||||
|
||||
@@ -441,28 +441,32 @@ Please continue from where you left off and complete all remaining tasks. Use th
|
||||
if (hasIncompleteTasks)
|
||||
completionMessage += ` (${completedTasks}/${totalTasks} tasks completed)`;
|
||||
|
||||
this.eventBus.emitAutoModeEvent('auto_mode_feature_complete', {
|
||||
featureId,
|
||||
featureName: feature.title,
|
||||
branchName: feature.branchName ?? null,
|
||||
passes: true,
|
||||
message: completionMessage,
|
||||
projectPath,
|
||||
model: tempRunningFeature.model,
|
||||
provider: tempRunningFeature.provider,
|
||||
});
|
||||
if (isAutoMode) {
|
||||
this.eventBus.emitAutoModeEvent('auto_mode_feature_complete', {
|
||||
featureId,
|
||||
featureName: feature.title,
|
||||
branchName: feature.branchName ?? null,
|
||||
passes: true,
|
||||
message: completionMessage,
|
||||
projectPath,
|
||||
model: tempRunningFeature.model,
|
||||
provider: tempRunningFeature.provider,
|
||||
});
|
||||
}
|
||||
} catch (error) {
|
||||
const errorInfo = classifyError(error);
|
||||
if (errorInfo.isAbort) {
|
||||
await this.updateFeatureStatusFn(projectPath, featureId, 'interrupted');
|
||||
this.eventBus.emitAutoModeEvent('auto_mode_feature_complete', {
|
||||
featureId,
|
||||
featureName: feature?.title,
|
||||
branchName: feature?.branchName ?? null,
|
||||
passes: false,
|
||||
message: 'Feature stopped by user',
|
||||
projectPath,
|
||||
});
|
||||
if (isAutoMode) {
|
||||
this.eventBus.emitAutoModeEvent('auto_mode_feature_complete', {
|
||||
featureId,
|
||||
featureName: feature?.title,
|
||||
branchName: feature?.branchName ?? null,
|
||||
passes: false,
|
||||
message: 'Feature stopped by user',
|
||||
projectPath,
|
||||
});
|
||||
}
|
||||
} else {
|
||||
logger.error(`Feature ${featureId} failed:`, error);
|
||||
await this.updateFeatureStatusFn(projectPath, featureId, 'backlog');
|
||||
|
||||
103
apps/server/src/services/github-pr-comment.service.ts
Normal file
103
apps/server/src/services/github-pr-comment.service.ts
Normal file
@@ -0,0 +1,103 @@
|
||||
/**
|
||||
* GitHub PR Comment Service
|
||||
*
|
||||
* Domain logic for resolving/unresolving PR review threads via the
|
||||
* GitHub GraphQL API. Extracted from the route handler so the route
|
||||
* only deals with request/response plumbing.
|
||||
*/
|
||||
|
||||
import { spawn } from 'child_process';
|
||||
import { execEnv } from '../lib/exec-utils.js';
|
||||
|
||||
/** Timeout for GitHub GraphQL API requests in milliseconds */
|
||||
const GITHUB_API_TIMEOUT_MS = 30000;
|
||||
|
||||
interface GraphQLMutationResponse {
|
||||
data?: {
|
||||
resolveReviewThread?: {
|
||||
thread?: { isResolved: boolean; id: string } | null;
|
||||
} | null;
|
||||
unresolveReviewThread?: {
|
||||
thread?: { isResolved: boolean; id: string } | null;
|
||||
} | null;
|
||||
};
|
||||
errors?: Array<{ message: string }>;
|
||||
}
|
||||
|
||||
/**
|
||||
* Execute a GraphQL mutation to resolve or unresolve a review thread.
|
||||
*/
|
||||
export async function executeReviewThreadMutation(
|
||||
projectPath: string,
|
||||
threadId: string,
|
||||
resolve: boolean
|
||||
): Promise<{ isResolved: boolean }> {
|
||||
const mutationName = resolve ? 'resolveReviewThread' : 'unresolveReviewThread';
|
||||
|
||||
const mutation = `
|
||||
mutation ${resolve ? 'ResolveThread' : 'UnresolveThread'}($threadId: ID!) {
|
||||
${mutationName}(input: { threadId: $threadId }) {
|
||||
thread {
|
||||
id
|
||||
isResolved
|
||||
}
|
||||
}
|
||||
}`;
|
||||
|
||||
const variables = { threadId };
|
||||
const requestBody = JSON.stringify({ query: mutation, variables });
|
||||
|
||||
// Declare timeoutId before registering the error handler to avoid TDZ confusion
|
||||
let timeoutId: NodeJS.Timeout | undefined;
|
||||
|
||||
const response = await new Promise<GraphQLMutationResponse>((res, rej) => {
|
||||
const gh = spawn('gh', ['api', 'graphql', '--input', '-'], {
|
||||
cwd: projectPath,
|
||||
env: execEnv,
|
||||
});
|
||||
|
||||
gh.on('error', (err) => {
|
||||
clearTimeout(timeoutId);
|
||||
rej(err);
|
||||
});
|
||||
|
||||
timeoutId = setTimeout(() => {
|
||||
gh.kill();
|
||||
rej(new Error('GitHub GraphQL API request timed out'));
|
||||
}, GITHUB_API_TIMEOUT_MS);
|
||||
|
||||
let stdout = '';
|
||||
let stderr = '';
|
||||
gh.stdout.on('data', (data: Buffer) => (stdout += data.toString()));
|
||||
gh.stderr.on('data', (data: Buffer) => (stderr += data.toString()));
|
||||
|
||||
gh.on('close', (code) => {
|
||||
clearTimeout(timeoutId);
|
||||
if (code !== 0) {
|
||||
return rej(new Error(`gh process exited with code ${code}: ${stderr}`));
|
||||
}
|
||||
try {
|
||||
res(JSON.parse(stdout));
|
||||
} catch (e) {
|
||||
rej(e);
|
||||
}
|
||||
});
|
||||
|
||||
gh.stdin.write(requestBody);
|
||||
gh.stdin.end();
|
||||
});
|
||||
|
||||
if (response.errors && response.errors.length > 0) {
|
||||
throw new Error(response.errors[0].message);
|
||||
}
|
||||
|
||||
const threadData = resolve
|
||||
? response.data?.resolveReviewThread?.thread
|
||||
: response.data?.unresolveReviewThread?.thread;
|
||||
|
||||
if (!threadData) {
|
||||
throw new Error('No thread data returned from GitHub API');
|
||||
}
|
||||
|
||||
return { isResolved: threadData.isResolved };
|
||||
}
|
||||
@@ -226,14 +226,17 @@ export class PipelineOrchestrator {
|
||||
logger.warn(`Step ${pipelineInfo.stepId} no longer exists, completing feature`);
|
||||
const finalStatus = feature.skipTests ? 'waiting_approval' : 'verified';
|
||||
await this.updateFeatureStatusFn(projectPath, featureId, finalStatus);
|
||||
this.eventBus.emitAutoModeEvent('auto_mode_feature_complete', {
|
||||
featureId,
|
||||
featureName: feature.title,
|
||||
branchName: feature.branchName ?? null,
|
||||
passes: true,
|
||||
message: 'Pipeline step no longer exists',
|
||||
projectPath,
|
||||
});
|
||||
const runningEntryForStep = this.concurrencyManager.getRunningFeature(featureId);
|
||||
if (runningEntryForStep?.isAutoMode) {
|
||||
this.eventBus.emitAutoModeEvent('auto_mode_feature_complete', {
|
||||
featureId,
|
||||
featureName: feature.title,
|
||||
branchName: feature.branchName ?? null,
|
||||
passes: true,
|
||||
message: 'Pipeline step no longer exists',
|
||||
projectPath,
|
||||
});
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -272,14 +275,17 @@ export class PipelineOrchestrator {
|
||||
);
|
||||
if (!pipelineService.isPipelineStatus(nextStatus)) {
|
||||
await this.updateFeatureStatusFn(projectPath, featureId, nextStatus);
|
||||
this.eventBus.emitAutoModeEvent('auto_mode_feature_complete', {
|
||||
featureId,
|
||||
featureName: feature.title,
|
||||
branchName: feature.branchName ?? null,
|
||||
passes: true,
|
||||
message: 'Pipeline completed (remaining steps excluded)',
|
||||
projectPath,
|
||||
});
|
||||
const runningEntryForExcluded = this.concurrencyManager.getRunningFeature(featureId);
|
||||
if (runningEntryForExcluded?.isAutoMode) {
|
||||
this.eventBus.emitAutoModeEvent('auto_mode_feature_complete', {
|
||||
featureId,
|
||||
featureName: feature.title,
|
||||
branchName: feature.branchName ?? null,
|
||||
passes: true,
|
||||
message: 'Pipeline completed (remaining steps excluded)',
|
||||
projectPath,
|
||||
});
|
||||
}
|
||||
return;
|
||||
}
|
||||
const nextStepId = pipelineService.getStepIdFromStatus(nextStatus);
|
||||
@@ -294,14 +300,17 @@ export class PipelineOrchestrator {
|
||||
if (stepsToExecute.length === 0) {
|
||||
const finalStatus = feature.skipTests ? 'waiting_approval' : 'verified';
|
||||
await this.updateFeatureStatusFn(projectPath, featureId, finalStatus);
|
||||
this.eventBus.emitAutoModeEvent('auto_mode_feature_complete', {
|
||||
featureId,
|
||||
featureName: feature.title,
|
||||
branchName: feature.branchName ?? null,
|
||||
passes: true,
|
||||
message: 'Pipeline completed (all steps excluded)',
|
||||
projectPath,
|
||||
});
|
||||
const runningEntryForAllExcluded = this.concurrencyManager.getRunningFeature(featureId);
|
||||
if (runningEntryForAllExcluded?.isAutoMode) {
|
||||
this.eventBus.emitAutoModeEvent('auto_mode_feature_complete', {
|
||||
featureId,
|
||||
featureName: feature.title,
|
||||
branchName: feature.branchName ?? null,
|
||||
passes: true,
|
||||
message: 'Pipeline completed (all steps excluded)',
|
||||
projectPath,
|
||||
});
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -370,25 +379,29 @@ export class PipelineOrchestrator {
|
||||
await this.updateFeatureStatusFn(projectPath, featureId, finalStatus);
|
||||
}
|
||||
logger.info(`Pipeline resume completed for feature ${featureId}`);
|
||||
this.eventBus.emitAutoModeEvent('auto_mode_feature_complete', {
|
||||
featureId,
|
||||
featureName: feature.title,
|
||||
branchName: feature.branchName ?? null,
|
||||
passes: true,
|
||||
message: 'Pipeline resumed successfully',
|
||||
projectPath,
|
||||
});
|
||||
} catch (error) {
|
||||
const errorInfo = classifyError(error);
|
||||
if (errorInfo.isAbort) {
|
||||
if (runningEntry.isAutoMode) {
|
||||
this.eventBus.emitAutoModeEvent('auto_mode_feature_complete', {
|
||||
featureId,
|
||||
featureName: feature.title,
|
||||
branchName: feature.branchName ?? null,
|
||||
passes: false,
|
||||
message: 'Pipeline stopped by user',
|
||||
passes: true,
|
||||
message: 'Pipeline resumed successfully',
|
||||
projectPath,
|
||||
});
|
||||
}
|
||||
} catch (error) {
|
||||
const errorInfo = classifyError(error);
|
||||
if (errorInfo.isAbort) {
|
||||
if (runningEntry.isAutoMode) {
|
||||
this.eventBus.emitAutoModeEvent('auto_mode_feature_complete', {
|
||||
featureId,
|
||||
featureName: feature.title,
|
||||
branchName: feature.branchName ?? null,
|
||||
passes: false,
|
||||
message: 'Pipeline stopped by user',
|
||||
projectPath,
|
||||
});
|
||||
}
|
||||
} else {
|
||||
logger.error(`Pipeline resume failed for ${featureId}:`, error);
|
||||
await this.updateFeatureStatusFn(projectPath, featureId, 'backlog');
|
||||
@@ -537,14 +550,17 @@ export class PipelineOrchestrator {
|
||||
}
|
||||
|
||||
logger.info(`Auto-merge successful for feature ${featureId}`);
|
||||
this.eventBus.emitAutoModeEvent('auto_mode_feature_complete', {
|
||||
featureId,
|
||||
featureName: feature.title,
|
||||
branchName,
|
||||
passes: true,
|
||||
message: 'Pipeline completed and merged',
|
||||
projectPath,
|
||||
});
|
||||
const runningEntryForMerge = this.concurrencyManager.getRunningFeature(featureId);
|
||||
if (runningEntryForMerge?.isAutoMode) {
|
||||
this.eventBus.emitAutoModeEvent('auto_mode_feature_complete', {
|
||||
featureId,
|
||||
featureName: feature.title,
|
||||
branchName,
|
||||
passes: true,
|
||||
message: 'Pipeline completed and merged',
|
||||
projectPath,
|
||||
});
|
||||
}
|
||||
return { success: true };
|
||||
} catch (error) {
|
||||
logger.error(`Merge failed for ${featureId}:`, error);
|
||||
|
||||
431
apps/server/src/services/pr-review-comments.service.ts
Normal file
431
apps/server/src/services/pr-review-comments.service.ts
Normal file
@@ -0,0 +1,431 @@
|
||||
/**
|
||||
* PR Review Comments Service
|
||||
*
|
||||
* Domain logic for fetching PR review comments, enriching them with
|
||||
* resolved-thread status, and sorting. Extracted from the route handler
|
||||
* so the route only deals with request/response plumbing.
|
||||
*/
|
||||
|
||||
import { spawn, execFile } from 'child_process';
|
||||
import { promisify } from 'util';
|
||||
import { createLogger } from '@automaker/utils';
|
||||
import { execEnv, logError } from '../lib/exec-utils.js';
|
||||
|
||||
const execFileAsync = promisify(execFile);
|
||||
|
||||
// ── Public types (re-exported for callers) ──
|
||||
|
||||
export interface PRReviewComment {
|
||||
id: string;
|
||||
author: string;
|
||||
avatarUrl?: string;
|
||||
body: string;
|
||||
path?: string;
|
||||
line?: number;
|
||||
createdAt: string;
|
||||
updatedAt?: string;
|
||||
isReviewComment: boolean;
|
||||
/** Whether this is an outdated review comment (code has changed since) */
|
||||
isOutdated?: boolean;
|
||||
/** Whether the review thread containing this comment has been resolved */
|
||||
isResolved?: boolean;
|
||||
/** The GraphQL node ID of the review thread (used for resolve/unresolve mutations) */
|
||||
threadId?: string;
|
||||
/** The diff hunk context for the comment */
|
||||
diffHunk?: string;
|
||||
/** The side of the diff (LEFT or RIGHT) */
|
||||
side?: string;
|
||||
/** The commit ID the comment was made on */
|
||||
commitId?: string;
|
||||
/** Whether the comment author is a bot/app account */
|
||||
isBot?: boolean;
|
||||
}
|
||||
|
||||
export interface ListPRReviewCommentsResult {
|
||||
success: boolean;
|
||||
comments?: PRReviewComment[];
|
||||
totalCount?: number;
|
||||
error?: string;
|
||||
}
|
||||
|
||||
// ── Internal types ──
|
||||
|
||||
/** Timeout for GitHub GraphQL API requests in milliseconds */
|
||||
const GITHUB_API_TIMEOUT_MS = 30000;
|
||||
|
||||
/** Maximum number of pagination pages to prevent infinite loops */
|
||||
const MAX_PAGINATION_PAGES = 20;
|
||||
|
||||
interface GraphQLReviewThreadComment {
|
||||
databaseId: number;
|
||||
}
|
||||
|
||||
interface GraphQLReviewThread {
|
||||
id: string;
|
||||
isResolved: boolean;
|
||||
comments: {
|
||||
pageInfo?: {
|
||||
hasNextPage: boolean;
|
||||
endCursor?: string | null;
|
||||
};
|
||||
nodes: GraphQLReviewThreadComment[];
|
||||
};
|
||||
}
|
||||
|
||||
interface GraphQLResponse {
|
||||
data?: {
|
||||
repository?: {
|
||||
pullRequest?: {
|
||||
reviewThreads?: {
|
||||
nodes: GraphQLReviewThread[];
|
||||
pageInfo?: {
|
||||
hasNextPage: boolean;
|
||||
endCursor?: string | null;
|
||||
};
|
||||
};
|
||||
} | null;
|
||||
};
|
||||
};
|
||||
errors?: Array<{ message: string }>;
|
||||
}
|
||||
|
||||
interface ReviewThreadInfo {
|
||||
isResolved: boolean;
|
||||
threadId: string;
|
||||
}
|
||||
|
||||
// ── Logger ──
|
||||
|
||||
const logger = createLogger('PRReviewCommentsService');
|
||||
|
||||
// ── Service functions ──
|
||||
|
||||
/**
|
||||
* Execute a GraphQL query via the `gh` CLI and return the parsed response.
|
||||
*/
|
||||
async function executeGraphQL(projectPath: string, requestBody: string): Promise<GraphQLResponse> {
|
||||
let timeoutId: NodeJS.Timeout | undefined;
|
||||
|
||||
const response = await new Promise<GraphQLResponse>((resolve, reject) => {
|
||||
const gh = spawn('gh', ['api', 'graphql', '--input', '-'], {
|
||||
cwd: projectPath,
|
||||
env: execEnv,
|
||||
});
|
||||
|
||||
gh.on('error', (err) => {
|
||||
clearTimeout(timeoutId);
|
||||
reject(err);
|
||||
});
|
||||
|
||||
timeoutId = setTimeout(() => {
|
||||
gh.kill();
|
||||
reject(new Error('GitHub GraphQL API request timed out'));
|
||||
}, GITHUB_API_TIMEOUT_MS);
|
||||
|
||||
let stdout = '';
|
||||
let stderr = '';
|
||||
gh.stdout.on('data', (data: Buffer) => (stdout += data.toString()));
|
||||
gh.stderr.on('data', (data: Buffer) => (stderr += data.toString()));
|
||||
|
||||
gh.on('close', (code) => {
|
||||
clearTimeout(timeoutId);
|
||||
if (code !== 0) {
|
||||
return reject(new Error(`gh process exited with code ${code}: ${stderr}`));
|
||||
}
|
||||
try {
|
||||
resolve(JSON.parse(stdout));
|
||||
} catch (e) {
|
||||
reject(e);
|
||||
}
|
||||
});
|
||||
|
||||
gh.stdin.on('error', () => {
|
||||
// Ignore stdin errors (e.g. when the child process is killed)
|
||||
});
|
||||
gh.stdin.write(requestBody);
|
||||
gh.stdin.end();
|
||||
});
|
||||
|
||||
if (response.errors && response.errors.length > 0) {
|
||||
throw new Error(response.errors[0].message);
|
||||
}
|
||||
|
||||
return response;
|
||||
}
|
||||
|
||||
/**
|
||||
* Fetch review thread resolved status and thread IDs using GitHub GraphQL API.
|
||||
* Uses cursor-based pagination to handle PRs with more than 100 review threads.
|
||||
* Returns a map of comment ID (string) -> { isResolved, threadId }.
|
||||
*/
|
||||
export async function fetchReviewThreadResolvedStatus(
|
||||
projectPath: string,
|
||||
owner: string,
|
||||
repo: string,
|
||||
prNumber: number
|
||||
): Promise<Map<string, ReviewThreadInfo>> {
|
||||
const resolvedMap = new Map<string, ReviewThreadInfo>();
|
||||
|
||||
const query = `
|
||||
query GetPRReviewThreads(
|
||||
$owner: String!
|
||||
$repo: String!
|
||||
$prNumber: Int!
|
||||
$cursor: String
|
||||
) {
|
||||
repository(owner: $owner, name: $repo) {
|
||||
pullRequest(number: $prNumber) {
|
||||
reviewThreads(first: 100, after: $cursor) {
|
||||
pageInfo {
|
||||
hasNextPage
|
||||
endCursor
|
||||
}
|
||||
nodes {
|
||||
id
|
||||
isResolved
|
||||
comments(first: 100) {
|
||||
pageInfo {
|
||||
hasNextPage
|
||||
endCursor
|
||||
}
|
||||
nodes {
|
||||
databaseId
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}`;
|
||||
|
||||
try {
|
||||
let cursor: string | null = null;
|
||||
let pageCount = 0;
|
||||
|
||||
do {
|
||||
const variables = { owner, repo, prNumber, cursor };
|
||||
const requestBody = JSON.stringify({ query, variables });
|
||||
const response = await executeGraphQL(projectPath, requestBody);
|
||||
|
||||
const reviewThreads = response.data?.repository?.pullRequest?.reviewThreads;
|
||||
const threads = reviewThreads?.nodes ?? [];
|
||||
|
||||
for (const thread of threads) {
|
||||
if (thread.comments.pageInfo?.hasNextPage) {
|
||||
logger.debug(
|
||||
`Review thread ${thread.id} in PR #${prNumber} has >100 comments — ` +
|
||||
'some comments may be missing resolved status'
|
||||
);
|
||||
}
|
||||
const info: ReviewThreadInfo = { isResolved: thread.isResolved, threadId: thread.id };
|
||||
for (const comment of thread.comments.nodes) {
|
||||
resolvedMap.set(String(comment.databaseId), info);
|
||||
}
|
||||
}
|
||||
|
||||
const pageInfo = reviewThreads?.pageInfo;
|
||||
if (pageInfo?.hasNextPage && pageInfo.endCursor) {
|
||||
cursor = pageInfo.endCursor;
|
||||
pageCount++;
|
||||
logger.debug(
|
||||
`Fetching next page of review threads for PR #${prNumber} (page ${pageCount + 1})`
|
||||
);
|
||||
} else {
|
||||
cursor = null;
|
||||
}
|
||||
} while (cursor && pageCount < MAX_PAGINATION_PAGES);
|
||||
|
||||
if (pageCount >= MAX_PAGINATION_PAGES) {
|
||||
logger.warn(
|
||||
`PR #${prNumber} in ${owner}/${repo} has more than ${MAX_PAGINATION_PAGES * 100} review threads — ` +
|
||||
'pagination limit reached. Some comments may be missing resolved status.'
|
||||
);
|
||||
}
|
||||
} catch (error) {
|
||||
// Log but don't fail — resolved status is best-effort
|
||||
logError(error, 'Failed to fetch PR review thread resolved status');
|
||||
}
|
||||
|
||||
return resolvedMap;
|
||||
}
|
||||
|
||||
/**
|
||||
* Fetch all comments for a PR (regular, inline review, and review body comments)
|
||||
*/
|
||||
export async function fetchPRReviewComments(
|
||||
projectPath: string,
|
||||
owner: string,
|
||||
repo: string,
|
||||
prNumber: number
|
||||
): Promise<PRReviewComment[]> {
|
||||
const allComments: PRReviewComment[] = [];
|
||||
|
||||
// Fetch review thread resolved status in parallel with comment fetching
|
||||
const resolvedStatusPromise = fetchReviewThreadResolvedStatus(projectPath, owner, repo, prNumber);
|
||||
|
||||
// 1. Fetch regular PR comments (issue-level comments)
|
||||
// Uses the REST API issues endpoint instead of `gh pr view --json comments`
|
||||
// because the latter uses GraphQL internally where bot/app authors can return
|
||||
// null, causing bot comments to be silently dropped or display as "unknown".
|
||||
try {
|
||||
const issueCommentsEndpoint = `repos/${owner}/${repo}/issues/${prNumber}/comments`;
|
||||
const { stdout: commentsOutput } = await execFileAsync(
|
||||
'gh',
|
||||
['api', issueCommentsEndpoint, '--paginate'],
|
||||
{
|
||||
cwd: projectPath,
|
||||
env: execEnv,
|
||||
maxBuffer: 1024 * 1024 * 10, // 10MB buffer for large PRs
|
||||
timeout: GITHUB_API_TIMEOUT_MS,
|
||||
}
|
||||
);
|
||||
|
||||
const commentsData = JSON.parse(commentsOutput);
|
||||
const regularComments = (Array.isArray(commentsData) ? commentsData : []).map(
|
||||
(c: {
|
||||
id: number;
|
||||
user: { login: string; avatar_url?: string; type?: string } | null;
|
||||
body: string;
|
||||
created_at: string;
|
||||
updated_at?: string;
|
||||
performed_via_github_app?: { slug: string } | null;
|
||||
}) => ({
|
||||
id: String(c.id),
|
||||
author: c.user?.login || c.performed_via_github_app?.slug || 'unknown',
|
||||
avatarUrl: c.user?.avatar_url,
|
||||
body: c.body,
|
||||
createdAt: c.created_at,
|
||||
updatedAt: c.updated_at,
|
||||
isReviewComment: false,
|
||||
isOutdated: false,
|
||||
isBot: c.user?.type === 'Bot' || !!c.performed_via_github_app,
|
||||
// Regular PR comments are not part of review threads, so not resolvable
|
||||
isResolved: false,
|
||||
})
|
||||
);
|
||||
|
||||
allComments.push(...regularComments);
|
||||
} catch (error) {
|
||||
logError(error, 'Failed to fetch regular PR comments');
|
||||
}
|
||||
|
||||
// 2. Fetch inline review comments (code-level comments with file/line info)
|
||||
try {
|
||||
const reviewsEndpoint = `repos/${owner}/${repo}/pulls/${prNumber}/comments`;
|
||||
const { stdout: reviewsOutput } = await execFileAsync(
|
||||
'gh',
|
||||
['api', reviewsEndpoint, '--paginate'],
|
||||
{
|
||||
cwd: projectPath,
|
||||
env: execEnv,
|
||||
maxBuffer: 1024 * 1024 * 10, // 10MB buffer for large PRs
|
||||
timeout: GITHUB_API_TIMEOUT_MS,
|
||||
}
|
||||
);
|
||||
|
||||
const reviewsData = JSON.parse(reviewsOutput);
|
||||
const reviewComments = (Array.isArray(reviewsData) ? reviewsData : []).map(
|
||||
(c: {
|
||||
id: number;
|
||||
user: { login: string; avatar_url?: string; type?: string } | null;
|
||||
body: string;
|
||||
path: string;
|
||||
line?: number;
|
||||
original_line?: number;
|
||||
created_at: string;
|
||||
updated_at?: string;
|
||||
diff_hunk?: string;
|
||||
side?: string;
|
||||
commit_id?: string;
|
||||
position?: number | null;
|
||||
performed_via_github_app?: { slug: string } | null;
|
||||
}) => ({
|
||||
id: String(c.id),
|
||||
author: c.user?.login || c.performed_via_github_app?.slug || 'unknown',
|
||||
avatarUrl: c.user?.avatar_url,
|
||||
body: c.body,
|
||||
path: c.path,
|
||||
line: c.line ?? c.original_line,
|
||||
createdAt: c.created_at,
|
||||
updatedAt: c.updated_at,
|
||||
isReviewComment: true,
|
||||
// A review comment is "outdated" if position is null (code has changed)
|
||||
isOutdated: c.position === null,
|
||||
// isResolved will be filled in below from GraphQL data
|
||||
isResolved: false,
|
||||
isBot: c.user?.type === 'Bot' || !!c.performed_via_github_app,
|
||||
diffHunk: c.diff_hunk,
|
||||
side: c.side,
|
||||
commitId: c.commit_id,
|
||||
})
|
||||
);
|
||||
|
||||
allComments.push(...reviewComments);
|
||||
} catch (error) {
|
||||
logError(error, 'Failed to fetch inline review comments');
|
||||
}
|
||||
|
||||
// 3. Fetch review body comments (summary text submitted with each review)
|
||||
// These are the top-level comments written when submitting a review
|
||||
// (Approve, Request Changes, Comment). They are separate from inline code comments
|
||||
// and issue-level comments. Only include reviews that have a non-empty body.
|
||||
try {
|
||||
const reviewsEndpoint = `repos/${owner}/${repo}/pulls/${prNumber}/reviews`;
|
||||
const { stdout: reviewBodiesOutput } = await execFileAsync(
|
||||
'gh',
|
||||
['api', reviewsEndpoint, '--paginate'],
|
||||
{
|
||||
cwd: projectPath,
|
||||
env: execEnv,
|
||||
maxBuffer: 1024 * 1024 * 10, // 10MB buffer for large PRs
|
||||
timeout: GITHUB_API_TIMEOUT_MS,
|
||||
}
|
||||
);
|
||||
|
||||
const reviewBodiesData = JSON.parse(reviewBodiesOutput);
|
||||
const reviewBodyComments = (Array.isArray(reviewBodiesData) ? reviewBodiesData : [])
|
||||
.filter(
|
||||
(r: { body?: string; state?: string }) =>
|
||||
r.body && r.body.trim().length > 0 && r.state !== 'PENDING'
|
||||
)
|
||||
.map(
|
||||
(r: {
|
||||
id: number;
|
||||
user: { login: string; avatar_url?: string; type?: string } | null;
|
||||
body: string;
|
||||
state: string;
|
||||
submitted_at: string;
|
||||
performed_via_github_app?: { slug: string } | null;
|
||||
}) => ({
|
||||
id: `review-${r.id}`,
|
||||
author: r.user?.login || r.performed_via_github_app?.slug || 'unknown',
|
||||
avatarUrl: r.user?.avatar_url,
|
||||
body: r.body,
|
||||
createdAt: r.submitted_at,
|
||||
isReviewComment: false,
|
||||
isOutdated: false,
|
||||
isResolved: false,
|
||||
isBot: r.user?.type === 'Bot' || !!r.performed_via_github_app,
|
||||
})
|
||||
);
|
||||
|
||||
allComments.push(...reviewBodyComments);
|
||||
} catch (error) {
|
||||
logError(error, 'Failed to fetch review body comments');
|
||||
}
|
||||
|
||||
// Wait for resolved status and apply to inline review comments
|
||||
const resolvedMap = await resolvedStatusPromise;
|
||||
for (const comment of allComments) {
|
||||
if (comment.isReviewComment && resolvedMap.has(comment.id)) {
|
||||
const info = resolvedMap.get(comment.id)!;
|
||||
comment.isResolved = info.isResolved;
|
||||
comment.threadId = info.threadId;
|
||||
}
|
||||
}
|
||||
|
||||
// Sort by createdAt descending (newest first)
|
||||
allComments.sort((a, b) => new Date(b.createdAt).getTime() - new Date(a.createdAt).getTime());
|
||||
|
||||
return allComments;
|
||||
}
|
||||
258
apps/server/src/services/push-service.ts
Normal file
258
apps/server/src/services/push-service.ts
Normal file
@@ -0,0 +1,258 @@
|
||||
/**
|
||||
* PushService - Push git operations without HTTP
|
||||
*
|
||||
* Encapsulates the full git push workflow including:
|
||||
* - Branch name and detached HEAD detection
|
||||
* - Safe array-based command execution (no shell interpolation)
|
||||
* - Divergent branch detection and auto-resolution via pull-then-retry
|
||||
* - Structured result reporting
|
||||
*
|
||||
* Mirrors the pull-service.ts pattern for consistency.
|
||||
*/
|
||||
|
||||
import { createLogger, getErrorMessage } from '@automaker/utils';
|
||||
import { execGitCommand } from '@automaker/git-utils';
|
||||
import { getCurrentBranch } from '../lib/git.js';
|
||||
import { performPull } from './pull-service.js';
|
||||
|
||||
const logger = createLogger('PushService');
|
||||
|
||||
// ============================================================================
|
||||
// Types
|
||||
// ============================================================================
|
||||
|
||||
export interface PushOptions {
|
||||
/** Remote name to push to (defaults to 'origin') */
|
||||
remote?: string;
|
||||
/** Force push */
|
||||
force?: boolean;
|
||||
/** When true and push is rejected due to divergence, pull then retry push */
|
||||
autoResolve?: boolean;
|
||||
}
|
||||
|
||||
export interface PushResult {
|
||||
success: boolean;
|
||||
error?: string;
|
||||
branch?: string;
|
||||
pushed?: boolean;
|
||||
/** Whether the push was initially rejected because the branches diverged */
|
||||
diverged?: boolean;
|
||||
/** Whether divergence was automatically resolved via pull-then-retry */
|
||||
autoResolved?: boolean;
|
||||
/** Whether the auto-resolve pull resulted in merge conflicts */
|
||||
hasConflicts?: boolean;
|
||||
/** Files with merge conflicts (only when hasConflicts is true) */
|
||||
conflictFiles?: string[];
|
||||
message?: string;
|
||||
}
|
||||
|
||||
// ============================================================================
|
||||
// Helper Functions
|
||||
// ============================================================================
|
||||
|
||||
/**
|
||||
* Detect whether push error output indicates a diverged/non-fast-forward rejection.
|
||||
*/
|
||||
function isDivergenceError(errorOutput: string): boolean {
|
||||
const lower = errorOutput.toLowerCase();
|
||||
// Require specific divergence indicators rather than just 'rejected' alone,
|
||||
// which could match pre-receive hook rejections or protected branch errors.
|
||||
const hasNonFastForward = lower.includes('non-fast-forward');
|
||||
const hasFetchFirst = lower.includes('fetch first');
|
||||
const hasFailedToPush = lower.includes('failed to push some refs');
|
||||
const hasRejected = lower.includes('rejected');
|
||||
return hasNonFastForward || hasFetchFirst || (hasRejected && hasFailedToPush);
|
||||
}
|
||||
|
||||
// ============================================================================
|
||||
// Main Service Function
|
||||
// ============================================================================
|
||||
|
||||
/**
|
||||
* Perform a git push on the given worktree.
|
||||
*
|
||||
* The workflow:
|
||||
* 1. Get current branch name (detect detached HEAD)
|
||||
* 2. Attempt `git push <remote> <branch>` with safe array args
|
||||
* 3. If push fails with divergence and autoResolve is true:
|
||||
* a. Pull from the same remote (with stash support)
|
||||
* b. If pull succeeds without conflicts, retry push
|
||||
* 4. If push fails with "no upstream" error, retry with --set-upstream
|
||||
* 5. Return structured result
|
||||
*
|
||||
* @param worktreePath - Path to the git worktree
|
||||
* @param options - Push options (remote, force, autoResolve)
|
||||
* @returns PushResult with detailed status information
|
||||
*/
|
||||
export async function performPush(
|
||||
worktreePath: string,
|
||||
options?: PushOptions
|
||||
): Promise<PushResult> {
|
||||
const targetRemote = options?.remote || 'origin';
|
||||
const force = options?.force ?? false;
|
||||
const autoResolve = options?.autoResolve ?? false;
|
||||
|
||||
// 1. Get current branch name
|
||||
let branchName: string;
|
||||
try {
|
||||
branchName = await getCurrentBranch(worktreePath);
|
||||
} catch (err) {
|
||||
return {
|
||||
success: false,
|
||||
error: `Failed to get current branch: ${getErrorMessage(err)}`,
|
||||
};
|
||||
}
|
||||
|
||||
// 2. Check for detached HEAD state
|
||||
if (branchName === 'HEAD') {
|
||||
return {
|
||||
success: false,
|
||||
error: 'Cannot push in detached HEAD state. Please checkout a branch first.',
|
||||
};
|
||||
}
|
||||
|
||||
// 3. Build push args (no -u flag; upstream is set in the fallback path only when needed)
|
||||
const pushArgs = ['push', targetRemote, branchName];
|
||||
if (force) {
|
||||
pushArgs.push('--force');
|
||||
}
|
||||
|
||||
// 4. Attempt push
|
||||
try {
|
||||
await execGitCommand(pushArgs, worktreePath);
|
||||
|
||||
return {
|
||||
success: true,
|
||||
branch: branchName,
|
||||
pushed: true,
|
||||
message: `Successfully pushed ${branchName} to ${targetRemote}`,
|
||||
};
|
||||
} catch (pushError: unknown) {
|
||||
const err = pushError as { stderr?: string; stdout?: string; message?: string };
|
||||
const errorOutput = `${err.stderr || ''} ${err.stdout || ''} ${err.message || ''}`;
|
||||
|
||||
// 5. Check if the error is a divergence rejection
|
||||
if (isDivergenceError(errorOutput)) {
|
||||
if (!autoResolve) {
|
||||
return {
|
||||
success: false,
|
||||
branch: branchName,
|
||||
pushed: false,
|
||||
diverged: true,
|
||||
error: `Push rejected: remote has changes not present locally. Use sync or pull first, or enable auto-resolve.`,
|
||||
message: `Push to ${targetRemote} was rejected because the remote branch has diverged.`,
|
||||
};
|
||||
}
|
||||
|
||||
// 6. Auto-resolve: pull then retry push
|
||||
logger.info('Push rejected due to divergence, attempting auto-resolve via pull', {
|
||||
worktreePath,
|
||||
remote: targetRemote,
|
||||
branch: branchName,
|
||||
});
|
||||
|
||||
try {
|
||||
const pullResult = await performPull(worktreePath, {
|
||||
remote: targetRemote,
|
||||
stashIfNeeded: true,
|
||||
});
|
||||
|
||||
if (!pullResult.success) {
|
||||
return {
|
||||
success: false,
|
||||
branch: branchName,
|
||||
pushed: false,
|
||||
diverged: true,
|
||||
autoResolved: false,
|
||||
error: `Auto-resolve failed during pull: ${pullResult.error}`,
|
||||
};
|
||||
}
|
||||
|
||||
if (pullResult.hasConflicts) {
|
||||
return {
|
||||
success: false,
|
||||
branch: branchName,
|
||||
pushed: false,
|
||||
diverged: true,
|
||||
autoResolved: false,
|
||||
hasConflicts: true,
|
||||
conflictFiles: pullResult.conflictFiles,
|
||||
error:
|
||||
'Auto-resolve pull resulted in merge conflicts. Resolve conflicts and push again.',
|
||||
};
|
||||
}
|
||||
|
||||
// 7. Retry push after successful pull
|
||||
try {
|
||||
await execGitCommand(pushArgs, worktreePath);
|
||||
|
||||
return {
|
||||
success: true,
|
||||
branch: branchName,
|
||||
pushed: true,
|
||||
diverged: true,
|
||||
autoResolved: true,
|
||||
message: `Push succeeded after auto-resolving divergence (pulled from ${targetRemote} first).`,
|
||||
};
|
||||
} catch (retryError: unknown) {
|
||||
const retryErr = retryError as { stderr?: string; message?: string };
|
||||
return {
|
||||
success: false,
|
||||
branch: branchName,
|
||||
pushed: false,
|
||||
diverged: true,
|
||||
autoResolved: false,
|
||||
error: `Push failed after auto-resolve pull: ${retryErr.stderr || retryErr.message || 'Unknown error'}`,
|
||||
};
|
||||
}
|
||||
} catch (pullError) {
|
||||
return {
|
||||
success: false,
|
||||
branch: branchName,
|
||||
pushed: false,
|
||||
diverged: true,
|
||||
autoResolved: false,
|
||||
error: `Auto-resolve pull failed: ${getErrorMessage(pullError)}`,
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
// 6b. Non-divergence error (e.g. no upstream configured) - retry with --set-upstream
|
||||
const isNoUpstreamError =
|
||||
errorOutput.toLowerCase().includes('no upstream') ||
|
||||
errorOutput.toLowerCase().includes('has no upstream branch') ||
|
||||
errorOutput.toLowerCase().includes('set-upstream');
|
||||
if (isNoUpstreamError) {
|
||||
try {
|
||||
const setUpstreamArgs = ['push', '--set-upstream', targetRemote, branchName];
|
||||
if (force) {
|
||||
setUpstreamArgs.push('--force');
|
||||
}
|
||||
await execGitCommand(setUpstreamArgs, worktreePath);
|
||||
|
||||
return {
|
||||
success: true,
|
||||
branch: branchName,
|
||||
pushed: true,
|
||||
message: `Successfully pushed ${branchName} to ${targetRemote} (set upstream)`,
|
||||
};
|
||||
} catch (upstreamError: unknown) {
|
||||
const upstreamErr = upstreamError as { stderr?: string; message?: string };
|
||||
return {
|
||||
success: false,
|
||||
branch: branchName,
|
||||
pushed: false,
|
||||
error: upstreamErr.stderr || upstreamErr.message || getErrorMessage(pushError),
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
// 6c. Other push error - return as-is
|
||||
return {
|
||||
success: false,
|
||||
branch: branchName,
|
||||
pushed: false,
|
||||
error: err.stderr || err.message || getErrorMessage(pushError),
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -573,6 +573,17 @@ export class SettingsService {
|
||||
ignoreEmptyArrayOverwrite('claudeApiProfiles');
|
||||
// Note: claudeCompatibleProviders intentionally NOT guarded - users should be able to delete all providers
|
||||
|
||||
// Check for explicit permission to clear eventHooks (escape hatch for intentional clearing)
|
||||
const allowEmptyEventHooks =
|
||||
(sanitizedUpdates as Record<string, unknown>).__allowEmptyEventHooks === true;
|
||||
// Remove the flag so it doesn't get persisted
|
||||
delete (sanitizedUpdates as Record<string, unknown>).__allowEmptyEventHooks;
|
||||
|
||||
// Only guard eventHooks if explicit permission wasn't granted
|
||||
if (!allowEmptyEventHooks) {
|
||||
ignoreEmptyArrayOverwrite('eventHooks');
|
||||
}
|
||||
|
||||
// Empty object overwrite guard
|
||||
const ignoreEmptyObjectOverwrite = <K extends keyof GlobalSettings>(key: K): void => {
|
||||
const nextVal = sanitizedUpdates[key] as unknown;
|
||||
|
||||
209
apps/server/src/services/sync-service.ts
Normal file
209
apps/server/src/services/sync-service.ts
Normal file
@@ -0,0 +1,209 @@
|
||||
/**
|
||||
* SyncService - Pull then push in a single operation
|
||||
*
|
||||
* Composes performPull() and performPush() to synchronize a branch
|
||||
* with its remote. Always uses stashIfNeeded for the pull step.
|
||||
* If push fails with divergence after pull, retries once.
|
||||
*
|
||||
* Follows the same pattern as pull-service.ts and push-service.ts.
|
||||
*/
|
||||
|
||||
import { createLogger, getErrorMessage } from '@automaker/utils';
|
||||
import { performPull } from './pull-service.js';
|
||||
import { performPush } from './push-service.js';
|
||||
import type { PullResult } from './pull-service.js';
|
||||
import type { PushResult } from './push-service.js';
|
||||
|
||||
const logger = createLogger('SyncService');
|
||||
|
||||
// ============================================================================
|
||||
// Types
|
||||
// ============================================================================
|
||||
|
||||
export interface SyncOptions {
|
||||
/** Remote name (defaults to 'origin') */
|
||||
remote?: string;
|
||||
}
|
||||
|
||||
export interface SyncResult {
|
||||
success: boolean;
|
||||
error?: string;
|
||||
branch?: string;
|
||||
/** Whether the pull step was performed */
|
||||
pulled?: boolean;
|
||||
/** Whether the push step was performed */
|
||||
pushed?: boolean;
|
||||
/** Pull resulted in conflicts */
|
||||
hasConflicts?: boolean;
|
||||
/** Files with merge conflicts */
|
||||
conflictFiles?: string[];
|
||||
/** Source of conflicts ('pull' | 'stash') */
|
||||
conflictSource?: 'pull' | 'stash';
|
||||
/** Whether the pull was a fast-forward */
|
||||
isFastForward?: boolean;
|
||||
/** Whether the pull resulted in a merge commit */
|
||||
isMerge?: boolean;
|
||||
/** Whether push divergence was auto-resolved */
|
||||
autoResolved?: boolean;
|
||||
message?: string;
|
||||
}
|
||||
|
||||
// ============================================================================
|
||||
// Main Service Function
|
||||
// ============================================================================
|
||||
|
||||
/**
|
||||
* Perform a sync operation (pull then push) on the given worktree.
|
||||
*
|
||||
* The workflow:
|
||||
* 1. Pull from remote with stashIfNeeded: true
|
||||
* 2. If pull has conflicts, stop and return conflict info
|
||||
* 3. Push to remote
|
||||
* 4. If push fails with divergence after pull, retry once
|
||||
*
|
||||
* @param worktreePath - Path to the git worktree
|
||||
* @param options - Sync options (remote)
|
||||
* @returns SyncResult with detailed status information
|
||||
*/
|
||||
export async function performSync(
|
||||
worktreePath: string,
|
||||
options?: SyncOptions
|
||||
): Promise<SyncResult> {
|
||||
const targetRemote = options?.remote || 'origin';
|
||||
|
||||
// 1. Pull from remote
|
||||
logger.info('Sync: starting pull', { worktreePath, remote: targetRemote });
|
||||
|
||||
let pullResult: PullResult;
|
||||
try {
|
||||
pullResult = await performPull(worktreePath, {
|
||||
remote: targetRemote,
|
||||
stashIfNeeded: true,
|
||||
});
|
||||
} catch (pullError) {
|
||||
return {
|
||||
success: false,
|
||||
error: `Sync pull failed: ${getErrorMessage(pullError)}`,
|
||||
};
|
||||
}
|
||||
|
||||
if (!pullResult.success) {
|
||||
return {
|
||||
success: false,
|
||||
branch: pullResult.branch,
|
||||
pulled: false,
|
||||
pushed: false,
|
||||
error: `Sync pull failed: ${pullResult.error}`,
|
||||
hasConflicts: pullResult.hasConflicts,
|
||||
conflictFiles: pullResult.conflictFiles,
|
||||
conflictSource: pullResult.conflictSource,
|
||||
};
|
||||
}
|
||||
|
||||
// 2. If pull had conflicts, stop and return conflict info
|
||||
if (pullResult.hasConflicts) {
|
||||
return {
|
||||
success: false,
|
||||
branch: pullResult.branch,
|
||||
pulled: true,
|
||||
pushed: false,
|
||||
hasConflicts: true,
|
||||
conflictFiles: pullResult.conflictFiles,
|
||||
conflictSource: pullResult.conflictSource,
|
||||
isFastForward: pullResult.isFastForward,
|
||||
isMerge: pullResult.isMerge,
|
||||
error: 'Sync stopped: pull resulted in merge conflicts. Resolve conflicts and try again.',
|
||||
message: pullResult.message,
|
||||
};
|
||||
}
|
||||
|
||||
// 3. Push to remote
|
||||
logger.info('Sync: pull succeeded, starting push', { worktreePath, remote: targetRemote });
|
||||
|
||||
let pushResult: PushResult;
|
||||
try {
|
||||
pushResult = await performPush(worktreePath, {
|
||||
remote: targetRemote,
|
||||
});
|
||||
} catch (pushError) {
|
||||
return {
|
||||
success: false,
|
||||
branch: pullResult.branch,
|
||||
pulled: true,
|
||||
pushed: false,
|
||||
isFastForward: pullResult.isFastForward,
|
||||
isMerge: pullResult.isMerge,
|
||||
error: `Sync push failed: ${getErrorMessage(pushError)}`,
|
||||
};
|
||||
}
|
||||
|
||||
if (!pushResult.success) {
|
||||
// 4. If push diverged after pull, retry once with autoResolve
|
||||
if (pushResult.diverged) {
|
||||
logger.info('Sync: push diverged after pull, retrying with autoResolve', {
|
||||
worktreePath,
|
||||
remote: targetRemote,
|
||||
});
|
||||
|
||||
try {
|
||||
const retryResult = await performPush(worktreePath, {
|
||||
remote: targetRemote,
|
||||
autoResolve: true,
|
||||
});
|
||||
|
||||
if (retryResult.success) {
|
||||
return {
|
||||
success: true,
|
||||
branch: retryResult.branch,
|
||||
pulled: true,
|
||||
pushed: true,
|
||||
autoResolved: true,
|
||||
isFastForward: pullResult.isFastForward,
|
||||
isMerge: pullResult.isMerge,
|
||||
message: 'Sync completed (push required auto-resolve).',
|
||||
};
|
||||
}
|
||||
|
||||
return {
|
||||
success: false,
|
||||
branch: retryResult.branch,
|
||||
pulled: true,
|
||||
pushed: false,
|
||||
hasConflicts: retryResult.hasConflicts,
|
||||
conflictFiles: retryResult.conflictFiles,
|
||||
error: retryResult.error,
|
||||
};
|
||||
} catch (retryError) {
|
||||
return {
|
||||
success: false,
|
||||
branch: pullResult.branch,
|
||||
pulled: true,
|
||||
pushed: false,
|
||||
error: `Sync push retry failed: ${getErrorMessage(retryError)}`,
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
success: false,
|
||||
branch: pushResult.branch,
|
||||
pulled: true,
|
||||
pushed: false,
|
||||
isFastForward: pullResult.isFastForward,
|
||||
isMerge: pullResult.isMerge,
|
||||
error: `Sync push failed: ${pushResult.error}`,
|
||||
};
|
||||
}
|
||||
|
||||
return {
|
||||
success: true,
|
||||
branch: pushResult.branch,
|
||||
pulled: pullResult.pulled ?? true,
|
||||
pushed: true,
|
||||
isFastForward: pullResult.isFastForward,
|
||||
isMerge: pullResult.isMerge,
|
||||
message: pullResult.pulled
|
||||
? 'Sync completed: pulled latest changes and pushed.'
|
||||
: 'Sync completed: already up to date, pushed local commits.',
|
||||
};
|
||||
}
|
||||
@@ -198,7 +198,7 @@ describe('claude-provider.ts', () => {
|
||||
expect(typeof callArgs.prompt).not.toBe('string');
|
||||
});
|
||||
|
||||
it('should use maxTurns default of 100', async () => {
|
||||
it('should use maxTurns default of 1000', async () => {
|
||||
vi.mocked(sdk.query).mockReturnValue(
|
||||
(async function* () {
|
||||
yield { type: 'text', text: 'test' };
|
||||
@@ -216,7 +216,7 @@ describe('claude-provider.ts', () => {
|
||||
expect(sdk.query).toHaveBeenCalledWith({
|
||||
prompt: 'Test',
|
||||
options: expect.objectContaining({
|
||||
maxTurns: 100,
|
||||
maxTurns: 1000,
|
||||
}),
|
||||
});
|
||||
});
|
||||
|
||||
@@ -320,8 +320,10 @@ describe('codex-provider.ts', () => {
|
||||
);
|
||||
|
||||
const call = vi.mocked(spawnJSONLProcess).mock.calls[0][0];
|
||||
// High reasoning effort should have 3x the default timeout (90000ms)
|
||||
expect(call.timeout).toBe(DEFAULT_TIMEOUT_MS * REASONING_TIMEOUT_MULTIPLIERS.high);
|
||||
// High reasoning effort should have 3x the CLI base timeout (120000ms)
|
||||
// CODEX_CLI_TIMEOUT_MS = 120000, multiplier for 'high' = 3.0 → 360000ms
|
||||
const CODEX_CLI_TIMEOUT_MS = 120000;
|
||||
expect(call.timeout).toBe(CODEX_CLI_TIMEOUT_MS * REASONING_TIMEOUT_MULTIPLIERS.high);
|
||||
});
|
||||
|
||||
it('passes extended timeout for xhigh reasoning effort', async () => {
|
||||
@@ -357,8 +359,10 @@ describe('codex-provider.ts', () => {
|
||||
);
|
||||
|
||||
const call = vi.mocked(spawnJSONLProcess).mock.calls[0][0];
|
||||
// No reasoning effort should use the default timeout
|
||||
expect(call.timeout).toBe(DEFAULT_TIMEOUT_MS);
|
||||
// No reasoning effort should use the CLI base timeout (2 minutes)
|
||||
// CODEX_CLI_TIMEOUT_MS = 120000ms, no multiplier applied
|
||||
const CODEX_CLI_TIMEOUT_MS = 120000;
|
||||
expect(call.timeout).toBe(CODEX_CLI_TIMEOUT_MS);
|
||||
});
|
||||
});
|
||||
|
||||
|
||||
580
apps/server/tests/unit/services/event-hook-service.test.ts
Normal file
580
apps/server/tests/unit/services/event-hook-service.test.ts
Normal file
@@ -0,0 +1,580 @@
|
||||
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
|
||||
import { EventHookService } from '../../../src/services/event-hook-service.js';
|
||||
import type { EventEmitter, EventCallback, EventType } from '../../../src/lib/events.js';
|
||||
import type { SettingsService } from '../../../src/services/settings-service.js';
|
||||
import type { EventHistoryService } from '../../../src/services/event-history-service.js';
|
||||
import type { FeatureLoader } from '../../../src/services/feature-loader.js';
|
||||
|
||||
/**
|
||||
* Create a mock EventEmitter for testing
|
||||
*/
|
||||
function createMockEventEmitter(): EventEmitter & {
|
||||
subscribers: Set<EventCallback>;
|
||||
simulateEvent: (type: EventType, payload: unknown) => void;
|
||||
} {
|
||||
const subscribers = new Set<EventCallback>();
|
||||
|
||||
return {
|
||||
subscribers,
|
||||
emit(type: EventType, payload: unknown) {
|
||||
for (const callback of subscribers) {
|
||||
callback(type, payload);
|
||||
}
|
||||
},
|
||||
subscribe(callback: EventCallback) {
|
||||
subscribers.add(callback);
|
||||
return () => {
|
||||
subscribers.delete(callback);
|
||||
};
|
||||
},
|
||||
simulateEvent(type: EventType, payload: unknown) {
|
||||
for (const callback of subscribers) {
|
||||
callback(type, payload);
|
||||
}
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Create a mock SettingsService
|
||||
*/
|
||||
function createMockSettingsService(hooks: unknown[] = []): SettingsService {
|
||||
return {
|
||||
getGlobalSettings: vi.fn().mockResolvedValue({ eventHooks: hooks }),
|
||||
} as unknown as SettingsService;
|
||||
}
|
||||
|
||||
/**
|
||||
* Create a mock EventHistoryService
|
||||
*/
|
||||
function createMockEventHistoryService() {
|
||||
return {
|
||||
storeEvent: vi.fn().mockResolvedValue({ id: 'test-event-id' }),
|
||||
} as unknown as EventHistoryService;
|
||||
}
|
||||
|
||||
/**
|
||||
* Create a mock FeatureLoader
|
||||
*/
|
||||
function createMockFeatureLoader(features: Record<string, { title: string }> = {}) {
|
||||
return {
|
||||
get: vi.fn().mockImplementation((_projectPath: string, featureId: string) => {
|
||||
return Promise.resolve(features[featureId] || null);
|
||||
}),
|
||||
} as unknown as FeatureLoader;
|
||||
}
|
||||
|
||||
describe('EventHookService', () => {
|
||||
let service: EventHookService;
|
||||
let mockEmitter: ReturnType<typeof createMockEventEmitter>;
|
||||
let mockSettingsService: ReturnType<typeof createMockSettingsService>;
|
||||
let mockEventHistoryService: ReturnType<typeof createMockEventHistoryService>;
|
||||
let mockFeatureLoader: ReturnType<typeof createMockFeatureLoader>;
|
||||
|
||||
beforeEach(() => {
|
||||
service = new EventHookService();
|
||||
mockEmitter = createMockEventEmitter();
|
||||
mockSettingsService = createMockSettingsService();
|
||||
mockEventHistoryService = createMockEventHistoryService();
|
||||
mockFeatureLoader = createMockFeatureLoader();
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
service.destroy();
|
||||
});
|
||||
|
||||
describe('initialize', () => {
|
||||
it('should subscribe to the event emitter', () => {
|
||||
service.initialize(mockEmitter, mockSettingsService, mockEventHistoryService);
|
||||
expect(mockEmitter.subscribers.size).toBe(1);
|
||||
});
|
||||
|
||||
it('should log initialization', () => {
|
||||
service.initialize(mockEmitter, mockSettingsService);
|
||||
expect(mockEmitter.subscribers.size).toBe(1);
|
||||
});
|
||||
});
|
||||
|
||||
describe('destroy', () => {
|
||||
it('should unsubscribe from the event emitter', () => {
|
||||
service.initialize(mockEmitter, mockSettingsService);
|
||||
expect(mockEmitter.subscribers.size).toBe(1);
|
||||
|
||||
service.destroy();
|
||||
expect(mockEmitter.subscribers.size).toBe(0);
|
||||
});
|
||||
});
|
||||
|
||||
describe('event mapping - auto_mode_feature_complete', () => {
|
||||
it('should map to feature_success when passes is true', async () => {
|
||||
service.initialize(
|
||||
mockEmitter,
|
||||
mockSettingsService,
|
||||
mockEventHistoryService,
|
||||
mockFeatureLoader
|
||||
);
|
||||
|
||||
mockEmitter.simulateEvent('auto-mode:event', {
|
||||
type: 'auto_mode_feature_complete',
|
||||
featureId: 'feat-1',
|
||||
featureName: 'Test Feature',
|
||||
passes: true,
|
||||
message: 'Feature completed in 30s',
|
||||
projectPath: '/test/project',
|
||||
});
|
||||
|
||||
// Allow async processing
|
||||
await vi.waitFor(() => {
|
||||
expect(mockEventHistoryService.storeEvent).toHaveBeenCalled();
|
||||
});
|
||||
|
||||
const storeCall = (mockEventHistoryService.storeEvent as ReturnType<typeof vi.fn>).mock
|
||||
.calls[0][0];
|
||||
expect(storeCall.trigger).toBe('feature_success');
|
||||
expect(storeCall.passes).toBe(true);
|
||||
});
|
||||
|
||||
it('should map to feature_error when passes is false', async () => {
|
||||
service.initialize(
|
||||
mockEmitter,
|
||||
mockSettingsService,
|
||||
mockEventHistoryService,
|
||||
mockFeatureLoader
|
||||
);
|
||||
|
||||
mockEmitter.simulateEvent('auto-mode:event', {
|
||||
type: 'auto_mode_feature_complete',
|
||||
featureId: 'feat-1',
|
||||
featureName: 'Test Feature',
|
||||
passes: false,
|
||||
message: 'Feature stopped by user',
|
||||
projectPath: '/test/project',
|
||||
});
|
||||
|
||||
await vi.waitFor(() => {
|
||||
expect(mockEventHistoryService.storeEvent).toHaveBeenCalled();
|
||||
});
|
||||
|
||||
const storeCall = (mockEventHistoryService.storeEvent as ReturnType<typeof vi.fn>).mock
|
||||
.calls[0][0];
|
||||
expect(storeCall.trigger).toBe('feature_error');
|
||||
expect(storeCall.passes).toBe(false);
|
||||
});
|
||||
|
||||
it('should NOT populate error field for successful feature completion', async () => {
|
||||
service.initialize(
|
||||
mockEmitter,
|
||||
mockSettingsService,
|
||||
mockEventHistoryService,
|
||||
mockFeatureLoader
|
||||
);
|
||||
|
||||
mockEmitter.simulateEvent('auto-mode:event', {
|
||||
type: 'auto_mode_feature_complete',
|
||||
featureId: 'feat-1',
|
||||
featureName: 'Test Feature',
|
||||
passes: true,
|
||||
message: 'Feature completed in 30s - auto-verified',
|
||||
projectPath: '/test/project',
|
||||
});
|
||||
|
||||
await vi.waitFor(() => {
|
||||
expect(mockEventHistoryService.storeEvent).toHaveBeenCalled();
|
||||
});
|
||||
|
||||
const storeCall = (mockEventHistoryService.storeEvent as ReturnType<typeof vi.fn>).mock
|
||||
.calls[0][0];
|
||||
expect(storeCall.trigger).toBe('feature_success');
|
||||
// Critical: error should NOT contain the success message
|
||||
expect(storeCall.error).toBeUndefined();
|
||||
expect(storeCall.errorType).toBeUndefined();
|
||||
});
|
||||
|
||||
it('should populate error field for failed feature completion', async () => {
|
||||
service.initialize(
|
||||
mockEmitter,
|
||||
mockSettingsService,
|
||||
mockEventHistoryService,
|
||||
mockFeatureLoader
|
||||
);
|
||||
|
||||
mockEmitter.simulateEvent('auto-mode:event', {
|
||||
type: 'auto_mode_feature_complete',
|
||||
featureId: 'feat-1',
|
||||
featureName: 'Test Feature',
|
||||
passes: false,
|
||||
message: 'Feature stopped by user',
|
||||
projectPath: '/test/project',
|
||||
});
|
||||
|
||||
await vi.waitFor(() => {
|
||||
expect(mockEventHistoryService.storeEvent).toHaveBeenCalled();
|
||||
});
|
||||
|
||||
const storeCall = (mockEventHistoryService.storeEvent as ReturnType<typeof vi.fn>).mock
|
||||
.calls[0][0];
|
||||
expect(storeCall.trigger).toBe('feature_error');
|
||||
// Error field should be populated for error triggers
|
||||
expect(storeCall.error).toBe('Feature stopped by user');
|
||||
});
|
||||
});
|
||||
|
||||
describe('event mapping - auto_mode_error', () => {
|
||||
it('should map to feature_error when featureId is present', async () => {
|
||||
service.initialize(
|
||||
mockEmitter,
|
||||
mockSettingsService,
|
||||
mockEventHistoryService,
|
||||
mockFeatureLoader
|
||||
);
|
||||
|
||||
mockEmitter.simulateEvent('auto-mode:event', {
|
||||
type: 'auto_mode_error',
|
||||
featureId: 'feat-1',
|
||||
error: 'Network timeout',
|
||||
errorType: 'network',
|
||||
projectPath: '/test/project',
|
||||
});
|
||||
|
||||
await vi.waitFor(() => {
|
||||
expect(mockEventHistoryService.storeEvent).toHaveBeenCalled();
|
||||
});
|
||||
|
||||
const storeCall = (mockEventHistoryService.storeEvent as ReturnType<typeof vi.fn>).mock
|
||||
.calls[0][0];
|
||||
expect(storeCall.trigger).toBe('feature_error');
|
||||
expect(storeCall.error).toBe('Network timeout');
|
||||
expect(storeCall.errorType).toBe('network');
|
||||
});
|
||||
|
||||
it('should map to auto_mode_error when featureId is not present', async () => {
|
||||
service.initialize(
|
||||
mockEmitter,
|
||||
mockSettingsService,
|
||||
mockEventHistoryService,
|
||||
mockFeatureLoader
|
||||
);
|
||||
|
||||
mockEmitter.simulateEvent('auto-mode:event', {
|
||||
type: 'auto_mode_error',
|
||||
error: 'System error',
|
||||
errorType: 'system',
|
||||
projectPath: '/test/project',
|
||||
});
|
||||
|
||||
await vi.waitFor(() => {
|
||||
expect(mockEventHistoryService.storeEvent).toHaveBeenCalled();
|
||||
});
|
||||
|
||||
const storeCall = (mockEventHistoryService.storeEvent as ReturnType<typeof vi.fn>).mock
|
||||
.calls[0][0];
|
||||
expect(storeCall.trigger).toBe('auto_mode_error');
|
||||
expect(storeCall.error).toBe('System error');
|
||||
expect(storeCall.errorType).toBe('system');
|
||||
});
|
||||
});
|
||||
|
||||
describe('event mapping - auto_mode_idle', () => {
|
||||
it('should map to auto_mode_complete', async () => {
|
||||
service.initialize(
|
||||
mockEmitter,
|
||||
mockSettingsService,
|
||||
mockEventHistoryService,
|
||||
mockFeatureLoader
|
||||
);
|
||||
|
||||
mockEmitter.simulateEvent('auto-mode:event', {
|
||||
type: 'auto_mode_idle',
|
||||
projectPath: '/test/project',
|
||||
});
|
||||
|
||||
await vi.waitFor(() => {
|
||||
expect(mockEventHistoryService.storeEvent).toHaveBeenCalled();
|
||||
});
|
||||
|
||||
const storeCall = (mockEventHistoryService.storeEvent as ReturnType<typeof vi.fn>).mock
|
||||
.calls[0][0];
|
||||
expect(storeCall.trigger).toBe('auto_mode_complete');
|
||||
});
|
||||
});
|
||||
|
||||
describe('event mapping - feature:created', () => {
|
||||
it('should trigger feature_created hook', async () => {
|
||||
service.initialize(
|
||||
mockEmitter,
|
||||
mockSettingsService,
|
||||
mockEventHistoryService,
|
||||
mockFeatureLoader
|
||||
);
|
||||
|
||||
mockEmitter.simulateEvent('feature:created', {
|
||||
featureId: 'feat-1',
|
||||
featureName: 'New Feature',
|
||||
projectPath: '/test/project',
|
||||
});
|
||||
|
||||
await vi.waitFor(() => {
|
||||
expect(mockEventHistoryService.storeEvent).toHaveBeenCalled();
|
||||
});
|
||||
|
||||
const storeCall = (mockEventHistoryService.storeEvent as ReturnType<typeof vi.fn>).mock
|
||||
.calls[0][0];
|
||||
expect(storeCall.trigger).toBe('feature_created');
|
||||
expect(storeCall.featureId).toBe('feat-1');
|
||||
});
|
||||
});
|
||||
|
||||
describe('event mapping - unhandled events', () => {
|
||||
it('should ignore auto-mode events with unrecognized types', async () => {
|
||||
service.initialize(
|
||||
mockEmitter,
|
||||
mockSettingsService,
|
||||
mockEventHistoryService,
|
||||
mockFeatureLoader
|
||||
);
|
||||
|
||||
mockEmitter.simulateEvent('auto-mode:event', {
|
||||
type: 'auto_mode_progress',
|
||||
featureId: 'feat-1',
|
||||
content: 'Working...',
|
||||
projectPath: '/test/project',
|
||||
});
|
||||
|
||||
// Give it time to process
|
||||
await new Promise((resolve) => setTimeout(resolve, 50));
|
||||
|
||||
expect(mockEventHistoryService.storeEvent).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('should ignore events without a type', async () => {
|
||||
service.initialize(
|
||||
mockEmitter,
|
||||
mockSettingsService,
|
||||
mockEventHistoryService,
|
||||
mockFeatureLoader
|
||||
);
|
||||
|
||||
mockEmitter.simulateEvent('auto-mode:event', {
|
||||
featureId: 'feat-1',
|
||||
projectPath: '/test/project',
|
||||
});
|
||||
|
||||
await new Promise((resolve) => setTimeout(resolve, 50));
|
||||
|
||||
expect(mockEventHistoryService.storeEvent).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
|
||||
describe('hook execution', () => {
|
||||
it('should execute matching enabled hooks for feature_success', async () => {
|
||||
const hooks = [
|
||||
{
|
||||
id: 'hook-1',
|
||||
enabled: true,
|
||||
trigger: 'feature_success',
|
||||
name: 'Success Hook',
|
||||
action: {
|
||||
type: 'shell',
|
||||
command: 'echo "success"',
|
||||
},
|
||||
},
|
||||
{
|
||||
id: 'hook-2',
|
||||
enabled: true,
|
||||
trigger: 'feature_error',
|
||||
name: 'Error Hook',
|
||||
action: {
|
||||
type: 'shell',
|
||||
command: 'echo "error"',
|
||||
},
|
||||
},
|
||||
];
|
||||
|
||||
mockSettingsService = createMockSettingsService(hooks);
|
||||
service.initialize(
|
||||
mockEmitter,
|
||||
mockSettingsService,
|
||||
mockEventHistoryService,
|
||||
mockFeatureLoader
|
||||
);
|
||||
|
||||
mockEmitter.simulateEvent('auto-mode:event', {
|
||||
type: 'auto_mode_feature_complete',
|
||||
featureId: 'feat-1',
|
||||
featureName: 'Test Feature',
|
||||
passes: true,
|
||||
message: 'Feature completed in 30s',
|
||||
projectPath: '/test/project',
|
||||
});
|
||||
|
||||
await vi.waitFor(() => {
|
||||
expect(mockSettingsService.getGlobalSettings).toHaveBeenCalled();
|
||||
});
|
||||
|
||||
// The error hook should NOT have been triggered for a success event
|
||||
const storeCall = (mockEventHistoryService.storeEvent as ReturnType<typeof vi.fn>).mock
|
||||
.calls[0][0];
|
||||
expect(storeCall.trigger).toBe('feature_success');
|
||||
});
|
||||
|
||||
it('should NOT execute error hooks when feature completes successfully', async () => {
|
||||
// This is the key regression test for the bug:
|
||||
// "Error event hook fired when a feature completes successfully"
|
||||
const errorHookCommand = vi.fn();
|
||||
const hooks = [
|
||||
{
|
||||
id: 'hook-error',
|
||||
enabled: true,
|
||||
trigger: 'feature_error',
|
||||
name: 'Error Notification',
|
||||
action: {
|
||||
type: 'shell',
|
||||
command: 'echo "ERROR FIRED"',
|
||||
},
|
||||
},
|
||||
];
|
||||
|
||||
mockSettingsService = createMockSettingsService(hooks);
|
||||
service.initialize(
|
||||
mockEmitter,
|
||||
mockSettingsService,
|
||||
mockEventHistoryService,
|
||||
mockFeatureLoader
|
||||
);
|
||||
|
||||
mockEmitter.simulateEvent('auto-mode:event', {
|
||||
type: 'auto_mode_feature_complete',
|
||||
featureId: 'feat-1',
|
||||
featureName: 'Test Feature',
|
||||
passes: true,
|
||||
message: 'Feature completed in 30s - auto-verified',
|
||||
projectPath: '/test/project',
|
||||
});
|
||||
|
||||
await vi.waitFor(() => {
|
||||
expect(mockEventHistoryService.storeEvent).toHaveBeenCalled();
|
||||
});
|
||||
|
||||
// Verify the trigger was feature_success, not feature_error
|
||||
const storeCall = (mockEventHistoryService.storeEvent as ReturnType<typeof vi.fn>).mock
|
||||
.calls[0][0];
|
||||
expect(storeCall.trigger).toBe('feature_success');
|
||||
// And no error information should be present
|
||||
expect(storeCall.error).toBeUndefined();
|
||||
expect(storeCall.errorType).toBeUndefined();
|
||||
});
|
||||
});
|
||||
|
||||
describe('feature name loading', () => {
|
||||
it('should load feature name from feature loader when not in payload', async () => {
|
||||
mockFeatureLoader = createMockFeatureLoader({
|
||||
'feat-1': { title: 'Loaded Feature Title' },
|
||||
});
|
||||
|
||||
service.initialize(
|
||||
mockEmitter,
|
||||
mockSettingsService,
|
||||
mockEventHistoryService,
|
||||
mockFeatureLoader
|
||||
);
|
||||
|
||||
mockEmitter.simulateEvent('auto-mode:event', {
|
||||
type: 'auto_mode_feature_complete',
|
||||
featureId: 'feat-1',
|
||||
passes: true,
|
||||
message: 'Done',
|
||||
projectPath: '/test/project',
|
||||
});
|
||||
|
||||
await vi.waitFor(() => {
|
||||
expect(mockEventHistoryService.storeEvent).toHaveBeenCalled();
|
||||
});
|
||||
|
||||
const storeCall = (mockEventHistoryService.storeEvent as ReturnType<typeof vi.fn>).mock
|
||||
.calls[0][0];
|
||||
expect(storeCall.featureName).toBe('Loaded Feature Title');
|
||||
});
|
||||
|
||||
it('should fall back to payload featureName when loader fails', async () => {
|
||||
mockFeatureLoader = createMockFeatureLoader({}); // Empty - no features found
|
||||
|
||||
service.initialize(
|
||||
mockEmitter,
|
||||
mockSettingsService,
|
||||
mockEventHistoryService,
|
||||
mockFeatureLoader
|
||||
);
|
||||
|
||||
mockEmitter.simulateEvent('auto-mode:event', {
|
||||
type: 'auto_mode_feature_complete',
|
||||
featureId: 'feat-1',
|
||||
featureName: 'Fallback Name',
|
||||
passes: true,
|
||||
message: 'Done',
|
||||
projectPath: '/test/project',
|
||||
});
|
||||
|
||||
await vi.waitFor(() => {
|
||||
expect(mockEventHistoryService.storeEvent).toHaveBeenCalled();
|
||||
});
|
||||
|
||||
const storeCall = (mockEventHistoryService.storeEvent as ReturnType<typeof vi.fn>).mock
|
||||
.calls[0][0];
|
||||
expect(storeCall.featureName).toBe('Fallback Name');
|
||||
});
|
||||
});
|
||||
|
||||
describe('error context for error events', () => {
|
||||
it('should use payload.error when available for error triggers', async () => {
|
||||
service.initialize(
|
||||
mockEmitter,
|
||||
mockSettingsService,
|
||||
mockEventHistoryService,
|
||||
mockFeatureLoader
|
||||
);
|
||||
|
||||
mockEmitter.simulateEvent('auto-mode:event', {
|
||||
type: 'auto_mode_error',
|
||||
featureId: 'feat-1',
|
||||
error: 'Authentication failed',
|
||||
errorType: 'auth',
|
||||
projectPath: '/test/project',
|
||||
});
|
||||
|
||||
await vi.waitFor(() => {
|
||||
expect(mockEventHistoryService.storeEvent).toHaveBeenCalled();
|
||||
});
|
||||
|
||||
const storeCall = (mockEventHistoryService.storeEvent as ReturnType<typeof vi.fn>).mock
|
||||
.calls[0][0];
|
||||
expect(storeCall.error).toBe('Authentication failed');
|
||||
expect(storeCall.errorType).toBe('auth');
|
||||
});
|
||||
|
||||
it('should fall back to payload.message for error field in error triggers', async () => {
|
||||
service.initialize(
|
||||
mockEmitter,
|
||||
mockSettingsService,
|
||||
mockEventHistoryService,
|
||||
mockFeatureLoader
|
||||
);
|
||||
|
||||
mockEmitter.simulateEvent('auto-mode:event', {
|
||||
type: 'auto_mode_feature_complete',
|
||||
featureId: 'feat-1',
|
||||
passes: false,
|
||||
message: 'Feature stopped by user',
|
||||
projectPath: '/test/project',
|
||||
});
|
||||
|
||||
await vi.waitFor(() => {
|
||||
expect(mockEventHistoryService.storeEvent).toHaveBeenCalled();
|
||||
});
|
||||
|
||||
const storeCall = (mockEventHistoryService.storeEvent as ReturnType<typeof vi.fn>).mock
|
||||
.calls[0][0];
|
||||
expect(storeCall.trigger).toBe('feature_error');
|
||||
expect(storeCall.error).toBe('Feature stopped by user');
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -175,7 +175,10 @@ describe('execution-service.ts', () => {
|
||||
} as unknown as TypedEventBus;
|
||||
|
||||
mockConcurrencyManager = {
|
||||
acquire: vi.fn().mockImplementation(({ featureId }) => createRunningFeature(featureId)),
|
||||
acquire: vi.fn().mockImplementation(({ featureId, isAutoMode }) => ({
|
||||
...createRunningFeature(featureId),
|
||||
isAutoMode: isAutoMode ?? false,
|
||||
})),
|
||||
release: vi.fn(),
|
||||
getRunningFeature: vi.fn(),
|
||||
isRunning: vi.fn(),
|
||||
@@ -550,8 +553,8 @@ describe('execution-service.ts', () => {
|
||||
expect(mockRunAgentFn).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('emits feature_complete event on success', async () => {
|
||||
await service.executeFeature('/test/project', 'feature-1');
|
||||
it('emits feature_complete event on success when isAutoMode is true', async () => {
|
||||
await service.executeFeature('/test/project', 'feature-1', false, true);
|
||||
|
||||
expect(mockEventBus.emitAutoModeEvent).toHaveBeenCalledWith(
|
||||
'auto_mode_feature_complete',
|
||||
@@ -561,6 +564,15 @@ describe('execution-service.ts', () => {
|
||||
})
|
||||
);
|
||||
});
|
||||
|
||||
it('does not emit feature_complete event on success when isAutoMode is false', async () => {
|
||||
await service.executeFeature('/test/project', 'feature-1', false, false);
|
||||
|
||||
const completeCalls = vi
|
||||
.mocked(mockEventBus.emitAutoModeEvent)
|
||||
.mock.calls.filter((call) => call[0] === 'auto_mode_feature_complete');
|
||||
expect(completeCalls.length).toBe(0);
|
||||
});
|
||||
});
|
||||
|
||||
describe('executeFeature - approved plan handling', () => {
|
||||
@@ -1110,7 +1122,7 @@ describe('execution-service.ts', () => {
|
||||
);
|
||||
});
|
||||
|
||||
it('handles abort signal without error event', async () => {
|
||||
it('handles abort signal without error event (emits feature_complete when isAutoMode=true)', async () => {
|
||||
const abortError = new Error('abort');
|
||||
abortError.name = 'AbortError';
|
||||
mockRunAgentFn = vi.fn().mockRejectedValue(abortError);
|
||||
@@ -1136,7 +1148,7 @@ describe('execution-service.ts', () => {
|
||||
mockLoadContextFilesFn
|
||||
);
|
||||
|
||||
await svc.executeFeature('/test/project', 'feature-1');
|
||||
await svc.executeFeature('/test/project', 'feature-1', false, true);
|
||||
|
||||
// Should emit feature_complete with stopped by user
|
||||
expect(mockEventBus.emitAutoModeEvent).toHaveBeenCalledWith(
|
||||
@@ -1155,6 +1167,47 @@ describe('execution-service.ts', () => {
|
||||
expect(errorCalls.length).toBe(0);
|
||||
});
|
||||
|
||||
it('handles abort signal without emitting feature_complete when isAutoMode=false', async () => {
|
||||
const abortError = new Error('abort');
|
||||
abortError.name = 'AbortError';
|
||||
mockRunAgentFn = vi.fn().mockRejectedValue(abortError);
|
||||
|
||||
const svc = new ExecutionService(
|
||||
mockEventBus,
|
||||
mockConcurrencyManager,
|
||||
mockWorktreeResolver,
|
||||
mockSettingsService,
|
||||
mockRunAgentFn,
|
||||
mockExecutePipelineFn,
|
||||
mockUpdateFeatureStatusFn,
|
||||
mockLoadFeatureFn,
|
||||
mockGetPlanningPromptPrefixFn,
|
||||
mockSaveFeatureSummaryFn,
|
||||
mockRecordLearningsFn,
|
||||
mockContextExistsFn,
|
||||
mockResumeFeatureFn,
|
||||
mockTrackFailureFn,
|
||||
mockSignalPauseFn,
|
||||
mockRecordSuccessFn,
|
||||
mockSaveExecutionStateFn,
|
||||
mockLoadContextFilesFn
|
||||
);
|
||||
|
||||
await svc.executeFeature('/test/project', 'feature-1', false, false);
|
||||
|
||||
// Should NOT emit feature_complete when isAutoMode is false
|
||||
const completeCalls = vi
|
||||
.mocked(mockEventBus.emitAutoModeEvent)
|
||||
.mock.calls.filter((call) => call[0] === 'auto_mode_feature_complete');
|
||||
expect(completeCalls.length).toBe(0);
|
||||
|
||||
// Should NOT emit error event (abort is not an error)
|
||||
const errorCalls = vi
|
||||
.mocked(mockEventBus.emitAutoModeEvent)
|
||||
.mock.calls.filter((call) => call[0] === 'auto_mode_error');
|
||||
expect(errorCalls.length).toBe(0);
|
||||
});
|
||||
|
||||
it('releases running feature even on error', async () => {
|
||||
const testError = new Error('Test error');
|
||||
mockRunAgentFn = vi.fn().mockRejectedValue(testError);
|
||||
@@ -1339,8 +1392,8 @@ describe('execution-service.ts', () => {
|
||||
it('handles missing agent output gracefully', async () => {
|
||||
vi.mocked(secureFs.readFile).mockRejectedValue(new Error('ENOENT'));
|
||||
|
||||
// Should not throw
|
||||
await service.executeFeature('/test/project', 'feature-1');
|
||||
// Should not throw (isAutoMode=true so event is emitted)
|
||||
await service.executeFeature('/test/project', 'feature-1', false, true);
|
||||
|
||||
// Feature should still complete successfully
|
||||
expect(mockEventBus.emitAutoModeEvent).toHaveBeenCalledWith(
|
||||
|
||||
@@ -170,14 +170,16 @@ describe('PipelineOrchestrator', () => {
|
||||
} as unknown as WorktreeResolver;
|
||||
|
||||
mockConcurrencyManager = {
|
||||
acquire: vi.fn().mockReturnValue({
|
||||
featureId: 'feature-1',
|
||||
acquire: vi.fn().mockImplementation(({ featureId, isAutoMode }) => ({
|
||||
featureId,
|
||||
projectPath: '/test/project',
|
||||
abortController: new AbortController(),
|
||||
branchName: null,
|
||||
worktreePath: null,
|
||||
}),
|
||||
isAutoMode: isAutoMode ?? false,
|
||||
})),
|
||||
release: vi.fn(),
|
||||
getRunningFeature: vi.fn().mockReturnValue(undefined),
|
||||
} as unknown as ConcurrencyManager;
|
||||
|
||||
mockSettingsService = null;
|
||||
@@ -541,8 +543,18 @@ describe('PipelineOrchestrator', () => {
|
||||
);
|
||||
});
|
||||
|
||||
it('should emit auto_mode_feature_complete on success', async () => {
|
||||
it('should emit auto_mode_feature_complete on success when isAutoMode is true', async () => {
|
||||
vi.mocked(performMerge).mockResolvedValue({ success: true });
|
||||
vi.mocked(mockConcurrencyManager.getRunningFeature).mockReturnValue({
|
||||
featureId: 'feature-1',
|
||||
projectPath: '/test/project',
|
||||
abortController: new AbortController(),
|
||||
branchName: null,
|
||||
worktreePath: null,
|
||||
isAutoMode: true,
|
||||
startTime: Date.now(),
|
||||
leaseCount: 1,
|
||||
});
|
||||
|
||||
const context = createMergeContext();
|
||||
await orchestrator.attemptMerge(context);
|
||||
@@ -553,6 +565,19 @@ describe('PipelineOrchestrator', () => {
|
||||
);
|
||||
});
|
||||
|
||||
it('should not emit auto_mode_feature_complete on success when isAutoMode is false', async () => {
|
||||
vi.mocked(performMerge).mockResolvedValue({ success: true });
|
||||
vi.mocked(mockConcurrencyManager.getRunningFeature).mockReturnValue(undefined);
|
||||
|
||||
const context = createMergeContext();
|
||||
await orchestrator.attemptMerge(context);
|
||||
|
||||
const completeCalls = vi
|
||||
.mocked(mockEventBus.emitAutoModeEvent)
|
||||
.mock.calls.filter((call) => call[0] === 'auto_mode_feature_complete');
|
||||
expect(completeCalls.length).toBe(0);
|
||||
});
|
||||
|
||||
it('should return needsAgentResolution true on conflict', async () => {
|
||||
vi.mocked(performMerge).mockResolvedValue({
|
||||
success: false,
|
||||
@@ -623,13 +648,24 @@ describe('PipelineOrchestrator', () => {
|
||||
expect(mockExecuteFeatureFn).toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('should complete feature when step no longer exists', async () => {
|
||||
it('should complete feature when step no longer exists and emit event when isAutoMode=true', async () => {
|
||||
const invalidPipelineInfo: PipelineStatusInfo = {
|
||||
...validPipelineInfo,
|
||||
stepIndex: -1,
|
||||
step: null,
|
||||
};
|
||||
|
||||
vi.mocked(mockConcurrencyManager.getRunningFeature).mockReturnValue({
|
||||
featureId: 'feature-1',
|
||||
projectPath: '/test/project',
|
||||
abortController: new AbortController(),
|
||||
branchName: null,
|
||||
worktreePath: null,
|
||||
isAutoMode: true,
|
||||
startTime: Date.now(),
|
||||
leaseCount: 1,
|
||||
});
|
||||
|
||||
await orchestrator.resumePipeline('/test/project', testFeature, true, invalidPipelineInfo);
|
||||
|
||||
expect(mockUpdateFeatureStatusFn).toHaveBeenCalledWith(
|
||||
@@ -642,6 +678,28 @@ describe('PipelineOrchestrator', () => {
|
||||
expect.objectContaining({ message: expect.stringContaining('no longer exists') })
|
||||
);
|
||||
});
|
||||
|
||||
it('should not emit feature_complete when step no longer exists and isAutoMode=false', async () => {
|
||||
const invalidPipelineInfo: PipelineStatusInfo = {
|
||||
...validPipelineInfo,
|
||||
stepIndex: -1,
|
||||
step: null,
|
||||
};
|
||||
|
||||
vi.mocked(mockConcurrencyManager.getRunningFeature).mockReturnValue(undefined);
|
||||
|
||||
await orchestrator.resumePipeline('/test/project', testFeature, true, invalidPipelineInfo);
|
||||
|
||||
expect(mockUpdateFeatureStatusFn).toHaveBeenCalledWith(
|
||||
'/test/project',
|
||||
'feature-1',
|
||||
'verified'
|
||||
);
|
||||
const completeCalls = vi
|
||||
.mocked(mockEventBus.emitAutoModeEvent)
|
||||
.mock.calls.filter((call) => call[0] === 'auto_mode_feature_complete');
|
||||
expect(completeCalls.length).toBe(0);
|
||||
});
|
||||
});
|
||||
|
||||
describe('resumeFromStep', () => {
|
||||
@@ -666,7 +724,7 @@ describe('PipelineOrchestrator', () => {
|
||||
expect(mockRunAgentFn).toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('should complete feature when all remaining steps excluded', async () => {
|
||||
it('should complete feature when all remaining steps excluded and emit event when isAutoMode=true', async () => {
|
||||
const featureWithAllExcluded: Feature = {
|
||||
...testFeature,
|
||||
excludedPipelineSteps: ['step-1', 'step-2'],
|
||||
@@ -674,6 +732,16 @@ describe('PipelineOrchestrator', () => {
|
||||
|
||||
vi.mocked(pipelineService.getNextStatus).mockReturnValue('verified');
|
||||
vi.mocked(pipelineService.isPipelineStatus).mockReturnValue(false);
|
||||
vi.mocked(mockConcurrencyManager.getRunningFeature).mockReturnValue({
|
||||
featureId: 'feature-1',
|
||||
projectPath: '/test/project',
|
||||
abortController: new AbortController(),
|
||||
branchName: null,
|
||||
worktreePath: null,
|
||||
isAutoMode: true,
|
||||
startTime: Date.now(),
|
||||
leaseCount: 1,
|
||||
});
|
||||
|
||||
await orchestrator.resumeFromStep(
|
||||
'/test/project',
|
||||
@@ -1033,7 +1101,7 @@ describe('PipelineOrchestrator', () => {
|
||||
);
|
||||
});
|
||||
|
||||
it('handles all steps excluded during resume', async () => {
|
||||
it('handles all steps excluded during resume and emits event when isAutoMode=true', async () => {
|
||||
const featureWithAllExcluded: Feature = {
|
||||
...testFeature,
|
||||
excludedPipelineSteps: ['step-1', 'step-2'],
|
||||
@@ -1041,6 +1109,16 @@ describe('PipelineOrchestrator', () => {
|
||||
|
||||
vi.mocked(pipelineService.getNextStatus).mockReturnValue('verified');
|
||||
vi.mocked(pipelineService.isPipelineStatus).mockReturnValue(false);
|
||||
vi.mocked(mockConcurrencyManager.getRunningFeature).mockReturnValue({
|
||||
featureId: 'feature-1',
|
||||
projectPath: '/test/project',
|
||||
abortController: new AbortController(),
|
||||
branchName: null,
|
||||
worktreePath: null,
|
||||
isAutoMode: true,
|
||||
startTime: Date.now(),
|
||||
leaseCount: 1,
|
||||
});
|
||||
|
||||
await orchestrator.resumeFromStep(
|
||||
'/test/project',
|
||||
|
||||
@@ -117,6 +117,8 @@ const eslintConfig = defineConfig([
|
||||
Electron: 'readonly',
|
||||
// Console
|
||||
console: 'readonly',
|
||||
// Structured clone (modern browser/Node API)
|
||||
structuredClone: 'readonly',
|
||||
// Vite defines
|
||||
__APP_VERSION__: 'readonly',
|
||||
__APP_BUILD_HASH__: 'readonly',
|
||||
|
||||
@@ -1,9 +1,28 @@
|
||||
# Map for conditional WebSocket upgrade header
|
||||
map $http_upgrade $connection_upgrade {
|
||||
default upgrade;
|
||||
'' close;
|
||||
}
|
||||
|
||||
server {
|
||||
listen 80;
|
||||
server_name localhost;
|
||||
root /usr/share/nginx/html;
|
||||
index index.html;
|
||||
|
||||
# Proxy API and WebSocket requests to the backend server container
|
||||
# Handles both HTTP API calls and WebSocket upgrades (/api/events, /api/terminal/ws)
|
||||
location /api/ {
|
||||
proxy_pass http://server:3008;
|
||||
proxy_http_version 1.1;
|
||||
proxy_set_header Upgrade $http_upgrade;
|
||||
proxy_set_header Connection $connection_upgrade;
|
||||
proxy_set_header Host $host;
|
||||
proxy_set_header X-Real-IP $remote_addr;
|
||||
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
|
||||
proxy_set_header X-Forwarded-Proto $scheme;
|
||||
}
|
||||
|
||||
location / {
|
||||
try_files $uri $uri/ /index.html;
|
||||
}
|
||||
|
||||
@@ -5,4 +5,6 @@ export { FileBrowserDialog } from './file-browser-dialog';
|
||||
export { NewProjectModal } from './new-project-modal';
|
||||
export { SandboxRejectionScreen } from './sandbox-rejection-screen';
|
||||
export { SandboxRiskDialog } from './sandbox-risk-dialog';
|
||||
export { PRCommentResolutionDialog } from './pr-comment-resolution-dialog';
|
||||
export type { PRCommentResolutionPRInfo } from './pr-comment-resolution-dialog';
|
||||
export { WorkspacePickerModal } from './workspace-picker-modal';
|
||||
|
||||
1148
apps/ui/src/components/dialogs/pr-comment-resolution-dialog.tsx
Normal file
1148
apps/ui/src/components/dialogs/pr-comment-resolution-dialog.tsx
Normal file
File diff suppressed because it is too large
Load Diff
@@ -1,4 +1,4 @@
|
||||
import { useState, useCallback, useEffect } from 'react';
|
||||
import { useState, useCallback, useEffect, startTransition } from 'react';
|
||||
import { Plus, Bug, FolderOpen, BookOpen } from 'lucide-react';
|
||||
import { useNavigate, useLocation } from '@tanstack/react-router';
|
||||
import { cn, isMac } from '@/lib/utils';
|
||||
@@ -103,10 +103,26 @@ export function ProjectSwitcher() {
|
||||
};
|
||||
|
||||
const handleProjectClick = useCallback(
|
||||
(project: Project) => {
|
||||
setCurrentProject(project);
|
||||
// Navigate to board view when switching projects
|
||||
navigate({ to: '/board' });
|
||||
async (project: Project) => {
|
||||
try {
|
||||
// Ensure .automaker directory structure exists before switching
|
||||
await initializeProject(project.path);
|
||||
} catch (error) {
|
||||
console.error('Failed to initialize project during switch:', error);
|
||||
// Continue with switch even if initialization fails -
|
||||
// the project may already be initialized
|
||||
}
|
||||
// Wrap in startTransition to let React batch the project switch and
|
||||
// navigation into a single low-priority update. Without this, the two
|
||||
// synchronous calls fire separate renders where currentProject points
|
||||
// to the new project but per-project state (worktrees, features) is
|
||||
// still stale, causing a cascade of effects and store mutations that
|
||||
// can trigger React error #185 (maximum update depth exceeded).
|
||||
startTransition(() => {
|
||||
setCurrentProject(project);
|
||||
// Navigate to board view when switching projects
|
||||
navigate({ to: '/board' });
|
||||
});
|
||||
},
|
||||
[setCurrentProject, navigate]
|
||||
);
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import { useCallback } from 'react';
|
||||
import {
|
||||
Folder,
|
||||
ChevronDown,
|
||||
@@ -15,6 +16,8 @@ import {
|
||||
} from 'lucide-react';
|
||||
import { cn } from '@/lib/utils';
|
||||
import { formatShortcut, type ThemeMode, useAppStore } from '@/store/app-store';
|
||||
import { initializeProject } from '@/lib/project-init';
|
||||
import type { Project } from '@/lib/electron';
|
||||
import {
|
||||
DropdownMenu,
|
||||
DropdownMenuContent,
|
||||
@@ -87,6 +90,22 @@ export function ProjectSelectorWithOptions({
|
||||
} = useAppStore();
|
||||
|
||||
const shortcuts = useKeyboardShortcutsConfig();
|
||||
// Wrap setCurrentProject to ensure .automaker is initialized before switching
|
||||
const setCurrentProjectWithInit = useCallback(
|
||||
async (p: Project) => {
|
||||
try {
|
||||
// Ensure .automaker directory structure exists before switching
|
||||
await initializeProject(p.path);
|
||||
} catch (error) {
|
||||
console.error('Failed to initialize project during switch:', error);
|
||||
// Continue with switch even if initialization fails -
|
||||
// the project may already be initialized
|
||||
}
|
||||
setCurrentProject(p);
|
||||
},
|
||||
[setCurrentProject]
|
||||
);
|
||||
|
||||
const {
|
||||
projectSearchQuery,
|
||||
setProjectSearchQuery,
|
||||
@@ -99,7 +118,7 @@ export function ProjectSelectorWithOptions({
|
||||
currentProject,
|
||||
isProjectPickerOpen,
|
||||
setIsProjectPickerOpen,
|
||||
setCurrentProject,
|
||||
setCurrentProject: setCurrentProjectWithInit,
|
||||
});
|
||||
|
||||
const { sensors, handleDragEnd } = useDragAndDrop({ projects, reorderProjects });
|
||||
@@ -107,6 +126,14 @@ export function ProjectSelectorWithOptions({
|
||||
const { globalTheme, setProjectTheme, setPreviewTheme, handlePreviewEnter, handlePreviewLeave } =
|
||||
useProjectTheme();
|
||||
|
||||
const handleSelectProject = useCallback(
|
||||
async (p: Project) => {
|
||||
await setCurrentProjectWithInit(p);
|
||||
setIsProjectPickerOpen(false);
|
||||
},
|
||||
[setCurrentProjectWithInit, setIsProjectPickerOpen]
|
||||
);
|
||||
|
||||
if (!sidebarOpen || projects.length === 0) {
|
||||
return null;
|
||||
}
|
||||
@@ -204,10 +231,7 @@ export function ProjectSelectorWithOptions({
|
||||
project={project}
|
||||
currentProjectId={currentProject?.id}
|
||||
isHighlighted={index === selectedProjectIndex}
|
||||
onSelect={(p) => {
|
||||
setCurrentProject(p);
|
||||
setIsProjectPickerOpen(false);
|
||||
}}
|
||||
onSelect={handleSelectProject}
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
|
||||
@@ -6,7 +6,7 @@ interface UseProjectPickerProps {
|
||||
currentProject: Project | null;
|
||||
isProjectPickerOpen: boolean;
|
||||
setIsProjectPickerOpen: (value: boolean | ((prev: boolean) => boolean)) => void;
|
||||
setCurrentProject: (project: Project) => void;
|
||||
setCurrentProject: (project: Project) => void | Promise<void>;
|
||||
}
|
||||
|
||||
export function useProjectPicker({
|
||||
@@ -92,9 +92,9 @@ export function useProjectPicker({
|
||||
}, [selectedProjectIndex, isProjectPickerOpen, filteredProjects, scrollToProject]);
|
||||
|
||||
// Handle selecting the currently highlighted project
|
||||
const selectHighlightedProject = useCallback(() => {
|
||||
const selectHighlightedProject = useCallback(async () => {
|
||||
if (filteredProjects.length > 0 && selectedProjectIndex < filteredProjects.length) {
|
||||
setCurrentProject(filteredProjects[selectedProjectIndex]);
|
||||
await setCurrentProject(filteredProjects[selectedProjectIndex]);
|
||||
setIsProjectPickerOpen(false);
|
||||
}
|
||||
}, [filteredProjects, selectedProjectIndex, setCurrentProject, setIsProjectPickerOpen]);
|
||||
@@ -108,7 +108,9 @@ export function useProjectPicker({
|
||||
setIsProjectPickerOpen(false);
|
||||
} else if (event.key === 'Enter') {
|
||||
event.preventDefault();
|
||||
selectHighlightedProject();
|
||||
selectHighlightedProject().catch(() => {
|
||||
/* Error already logged upstream */
|
||||
});
|
||||
} else if (event.key === 'ArrowDown') {
|
||||
event.preventDefault();
|
||||
setSelectedProjectIndex((prev) => (prev < filteredProjects.length - 1 ? prev + 1 : prev));
|
||||
|
||||
@@ -25,7 +25,7 @@ export interface SortableProjectItemProps {
|
||||
project: Project;
|
||||
currentProjectId: string | undefined;
|
||||
isHighlighted: boolean;
|
||||
onSelect: (project: Project) => void;
|
||||
onSelect: (project: Project) => void | Promise<void>;
|
||||
}
|
||||
|
||||
export interface ThemeMenuItemProps {
|
||||
|
||||
@@ -19,7 +19,7 @@ import {
|
||||
ArchiveRestore,
|
||||
} from 'lucide-react';
|
||||
import { Spinner } from '@/components/ui/spinner';
|
||||
import { cn } from '@/lib/utils';
|
||||
import { cn, pathsEqual } from '@/lib/utils';
|
||||
import type { SessionListItem } from '@/types/electron';
|
||||
import { useKeyboardShortcutsConfig } from '@/hooks/use-keyboard-shortcuts';
|
||||
import { getElectronAPI } from '@/lib/electron';
|
||||
@@ -93,6 +93,7 @@ interface SessionManagerProps {
|
||||
currentSessionId: string | null;
|
||||
onSelectSession: (sessionId: string | null) => void;
|
||||
projectPath: string;
|
||||
workingDirectory?: string; // Current worktree path for scoping sessions
|
||||
isCurrentSessionThinking?: boolean;
|
||||
onQuickCreateRef?: React.MutableRefObject<(() => Promise<void>) | null>;
|
||||
}
|
||||
@@ -101,6 +102,7 @@ export function SessionManager({
|
||||
currentSessionId,
|
||||
onSelectSession,
|
||||
projectPath,
|
||||
workingDirectory,
|
||||
isCurrentSessionThinking = false,
|
||||
onQuickCreateRef,
|
||||
}: SessionManagerProps) {
|
||||
@@ -153,6 +155,7 @@ export function SessionManager({
|
||||
if (result.data) {
|
||||
await checkRunningSessions(result.data);
|
||||
}
|
||||
return result;
|
||||
}, [queryClient, refetchSessions, checkRunningSessions]);
|
||||
|
||||
// Check running state on initial load (runs only once when sessions first load)
|
||||
@@ -177,6 +180,9 @@ export function SessionManager({
|
||||
return () => clearInterval(interval);
|
||||
}, [sessions, runningSessions.size, isCurrentSessionThinking, checkRunningSessions]);
|
||||
|
||||
// Effective working directory for session creation (worktree path or project path)
|
||||
const effectiveWorkingDirectory = workingDirectory || projectPath;
|
||||
|
||||
// Create new session with random name
|
||||
const handleCreateSession = async () => {
|
||||
const api = getElectronAPI();
|
||||
@@ -184,7 +190,7 @@ export function SessionManager({
|
||||
|
||||
const sessionName = newSessionName.trim() || generateRandomSessionName();
|
||||
|
||||
const result = await api.sessions.create(sessionName, projectPath, projectPath);
|
||||
const result = await api.sessions.create(sessionName, projectPath, effectiveWorkingDirectory);
|
||||
|
||||
if (result.success && result.session?.id) {
|
||||
setNewSessionName('');
|
||||
@@ -195,19 +201,19 @@ export function SessionManager({
|
||||
};
|
||||
|
||||
// Create new session directly with a random name (one-click)
|
||||
const handleQuickCreateSession = async () => {
|
||||
const handleQuickCreateSession = useCallback(async () => {
|
||||
const api = getElectronAPI();
|
||||
if (!api?.sessions) return;
|
||||
|
||||
const sessionName = generateRandomSessionName();
|
||||
|
||||
const result = await api.sessions.create(sessionName, projectPath, projectPath);
|
||||
const result = await api.sessions.create(sessionName, projectPath, effectiveWorkingDirectory);
|
||||
|
||||
if (result.success && result.session?.id) {
|
||||
await invalidateSessions();
|
||||
onSelectSession(result.session.id);
|
||||
}
|
||||
};
|
||||
}, [effectiveWorkingDirectory, projectPath, invalidateSessions, onSelectSession]);
|
||||
|
||||
// Expose the quick create function via ref for keyboard shortcuts
|
||||
useEffect(() => {
|
||||
@@ -219,7 +225,7 @@ export function SessionManager({
|
||||
onQuickCreateRef.current = null;
|
||||
}
|
||||
};
|
||||
}, [onQuickCreateRef, projectPath]);
|
||||
}, [onQuickCreateRef, handleQuickCreateSession]);
|
||||
|
||||
// Rename session
|
||||
const handleRenameSession = async (sessionId: string) => {
|
||||
@@ -292,10 +298,16 @@ export function SessionManager({
|
||||
|
||||
const result = await api.sessions.delete(sessionId);
|
||||
if (result.success) {
|
||||
await invalidateSessions();
|
||||
const refetchResult = await invalidateSessions();
|
||||
if (currentSessionId === sessionId) {
|
||||
// Switch to another session or create a new one
|
||||
const activeSessionsList = sessions.filter((s) => !s.isArchived);
|
||||
// Switch to another session using fresh data, excluding the deleted session
|
||||
// Filter to sessions within the same worktree to avoid jumping to a different worktree
|
||||
const freshSessions = refetchResult?.data ?? [];
|
||||
const activeSessionsList = freshSessions.filter((s) => {
|
||||
if (s.isArchived || s.id === sessionId) return false;
|
||||
const sessionDir = s.workingDirectory || s.projectPath;
|
||||
return pathsEqual(sessionDir, effectiveWorkingDirectory);
|
||||
});
|
||||
if (activeSessionsList.length > 0) {
|
||||
onSelectSession(activeSessionsList[0].id);
|
||||
}
|
||||
@@ -318,8 +330,16 @@ export function SessionManager({
|
||||
setIsDeleteAllArchivedDialogOpen(false);
|
||||
};
|
||||
|
||||
const activeSessions = sessions.filter((s) => !s.isArchived);
|
||||
const archivedSessions = sessions.filter((s) => s.isArchived);
|
||||
// Filter sessions by current working directory (worktree scoping)
|
||||
const scopedSessions = sessions.filter((s) => {
|
||||
const sessionDir = s.workingDirectory || s.projectPath;
|
||||
// Match sessions whose workingDirectory matches the current effective directory
|
||||
// Use pathsEqual for cross-platform path normalization (trailing slashes, separators)
|
||||
return pathsEqual(sessionDir, effectiveWorkingDirectory);
|
||||
});
|
||||
|
||||
const activeSessions = scopedSessions.filter((s) => !s.isArchived);
|
||||
const archivedSessions = scopedSessions.filter((s) => s.isArchived);
|
||||
const displayedSessions = activeTab === 'active' ? activeSessions : archivedSessions;
|
||||
|
||||
return (
|
||||
|
||||
205
apps/ui/src/components/ui/app-error-boundary.tsx
Normal file
205
apps/ui/src/components/ui/app-error-boundary.tsx
Normal file
@@ -0,0 +1,205 @@
|
||||
import { Component, type ReactNode, type ErrorInfo } from 'react';
|
||||
import { createLogger } from '@automaker/utils/logger';
|
||||
|
||||
const logger = createLogger('AppErrorBoundary');
|
||||
|
||||
interface Props {
|
||||
children: ReactNode;
|
||||
}
|
||||
|
||||
interface State {
|
||||
hasError: boolean;
|
||||
error: Error | null;
|
||||
isCrashLoop: boolean;
|
||||
}
|
||||
|
||||
/** Key used to track recent crash timestamps for crash loop detection */
|
||||
const CRASH_TIMESTAMPS_KEY = 'automaker-crash-timestamps';
|
||||
/** Number of crashes within the time window that constitutes a crash loop */
|
||||
const CRASH_LOOP_THRESHOLD = 3;
|
||||
/** Time window in ms for crash loop detection (30 seconds) */
|
||||
const CRASH_LOOP_WINDOW_MS = 30_000;
|
||||
|
||||
/**
|
||||
* Root-level error boundary for the entire application.
|
||||
*
|
||||
* Catches uncaught React errors that would otherwise show TanStack Router's
|
||||
* default "Something went wrong!" screen with a raw error message.
|
||||
*
|
||||
* Provides a user-friendly error screen with a reload button to recover.
|
||||
* This is especially important for transient errors during initial app load
|
||||
* (e.g., race conditions during auth/hydration on fresh browser sessions).
|
||||
*
|
||||
* Includes crash loop detection: if the app crashes 3+ times within 30 seconds,
|
||||
* the UI cache is automatically cleared to break loops caused by stale cached
|
||||
* worktree paths or other corrupt persisted state.
|
||||
*/
|
||||
export class AppErrorBoundary extends Component<Props, State> {
|
||||
constructor(props: Props) {
|
||||
super(props);
|
||||
this.state = { hasError: false, error: null, isCrashLoop: false };
|
||||
}
|
||||
|
||||
static getDerivedStateFromError(error: Error): Partial<State> {
|
||||
return { hasError: true, error };
|
||||
}
|
||||
|
||||
componentDidCatch(error: Error, errorInfo: ErrorInfo) {
|
||||
logger.error('Uncaught application error:', {
|
||||
error: error.message,
|
||||
stack: error.stack,
|
||||
componentStack: errorInfo.componentStack,
|
||||
});
|
||||
|
||||
// Track crash timestamps to detect crash loops.
|
||||
// If the app crashes multiple times in quick succession, it's likely due to
|
||||
// stale cached data (e.g., worktree paths that no longer exist on disk).
|
||||
try {
|
||||
const now = Date.now();
|
||||
const raw = sessionStorage.getItem(CRASH_TIMESTAMPS_KEY);
|
||||
const timestamps: number[] = raw ? JSON.parse(raw) : [];
|
||||
timestamps.push(now);
|
||||
// Keep only timestamps within the detection window
|
||||
const recent = timestamps.filter((t) => now - t < CRASH_LOOP_WINDOW_MS);
|
||||
sessionStorage.setItem(CRASH_TIMESTAMPS_KEY, JSON.stringify(recent));
|
||||
|
||||
if (recent.length >= CRASH_LOOP_THRESHOLD) {
|
||||
logger.error(
|
||||
`Crash loop detected (${recent.length} crashes in ${CRASH_LOOP_WINDOW_MS}ms) — clearing UI cache`
|
||||
);
|
||||
// Auto-clear the UI cache to break the loop
|
||||
localStorage.removeItem('automaker-ui-cache');
|
||||
sessionStorage.removeItem(CRASH_TIMESTAMPS_KEY);
|
||||
this.setState({ isCrashLoop: true });
|
||||
}
|
||||
} catch {
|
||||
// Storage may be unavailable — ignore
|
||||
}
|
||||
}
|
||||
|
||||
handleReload = () => {
|
||||
window.location.reload();
|
||||
};
|
||||
|
||||
handleClearCacheAndReload = () => {
|
||||
// Clear the UI cache store that persists worktree selections and other UI state.
|
||||
// This breaks crash loops caused by stale worktree paths that no longer exist on disk.
|
||||
try {
|
||||
localStorage.removeItem('automaker-ui-cache');
|
||||
} catch {
|
||||
// localStorage may be unavailable in some contexts
|
||||
}
|
||||
window.location.reload();
|
||||
};
|
||||
|
||||
render() {
|
||||
if (this.state.hasError) {
|
||||
return (
|
||||
<div
|
||||
className="flex h-screen w-full flex-col items-center justify-center gap-6 bg-background p-6 text-foreground"
|
||||
data-testid="app-error-boundary"
|
||||
>
|
||||
{/* Logo matching the app shell in index.html */}
|
||||
<svg
|
||||
className="h-14 w-14 opacity-90"
|
||||
viewBox="0 0 256 256"
|
||||
xmlns="http://www.w3.org/2000/svg"
|
||||
aria-hidden="true"
|
||||
>
|
||||
<rect
|
||||
className="fill-foreground/[0.08]"
|
||||
x="16"
|
||||
y="16"
|
||||
width="224"
|
||||
height="224"
|
||||
rx="56"
|
||||
/>
|
||||
<g
|
||||
className="stroke-foreground/70"
|
||||
fill="none"
|
||||
strokeWidth="20"
|
||||
strokeLinecap="round"
|
||||
strokeLinejoin="round"
|
||||
>
|
||||
<path d="M92 92 L52 128 L92 164" />
|
||||
<path d="M144 72 L116 184" />
|
||||
<path d="M164 92 L204 128 L164 164" />
|
||||
</g>
|
||||
</svg>
|
||||
|
||||
<div className="text-center space-y-2">
|
||||
<h1 className="text-xl font-semibold">Something went wrong</h1>
|
||||
<p className="text-sm text-muted-foreground max-w-md">
|
||||
{this.state.isCrashLoop
|
||||
? 'The application crashed repeatedly, likely due to stale cached data. The cache has been cleared automatically. Reload to continue.'
|
||||
: 'The application encountered an unexpected error. This is usually temporary and can be resolved by reloading the page.'}
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<div className="flex items-center gap-3">
|
||||
<button
|
||||
type="button"
|
||||
onClick={this.handleReload}
|
||||
className="inline-flex items-center gap-2 rounded-md border border-border bg-background px-4 py-2 text-sm font-medium text-foreground shadow-sm transition-colors hover:bg-muted focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring"
|
||||
>
|
||||
<svg
|
||||
className="h-4 w-4"
|
||||
xmlns="http://www.w3.org/2000/svg"
|
||||
viewBox="0 0 24 24"
|
||||
fill="none"
|
||||
stroke="currentColor"
|
||||
strokeWidth="2"
|
||||
strokeLinecap="round"
|
||||
strokeLinejoin="round"
|
||||
aria-hidden="true"
|
||||
>
|
||||
<path d="M21 12a9 9 0 0 0-9-9 9.75 9.75 0 0 0-6.74 2.74L3 8" />
|
||||
<path d="M3 3v5h5" />
|
||||
<path d="M3 12a9 9 0 0 0 9 9 9.75 9.75 0 0 0 6.74-2.74L21 16" />
|
||||
<path d="M16 21h5v-5" />
|
||||
</svg>
|
||||
Reload Page
|
||||
</button>
|
||||
|
||||
<button
|
||||
type="button"
|
||||
onClick={this.handleClearCacheAndReload}
|
||||
className="inline-flex items-center gap-2 rounded-md border border-border bg-background px-4 py-2 text-sm font-medium text-muted-foreground shadow-sm transition-colors hover:bg-muted hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring"
|
||||
>
|
||||
<svg
|
||||
className="h-4 w-4"
|
||||
xmlns="http://www.w3.org/2000/svg"
|
||||
viewBox="0 0 24 24"
|
||||
fill="none"
|
||||
stroke="currentColor"
|
||||
strokeWidth="2"
|
||||
strokeLinecap="round"
|
||||
strokeLinejoin="round"
|
||||
aria-hidden="true"
|
||||
>
|
||||
<path d="M3 6h18" />
|
||||
<path d="M19 6v14c0 1-1 2-2 2H7c-1 0-2-1-2-2V6" />
|
||||
<path d="M8 6V4c0-1 1-2 2-2h4c1 0 2 1 2 2v2" />
|
||||
</svg>
|
||||
Clear Cache & Reload
|
||||
</button>
|
||||
</div>
|
||||
|
||||
{/* Collapsible technical details for debugging */}
|
||||
{this.state.error && (
|
||||
<details className="text-xs text-muted-foreground max-w-lg w-full">
|
||||
<summary className="cursor-pointer hover:text-foreground text-center">
|
||||
Technical details
|
||||
</summary>
|
||||
<pre className="mt-2 p-3 bg-muted/50 rounded-md text-left overflow-auto max-h-32 border border-border">
|
||||
{this.state.error.stack || this.state.error.message}
|
||||
</pre>
|
||||
</details>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
return this.props.children;
|
||||
}
|
||||
}
|
||||
@@ -20,9 +20,13 @@ import { AgentInputArea } from './agent-view/input-area';
|
||||
const LG_BREAKPOINT = 1024;
|
||||
|
||||
export function AgentView() {
|
||||
const { currentProject } = useAppStore();
|
||||
const { currentProject, getCurrentWorktree } = useAppStore();
|
||||
const [input, setInput] = useState('');
|
||||
const [currentTool, setCurrentTool] = useState<string | null>(null);
|
||||
|
||||
// Get the current worktree to scope sessions and agent working directory
|
||||
const currentWorktree = currentProject ? getCurrentWorktree(currentProject.path) : null;
|
||||
const effectiveWorkingDirectory = currentWorktree?.path || currentProject?.path;
|
||||
// Initialize session manager state - starts as true to match SSR
|
||||
// Then updates on mount based on actual screen size to prevent hydration mismatch
|
||||
const [showSessionManager, setShowSessionManager] = useState(true);
|
||||
@@ -52,9 +56,10 @@ export function AgentView() {
|
||||
// Guard to prevent concurrent invocations of handleCreateSessionFromEmptyState
|
||||
const createSessionInFlightRef = useRef(false);
|
||||
|
||||
// Session management hook
|
||||
// Session management hook - scoped to current worktree
|
||||
const { currentSessionId, handleSelectSession } = useAgentSession({
|
||||
projectPath: currentProject?.path,
|
||||
workingDirectory: effectiveWorkingDirectory,
|
||||
});
|
||||
|
||||
// Use the Electron agent hook (only if we have a session)
|
||||
@@ -71,7 +76,7 @@ export function AgentView() {
|
||||
clearServerQueue,
|
||||
} = useElectronAgent({
|
||||
sessionId: currentSessionId || '',
|
||||
workingDirectory: currentProject?.path,
|
||||
workingDirectory: effectiveWorkingDirectory,
|
||||
model: modelSelection.model,
|
||||
thinkingLevel: modelSelection.thinkingLevel,
|
||||
onToolUse: (toolName) => {
|
||||
@@ -229,6 +234,7 @@ export function AgentView() {
|
||||
currentSessionId={currentSessionId}
|
||||
onSelectSession={handleSelectSession}
|
||||
projectPath={currentProject.path}
|
||||
workingDirectory={effectiveWorkingDirectory}
|
||||
isCurrentSessionThinking={isProcessing}
|
||||
onQuickCreateRef={quickCreateSessionRef}
|
||||
/>
|
||||
@@ -248,6 +254,7 @@ export function AgentView() {
|
||||
showSessionManager={showSessionManager}
|
||||
onToggleSessionManager={() => setShowSessionManager(!showSessionManager)}
|
||||
onClearChat={handleClearChat}
|
||||
worktreeBranch={currentWorktree?.branch}
|
||||
/>
|
||||
|
||||
{/* Messages */}
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { Bot, PanelLeftClose, PanelLeft, Wrench, Trash2 } from 'lucide-react';
|
||||
import { Bot, PanelLeftClose, PanelLeft, Wrench, Trash2, GitBranch } from 'lucide-react';
|
||||
import { Button } from '@/components/ui/button';
|
||||
|
||||
interface AgentHeaderProps {
|
||||
@@ -11,6 +11,7 @@ interface AgentHeaderProps {
|
||||
showSessionManager: boolean;
|
||||
onToggleSessionManager: () => void;
|
||||
onClearChat: () => void;
|
||||
worktreeBranch?: string;
|
||||
}
|
||||
|
||||
export function AgentHeader({
|
||||
@@ -23,6 +24,7 @@ export function AgentHeader({
|
||||
showSessionManager,
|
||||
onToggleSessionManager,
|
||||
onClearChat,
|
||||
worktreeBranch,
|
||||
}: AgentHeaderProps) {
|
||||
return (
|
||||
<div className="flex items-center justify-between px-6 py-4 border-b border-border bg-card/50 backdrop-blur-sm">
|
||||
@@ -32,10 +34,18 @@ export function AgentHeader({
|
||||
</div>
|
||||
<div>
|
||||
<h1 className="text-lg font-semibold text-foreground">AI Agent</h1>
|
||||
<p className="text-sm text-muted-foreground">
|
||||
{projectName}
|
||||
{currentSessionId && !isConnected && ' - Connecting...'}
|
||||
</p>
|
||||
<div className="flex items-center gap-2 text-sm text-muted-foreground">
|
||||
<span>
|
||||
{projectName}
|
||||
{currentSessionId && !isConnected && ' - Connecting...'}
|
||||
</span>
|
||||
{worktreeBranch && (
|
||||
<span className="inline-flex items-center gap-1 text-xs bg-muted/50 px-2 py-0.5 rounded-full border border-border">
|
||||
<GitBranch className="w-3 h-3 shrink-0" />
|
||||
<span className="max-w-[180px] truncate">{worktreeBranch}</span>
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
|
||||
@@ -6,6 +6,7 @@ const logger = createLogger('AgentSession');
|
||||
|
||||
interface UseAgentSessionOptions {
|
||||
projectPath: string | undefined;
|
||||
workingDirectory?: string; // Current worktree path for per-worktree session persistence
|
||||
}
|
||||
|
||||
interface UseAgentSessionResult {
|
||||
@@ -13,49 +14,56 @@ interface UseAgentSessionResult {
|
||||
handleSelectSession: (sessionId: string | null) => void;
|
||||
}
|
||||
|
||||
export function useAgentSession({ projectPath }: UseAgentSessionOptions): UseAgentSessionResult {
|
||||
export function useAgentSession({
|
||||
projectPath,
|
||||
workingDirectory,
|
||||
}: UseAgentSessionOptions): UseAgentSessionResult {
|
||||
const { setLastSelectedSession, getLastSelectedSession } = useAppStore();
|
||||
const [currentSessionId, setCurrentSessionId] = useState<string | null>(null);
|
||||
|
||||
// Track if initial session has been loaded
|
||||
const initialSessionLoadedRef = useRef(false);
|
||||
|
||||
// Use workingDirectory as the persistence key so sessions are scoped per worktree
|
||||
const persistenceKey = workingDirectory || projectPath;
|
||||
|
||||
// Handle session selection with persistence
|
||||
const handleSelectSession = useCallback(
|
||||
(sessionId: string | null) => {
|
||||
setCurrentSessionId(sessionId);
|
||||
// Persist the selection for this project
|
||||
if (projectPath) {
|
||||
setLastSelectedSession(projectPath, sessionId);
|
||||
// Persist the selection for this worktree/project
|
||||
if (persistenceKey) {
|
||||
setLastSelectedSession(persistenceKey, sessionId);
|
||||
}
|
||||
},
|
||||
[projectPath, setLastSelectedSession]
|
||||
[persistenceKey, setLastSelectedSession]
|
||||
);
|
||||
|
||||
// Restore last selected session when switching to Agent view or when project changes
|
||||
// Restore last selected session when switching to Agent view or when worktree changes
|
||||
useEffect(() => {
|
||||
if (!projectPath) {
|
||||
if (!persistenceKey) {
|
||||
// No project, reset
|
||||
setCurrentSessionId(null);
|
||||
initialSessionLoadedRef.current = false;
|
||||
return;
|
||||
}
|
||||
|
||||
// Only restore once per project
|
||||
// Only restore once per persistence key
|
||||
if (initialSessionLoadedRef.current) return;
|
||||
initialSessionLoadedRef.current = true;
|
||||
|
||||
const lastSessionId = getLastSelectedSession(projectPath);
|
||||
const lastSessionId = getLastSelectedSession(persistenceKey);
|
||||
if (lastSessionId) {
|
||||
logger.info('Restoring last selected session:', lastSessionId);
|
||||
setCurrentSessionId(lastSessionId);
|
||||
}
|
||||
}, [projectPath, getLastSelectedSession]);
|
||||
}, [persistenceKey, getLastSelectedSession]);
|
||||
|
||||
// Reset initialSessionLoadedRef when project changes
|
||||
// Reset when worktree/project changes - clear current session and allow restore
|
||||
useEffect(() => {
|
||||
initialSessionLoadedRef.current = false;
|
||||
}, [projectPath]);
|
||||
setCurrentSessionId(null);
|
||||
}, [persistenceKey]);
|
||||
|
||||
return {
|
||||
currentSessionId,
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { useEffect, useState, useCallback, useMemo } from 'react';
|
||||
import { useEffect, useState, useCallback, useMemo, useRef } from 'react';
|
||||
import { createLogger } from '@automaker/utils/logger';
|
||||
import type { PointerEvent as ReactPointerEvent } from 'react';
|
||||
import {
|
||||
@@ -33,7 +33,11 @@ import { getHttpApiClient } from '@/lib/http-api-client';
|
||||
import type { BacklogPlanResult, FeatureStatusWithPipeline } from '@automaker/types';
|
||||
import { pathsEqual } from '@/lib/utils';
|
||||
import { toast } from 'sonner';
|
||||
import { BoardBackgroundModal } from '@/components/dialogs/board-background-modal';
|
||||
import {
|
||||
BoardBackgroundModal,
|
||||
PRCommentResolutionDialog,
|
||||
type PRCommentResolutionPRInfo,
|
||||
} from '@/components/dialogs';
|
||||
import { useShallow } from 'zustand/react/shallow';
|
||||
import { useAutoMode } from '@/hooks/use-auto-mode';
|
||||
import { resolveModelString } from '@automaker/model-resolver';
|
||||
@@ -95,6 +99,7 @@ import { useQueryClient } from '@tanstack/react-query';
|
||||
import { queryKeys } from '@/lib/query-keys';
|
||||
import { useAutoModeQueryInvalidation } from '@/hooks/use-query-invalidation';
|
||||
import { useUpdateGlobalSettings } from '@/hooks/mutations/use-settings-mutations';
|
||||
import { forceSyncSettingsToServer } from '@/hooks/use-settings-sync';
|
||||
|
||||
// Stable empty array to avoid infinite loop in selector
|
||||
const EMPTY_WORKTREES: ReturnType<ReturnType<typeof useAppStore.getState>['getWorktrees']> = [];
|
||||
@@ -110,6 +115,7 @@ export function BoardView() {
|
||||
pendingPlanApproval,
|
||||
setPendingPlanApproval,
|
||||
updateFeature,
|
||||
batchUpdateFeatures,
|
||||
getCurrentWorktree,
|
||||
setCurrentWorktree,
|
||||
getWorktrees,
|
||||
@@ -128,6 +134,7 @@ export function BoardView() {
|
||||
pendingPlanApproval: state.pendingPlanApproval,
|
||||
setPendingPlanApproval: state.setPendingPlanApproval,
|
||||
updateFeature: state.updateFeature,
|
||||
batchUpdateFeatures: state.batchUpdateFeatures,
|
||||
getCurrentWorktree: state.getCurrentWorktree,
|
||||
setCurrentWorktree: state.setCurrentWorktree,
|
||||
getWorktrees: state.getWorktrees,
|
||||
@@ -184,6 +191,9 @@ export function BoardView() {
|
||||
const [showCreatePRDialog, setShowCreatePRDialog] = useState(false);
|
||||
const [showCreateBranchDialog, setShowCreateBranchDialog] = useState(false);
|
||||
const [showMergeRebaseDialog, setShowMergeRebaseDialog] = useState(false);
|
||||
const [showPRCommentDialog, setShowPRCommentDialog] = useState(false);
|
||||
const [prCommentDialogPRInfo, setPRCommentDialogPRInfo] =
|
||||
useState<PRCommentResolutionPRInfo | null>(null);
|
||||
const [selectedWorktreeForAction, setSelectedWorktreeForAction] = useState<WorktreeInfo | null>(
|
||||
null
|
||||
);
|
||||
@@ -404,60 +414,115 @@ export function BoardView() {
|
||||
currentProject,
|
||||
});
|
||||
|
||||
// Shared helper: batch-reset branch assignment and persist for each affected feature.
|
||||
// Used when worktrees are deleted or branches are removed during merge.
|
||||
const batchResetBranchFeatures = useCallback(
|
||||
(branchName: string) => {
|
||||
const affectedIds = hookFeatures.filter((f) => f.branchName === branchName).map((f) => f.id);
|
||||
if (affectedIds.length === 0) return;
|
||||
const updates: Partial<Feature> = { branchName: null };
|
||||
batchUpdateFeatures(affectedIds, updates);
|
||||
for (const id of affectedIds) {
|
||||
persistFeatureUpdate(id, updates).catch((err: unknown) => {
|
||||
console.error(
|
||||
`[batchResetBranchFeatures] Failed to persist update for feature ${id}:`,
|
||||
err
|
||||
);
|
||||
});
|
||||
}
|
||||
},
|
||||
[hookFeatures, batchUpdateFeatures, persistFeatureUpdate]
|
||||
);
|
||||
|
||||
// Memoize the removed worktrees handler to prevent infinite loops
|
||||
const handleRemovedWorktrees = useCallback(
|
||||
(removedWorktrees: Array<{ path: string; branch: string }>) => {
|
||||
// Reset features that were assigned to the removed worktrees (by branch)
|
||||
hookFeatures.forEach((feature) => {
|
||||
const matchesRemovedWorktree = removedWorktrees.some((removed) => {
|
||||
// Match by branch name since worktreePath is no longer stored
|
||||
return feature.branchName === removed.branch;
|
||||
});
|
||||
|
||||
if (matchesRemovedWorktree) {
|
||||
// Reset the feature's branch assignment - update both local state and persist
|
||||
const updates = { branchName: null as unknown as string | undefined };
|
||||
updateFeature(feature.id, updates);
|
||||
persistFeatureUpdate(feature.id, updates);
|
||||
}
|
||||
});
|
||||
for (const { branch } of removedWorktrees) {
|
||||
batchResetBranchFeatures(branch);
|
||||
}
|
||||
},
|
||||
[hookFeatures, updateFeature, persistFeatureUpdate]
|
||||
[batchResetBranchFeatures]
|
||||
);
|
||||
|
||||
// Get current worktree info (path) for filtering features
|
||||
// This needs to be before useBoardActions so we can pass currentWorktreeBranch
|
||||
const currentWorktreeInfo = currentProject ? getCurrentWorktree(currentProject.path) : null;
|
||||
const currentWorktreePath = currentWorktreeInfo?.path ?? null;
|
||||
const worktreesByProject = useAppStore((s) => s.worktreesByProject);
|
||||
const worktrees = useMemo(
|
||||
() =>
|
||||
currentProject
|
||||
? (worktreesByProject[currentProject.path] ?? EMPTY_WORKTREES)
|
||||
: EMPTY_WORKTREES,
|
||||
[currentProject, worktreesByProject]
|
||||
|
||||
// Select worktrees for the current project directly from the store.
|
||||
// Using a project-scoped selector prevents re-renders when OTHER projects'
|
||||
// worktrees change (the old selector subscribed to the entire worktreesByProject
|
||||
// object, causing unnecessary re-renders that cascaded into selectedWorktree →
|
||||
// useAutoMode → refreshStatus → setAutoModeRunning → store update → re-render loop
|
||||
// that could trigger React error #185 on initial project open).
|
||||
const currentProjectPath = currentProject?.path;
|
||||
const worktrees = useAppStore(
|
||||
useCallback(
|
||||
(s) =>
|
||||
currentProjectPath
|
||||
? (s.worktreesByProject[currentProjectPath] ?? EMPTY_WORKTREES)
|
||||
: EMPTY_WORKTREES,
|
||||
[currentProjectPath]
|
||||
)
|
||||
);
|
||||
|
||||
// Get the branch for the currently selected worktree
|
||||
// Find the worktree that matches the current selection, or use main worktree
|
||||
//
|
||||
// IMPORTANT: Stabilize the returned object reference using a ref to prevent
|
||||
// cascading re-renders during project switches. The spread `{ ...found, ... }`
|
||||
// creates a new object every time, even when the underlying data is identical.
|
||||
// Without stabilization, the new reference propagates to useAutoMode and other
|
||||
// consumers, contributing to the re-render cascade that triggers React error #185.
|
||||
const prevSelectedWorktreeRef = useRef<WorktreeInfo | undefined>(undefined);
|
||||
const selectedWorktree = useMemo((): WorktreeInfo | undefined => {
|
||||
let found;
|
||||
let usedFallback = false;
|
||||
if (currentWorktreePath === null) {
|
||||
// Primary worktree selected - find the main worktree
|
||||
found = worktrees.find((w) => w.isMain);
|
||||
} else {
|
||||
// Specific worktree selected - find it by path
|
||||
found = worktrees.find((w) => !w.isMain && pathsEqual(w.path, currentWorktreePath));
|
||||
// If the selected worktree no longer exists (e.g. just deleted),
|
||||
// fall back to main to prevent rendering with undefined worktree.
|
||||
// onDeleted will call setCurrentWorktree(…, null) to reset properly.
|
||||
if (!found) {
|
||||
found = worktrees.find((w) => w.isMain);
|
||||
usedFallback = true;
|
||||
}
|
||||
}
|
||||
if (!found) {
|
||||
prevSelectedWorktreeRef.current = undefined;
|
||||
return undefined;
|
||||
}
|
||||
if (!found) return undefined;
|
||||
// Ensure all required WorktreeInfo fields are present
|
||||
return {
|
||||
const result: WorktreeInfo = {
|
||||
...found,
|
||||
isCurrent:
|
||||
found.isCurrent ??
|
||||
(currentWorktreePath !== null ? pathsEqual(found.path, currentWorktreePath) : found.isMain),
|
||||
(usedFallback
|
||||
? found.isMain // treat main as current during the transient fallback render
|
||||
: currentWorktreePath !== null
|
||||
? pathsEqual(found.path, currentWorktreePath)
|
||||
: found.isMain),
|
||||
hasWorktree: found.hasWorktree ?? true,
|
||||
};
|
||||
// Return the previous reference if the key fields haven't changed,
|
||||
// preventing downstream hooks from seeing a "new" worktree on every render.
|
||||
const prev = prevSelectedWorktreeRef.current;
|
||||
if (
|
||||
prev &&
|
||||
prev.path === result.path &&
|
||||
prev.branch === result.branch &&
|
||||
prev.isMain === result.isMain &&
|
||||
prev.isCurrent === result.isCurrent &&
|
||||
prev.hasWorktree === result.hasWorktree
|
||||
) {
|
||||
return prev;
|
||||
}
|
||||
prevSelectedWorktreeRef.current = result;
|
||||
return result;
|
||||
}, [worktrees, currentWorktreePath]);
|
||||
|
||||
// Auto mode hook - pass current worktree to get worktree-specific state
|
||||
@@ -922,26 +987,39 @@ export function BoardView() {
|
||||
[handleAddFeature, handleStartImplementation]
|
||||
);
|
||||
|
||||
// Handler for addressing PR comments - creates a feature and starts it automatically
|
||||
const handleAddressPRComments = useCallback(
|
||||
// Handler for managing PR comments - opens the PR Comment Resolution dialog
|
||||
const handleAddressPRComments = useCallback((worktree: WorktreeInfo, prInfo: PRInfo) => {
|
||||
setPRCommentDialogPRInfo({
|
||||
number: prInfo.number,
|
||||
title: prInfo.title,
|
||||
// Pass the worktree's branch so features are created on the correct worktree
|
||||
headRefName: worktree.branch,
|
||||
});
|
||||
setShowPRCommentDialog(true);
|
||||
}, []);
|
||||
|
||||
// Handler for auto-addressing PR comments - immediately creates and starts a feature task
|
||||
const handleAutoAddressPRComments = useCallback(
|
||||
async (worktree: WorktreeInfo, prInfo: PRInfo) => {
|
||||
// Use a simple prompt that instructs the agent to read and address PR feedback
|
||||
// The agent will fetch the PR comments directly, which is more reliable and up-to-date
|
||||
const prNumber = prInfo.number;
|
||||
const description = `Read the review requests on PR #${prNumber} and address any feedback the best you can.`;
|
||||
if (!prInfo.number) {
|
||||
toast.error('Cannot address PR comments', {
|
||||
description: 'No PR number available for this worktree.',
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
const featureData = {
|
||||
title: `Address PR #${prNumber} Review Comments`,
|
||||
category: 'PR Review',
|
||||
description,
|
||||
title: `Address PR #${prInfo.number} Review Comments`,
|
||||
category: 'Maintenance',
|
||||
description: `Read the review requests on PR #${prInfo.number} and address any feedback the best you can.`,
|
||||
images: [],
|
||||
imagePaths: [],
|
||||
skipTests: defaultSkipTests,
|
||||
model: 'opus' as const,
|
||||
model: resolveModelString('opus'),
|
||||
thinkingLevel: 'none' as const,
|
||||
branchName: worktree.branch,
|
||||
workMode: 'custom' as const, // Use the worktree's branch
|
||||
priority: 1, // High priority for PR feedback
|
||||
workMode: 'custom' as const,
|
||||
priority: 1,
|
||||
planningMode: 'skip' as const,
|
||||
requirePlanApproval: false,
|
||||
};
|
||||
@@ -988,7 +1066,7 @@ export function BoardView() {
|
||||
images: [],
|
||||
imagePaths: [],
|
||||
skipTests: defaultSkipTests,
|
||||
model: 'opus' as const,
|
||||
model: resolveModelString('opus'),
|
||||
thinkingLevel: 'none' as const,
|
||||
branchName: conflictInfo.targetBranch,
|
||||
workMode: 'custom' as const, // Use the target branch where conflicts need to be resolved
|
||||
@@ -1508,23 +1586,14 @@ export function BoardView() {
|
||||
setShowCreateBranchDialog(true);
|
||||
}}
|
||||
onAddressPRComments={handleAddressPRComments}
|
||||
onAutoAddressPRComments={handleAutoAddressPRComments}
|
||||
onResolveConflicts={handleResolveConflicts}
|
||||
onCreateMergeConflictResolutionFeature={handleCreateMergeConflictResolutionFeature}
|
||||
onBranchSwitchConflict={handleBranchSwitchConflict}
|
||||
onStashPopConflict={handleStashPopConflict}
|
||||
onStashApplyConflict={handleStashApplyConflict}
|
||||
onBranchDeletedDuringMerge={(branchName) => {
|
||||
// Reset features that were assigned to the deleted branch (same logic as onDeleted in DeleteWorktreeDialog)
|
||||
hookFeatures.forEach((feature) => {
|
||||
if (feature.branchName === branchName) {
|
||||
// Reset the feature's branch assignment - update both local state and persist
|
||||
const updates = {
|
||||
branchName: null as unknown as string | undefined,
|
||||
};
|
||||
updateFeature(feature.id, updates);
|
||||
persistFeatureUpdate(feature.id, updates);
|
||||
}
|
||||
});
|
||||
batchResetBranchFeatures(branchName);
|
||||
setWorktreeRefreshKey((k) => k + 1);
|
||||
}}
|
||||
onRemovedWorktrees={handleRemovedWorktrees}
|
||||
@@ -1901,21 +1970,76 @@ export function BoardView() {
|
||||
}
|
||||
defaultDeleteBranch={getDefaultDeleteBranch(currentProject.path)}
|
||||
onDeleted={(deletedWorktree, _deletedBranch) => {
|
||||
// Reset features that were assigned to the deleted worktree (by branch)
|
||||
hookFeatures.forEach((feature) => {
|
||||
// Match by branch name since worktreePath is no longer stored
|
||||
if (feature.branchName === deletedWorktree.branch) {
|
||||
// Reset the feature's branch assignment - update both local state and persist
|
||||
const updates = {
|
||||
branchName: null as unknown as string | undefined,
|
||||
// 1. Reset current worktree to main FIRST. This must happen
|
||||
// BEFORE removing from the list to ensure downstream hooks
|
||||
// (useAutoMode, useBoardFeatures) see a valid worktree and
|
||||
// never try to render the deleted worktree.
|
||||
const mainBranch = worktrees.find((w) => w.isMain)?.branch || 'main';
|
||||
setCurrentWorktree(currentProject.path, null, mainBranch);
|
||||
|
||||
// 2. Immediately remove the deleted worktree from the store's
|
||||
// worktree list so the UI never renders a stale tab/dropdown
|
||||
// item that can be clicked and cause a crash.
|
||||
const remainingWorktrees = worktrees.filter(
|
||||
(w) => !pathsEqual(w.path, deletedWorktree.path)
|
||||
);
|
||||
setWorktrees(currentProject.path, remainingWorktrees);
|
||||
|
||||
// 3. Cancel any in-flight worktree queries, then optimistically
|
||||
// update the React Query cache so the worktree disappears
|
||||
// from the dropdown immediately. Cancelling first prevents a
|
||||
// pending refetch from overwriting our optimistic update with
|
||||
// stale server data.
|
||||
const worktreeQueryKey = queryKeys.worktrees.all(currentProject.path);
|
||||
void queryClient.cancelQueries({ queryKey: worktreeQueryKey });
|
||||
queryClient.setQueryData(
|
||||
worktreeQueryKey,
|
||||
(
|
||||
old:
|
||||
| {
|
||||
worktrees: WorktreeInfo[];
|
||||
removedWorktrees: Array<{ path: string; branch: string }>;
|
||||
}
|
||||
| undefined
|
||||
) => {
|
||||
if (!old) return old;
|
||||
return {
|
||||
...old,
|
||||
worktrees: old.worktrees.filter(
|
||||
(w: WorktreeInfo) => !pathsEqual(w.path, deletedWorktree.path)
|
||||
),
|
||||
};
|
||||
updateFeature(feature.id, updates);
|
||||
persistFeatureUpdate(feature.id, updates);
|
||||
}
|
||||
);
|
||||
|
||||
// 4. Batch-reset features assigned to the deleted worktree in one
|
||||
// store mutation to avoid N individual updateFeature calls that
|
||||
// cascade into React error #185.
|
||||
batchResetBranchFeatures(deletedWorktree.branch);
|
||||
|
||||
// 5. Do NOT trigger setWorktreeRefreshKey here. The optimistic
|
||||
// cache update (step 3) already removed the worktree from
|
||||
// both the Zustand store and React Query cache. Incrementing
|
||||
// the refresh key would cause invalidateQueries → server
|
||||
// refetch, and if the server's .worktrees/ directory scan
|
||||
// finds remnants of the deleted worktree, it would re-add
|
||||
// it to the dropdown. The 30-second polling interval in
|
||||
// WorktreePanel will eventually reconcile with the server.
|
||||
setSelectedWorktreeForAction(null);
|
||||
|
||||
// 6. Force-sync settings immediately so the reset worktree
|
||||
// selection is persisted before any potential page reload.
|
||||
// Without this, the debounced sync (1s) may not complete
|
||||
// in time and the stale worktree path survives in
|
||||
// server settings, causing the deleted worktree to
|
||||
// reappear on next load.
|
||||
forceSyncSettingsToServer().then((ok) => {
|
||||
if (!ok) {
|
||||
logger.warn(
|
||||
'forceSyncSettingsToServer failed after worktree deletion; stale path may reappear on reload'
|
||||
);
|
||||
}
|
||||
});
|
||||
|
||||
setWorktreeRefreshKey((k) => k + 1);
|
||||
setSelectedWorktreeForAction(null);
|
||||
}}
|
||||
/>
|
||||
|
||||
@@ -1985,6 +2109,18 @@ export function BoardView() {
|
||||
}}
|
||||
/>
|
||||
|
||||
{/* PR Comment Resolution Dialog */}
|
||||
{prCommentDialogPRInfo && (
|
||||
<PRCommentResolutionDialog
|
||||
open={showPRCommentDialog}
|
||||
onOpenChange={(open) => {
|
||||
setShowPRCommentDialog(open);
|
||||
if (!open) setPRCommentDialogPRInfo(null);
|
||||
}}
|
||||
pr={prCommentDialogPRInfo}
|
||||
/>
|
||||
)}
|
||||
|
||||
{/* Init Script Indicator - floating overlay for worktree init script status */}
|
||||
{getShowInitScriptIndicator(currentProject.path) && (
|
||||
<InitScriptIndicator projectPath={currentProject.path} />
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import { memo, useEffect, useState, useMemo, useRef } from 'react';
|
||||
import { useQueryClient } from '@tanstack/react-query';
|
||||
import { Feature, ThinkingLevel, ReasoningEffort, ParsedTask } from '@/store/app-store';
|
||||
import { getProviderFromModel } from '@/lib/utils';
|
||||
import { parseAgentContext, formatModelName, DEFAULT_MODEL } from '@/lib/agent-context-parser';
|
||||
@@ -10,6 +11,7 @@ import { getElectronAPI } from '@/lib/electron';
|
||||
import { SummaryDialog } from './summary-dialog';
|
||||
import { getProviderIconForModel } from '@/components/ui/provider-icon';
|
||||
import { useFeature, useAgentOutput } from '@/hooks/queries';
|
||||
import { queryKeys } from '@/lib/query-keys';
|
||||
|
||||
/**
|
||||
* Formats thinking level for compact display
|
||||
@@ -58,6 +60,7 @@ export const AgentInfoPanel = memo(function AgentInfoPanel({
|
||||
summary,
|
||||
isActivelyRunning,
|
||||
}: AgentInfoPanelProps) {
|
||||
const queryClient = useQueryClient();
|
||||
const [isSummaryDialogOpen, setIsSummaryDialogOpen] = useState(false);
|
||||
const [isTodosExpanded, setIsTodosExpanded] = useState(false);
|
||||
// Track real-time task status updates from WebSocket events
|
||||
@@ -130,6 +133,25 @@ export const AgentInfoPanel = memo(function AgentInfoPanel({
|
||||
pollingInterval,
|
||||
});
|
||||
|
||||
// On mount, ensure feature and agent output queries are fresh.
|
||||
// This handles the worktree switch scenario where cards unmount when filtered out
|
||||
// and remount when the user switches back. Without this, the React Query cache
|
||||
// may serve stale data (or no data) for the individual feature query, causing
|
||||
// the todo list to appear empty until the next polling cycle.
|
||||
useEffect(() => {
|
||||
if (shouldFetchData && projectPath && feature.id && !contextContent) {
|
||||
// Invalidate both the single feature and agent output queries to trigger immediate refetch
|
||||
queryClient.invalidateQueries({
|
||||
queryKey: queryKeys.features.single(projectPath, feature.id),
|
||||
});
|
||||
queryClient.invalidateQueries({
|
||||
queryKey: queryKeys.features.agentOutput(projectPath, feature.id),
|
||||
});
|
||||
}
|
||||
// Only run on mount (feature.id and projectPath identify this specific card instance)
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, [feature.id, projectPath]);
|
||||
|
||||
// Parse agent output into agentInfo
|
||||
const agentInfo = useMemo(() => {
|
||||
if (contextContent) {
|
||||
@@ -305,9 +327,11 @@ export const AgentInfoPanel = memo(function AgentInfoPanel({
|
||||
|
||||
// Agent Info Panel for non-backlog cards
|
||||
// Show panel if we have agentInfo OR planSpec.tasks (for spec/full mode)
|
||||
// OR if the feature has effective todos from any source (handles initial mount after worktree switch)
|
||||
// OR if the feature is actively running (ensures panel stays visible during execution)
|
||||
// Note: hasPlanSpecTasks is already defined above and includes freshPlanSpec
|
||||
// (The backlog case was already handled above and returned early)
|
||||
if (agentInfo || hasPlanSpecTasks) {
|
||||
if (agentInfo || hasPlanSpecTasks || effectiveTodos.length > 0 || isActivelyRunning) {
|
||||
return (
|
||||
<>
|
||||
<div className="mb-3 space-y-2 overflow-hidden">
|
||||
|
||||
@@ -123,6 +123,18 @@ interface AddFeatureDialogProps {
|
||||
* This is used when the "Default to worktree mode" setting is disabled.
|
||||
*/
|
||||
forceCurrentBranchMode?: boolean;
|
||||
/**
|
||||
* Pre-filled title for the feature (e.g., from a GitHub issue).
|
||||
*/
|
||||
prefilledTitle?: string;
|
||||
/**
|
||||
* Pre-filled description for the feature (e.g., from a GitHub issue).
|
||||
*/
|
||||
prefilledDescription?: string;
|
||||
/**
|
||||
* Pre-filled category for the feature (e.g., 'From GitHub').
|
||||
*/
|
||||
prefilledCategory?: string;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -149,6 +161,9 @@ export function AddFeatureDialog({
|
||||
projectPath,
|
||||
selectedNonMainWorktreeBranch,
|
||||
forceCurrentBranchMode,
|
||||
prefilledTitle,
|
||||
prefilledDescription,
|
||||
prefilledCategory,
|
||||
}: AddFeatureDialogProps) {
|
||||
const isSpawnMode = !!parentFeature;
|
||||
const navigate = useNavigate();
|
||||
@@ -211,6 +226,11 @@ export function AddFeatureDialog({
|
||||
wasOpenRef.current = open;
|
||||
|
||||
if (justOpened) {
|
||||
// Initialize with prefilled values if provided, otherwise use defaults
|
||||
setTitle(prefilledTitle ?? '');
|
||||
setDescription(prefilledDescription ?? '');
|
||||
setCategory(prefilledCategory ?? '');
|
||||
|
||||
setSkipTests(defaultSkipTests);
|
||||
// When a non-main worktree is selected, use its branch name for custom mode
|
||||
// Otherwise, use the default branch
|
||||
@@ -254,6 +274,9 @@ export function AddFeatureDialog({
|
||||
forceCurrentBranchMode,
|
||||
parentFeature,
|
||||
allFeatures,
|
||||
prefilledTitle,
|
||||
prefilledDescription,
|
||||
prefilledCategory,
|
||||
]);
|
||||
|
||||
// Clear requirePlanApproval when planning mode is skip or lite
|
||||
|
||||
@@ -105,43 +105,106 @@ export function CreatePRDialog({
|
||||
const branchAheadCount = branchesData?.aheadCount ?? 0;
|
||||
const needsPush = !branchHasRemote || branchAheadCount > 0 || !!worktree?.hasChanges;
|
||||
|
||||
// Filter out current worktree branch from the list
|
||||
// When a target remote is selected, only show branches from that remote
|
||||
const branches = useMemo(() => {
|
||||
if (!branchesData?.branches) return [];
|
||||
const allBranches = branchesData.branches
|
||||
.map((b) => b.name)
|
||||
.filter((name) => name !== worktree?.branch);
|
||||
// Determine the active remote to scope branches to.
|
||||
// For multi-remote: use the selected target remote.
|
||||
// For single remote: automatically scope to that remote.
|
||||
const activeRemote = useMemo(() => {
|
||||
if (remotes.length === 1) return remotes[0].name;
|
||||
if (selectedTargetRemote) return selectedTargetRemote;
|
||||
return '';
|
||||
}, [remotes, selectedTargetRemote]);
|
||||
|
||||
// If a target remote is selected and we have remote info with branches,
|
||||
// only show that remote's branches (not branches from other remotes)
|
||||
if (selectedTargetRemote) {
|
||||
const targetRemoteInfo = remotes.find((r) => r.name === selectedTargetRemote);
|
||||
if (targetRemoteInfo?.branches && targetRemoteInfo.branches.length > 0) {
|
||||
const targetBranchNames = new Set(targetRemoteInfo.branches);
|
||||
// Filter to only include branches that exist on the target remote
|
||||
// Match both short names (e.g. "main") and prefixed names (e.g. "upstream/main")
|
||||
return allBranches.filter((name) => {
|
||||
// Check if the branch name matches a target remote branch directly
|
||||
if (targetBranchNames.has(name)) return true;
|
||||
// Check if it's a prefixed remote branch (e.g. "upstream/main")
|
||||
const prefix = `${selectedTargetRemote}/`;
|
||||
if (name.startsWith(prefix) && targetBranchNames.has(name.slice(prefix.length)))
|
||||
return true;
|
||||
return false;
|
||||
// Filter branches by the active remote and strip remote prefixes for display.
|
||||
// Returns display names (e.g. "main") without remote prefix.
|
||||
// Also builds a map from display name → full ref (e.g. "origin/main") for PR creation.
|
||||
const { branches, branchFullRefMap } = useMemo(() => {
|
||||
if (!branchesData?.branches)
|
||||
return { branches: [], branchFullRefMap: new Map<string, string>() };
|
||||
|
||||
const refMap = new Map<string, string>();
|
||||
|
||||
// If we have an active remote with branch info from the remotes endpoint, use that as the source
|
||||
const activeRemoteInfo = activeRemote
|
||||
? remotes.find((r) => r.name === activeRemote)
|
||||
: undefined;
|
||||
|
||||
if (activeRemoteInfo?.branches && activeRemoteInfo.branches.length > 0) {
|
||||
// Use the remote's branch list — these are already short names (e.g. "main")
|
||||
const filteredBranches = activeRemoteInfo.branches
|
||||
.filter((branchName) => {
|
||||
// Exclude the current worktree branch
|
||||
return branchName !== worktree?.branch;
|
||||
})
|
||||
.map((branchName) => {
|
||||
// Map display name to full ref
|
||||
const fullRef = `${activeRemote}/${branchName}`;
|
||||
refMap.set(branchName, fullRef);
|
||||
return branchName;
|
||||
});
|
||||
|
||||
return { branches: filteredBranches, branchFullRefMap: refMap };
|
||||
}
|
||||
|
||||
// Fallback: if no remote info available, use the branches from the branches endpoint
|
||||
// Filter and strip prefixes
|
||||
const seen = new Set<string>();
|
||||
const filteredBranches: string[] = [];
|
||||
|
||||
for (const b of branchesData.branches) {
|
||||
// Skip the current worktree branch
|
||||
if (b.name === worktree?.branch) continue;
|
||||
|
||||
if (b.isRemote) {
|
||||
// Remote branch: check if it belongs to the active remote
|
||||
const slashIndex = b.name.indexOf('/');
|
||||
if (slashIndex === -1) continue;
|
||||
|
||||
const remoteName = b.name.substring(0, slashIndex);
|
||||
const branchName = b.name.substring(slashIndex + 1);
|
||||
|
||||
// If we have an active remote, only include branches from that remote
|
||||
if (activeRemote && remoteName !== activeRemote) continue;
|
||||
|
||||
// Strip the remote prefix for display
|
||||
if (!seen.has(branchName)) {
|
||||
seen.add(branchName);
|
||||
filteredBranches.push(branchName);
|
||||
refMap.set(branchName, b.name);
|
||||
}
|
||||
} else {
|
||||
// Local branch — only include if it has a remote counterpart on the active remote
|
||||
// or if no active remote is set (no remotes at all)
|
||||
if (!activeRemote) {
|
||||
if (!seen.has(b.name)) {
|
||||
seen.add(b.name);
|
||||
filteredBranches.push(b.name);
|
||||
refMap.set(b.name, b.name);
|
||||
}
|
||||
}
|
||||
// When active remote is set, skip local-only branches — the remote version
|
||||
// will be included from the remote branches above
|
||||
}
|
||||
}
|
||||
|
||||
return allBranches;
|
||||
}, [branchesData?.branches, worktree?.branch, selectedTargetRemote, remotes]);
|
||||
return { branches: filteredBranches, branchFullRefMap: refMap };
|
||||
}, [branchesData?.branches, worktree?.branch, activeRemote, remotes]);
|
||||
|
||||
// When branches change (e.g. target remote changed), reset base branch if current selection is no longer valid
|
||||
useEffect(() => {
|
||||
if (branches.length > 0 && baseBranch && !branches.includes(baseBranch)) {
|
||||
// Current base branch is not in the filtered list — pick the best match
|
||||
const mainBranch = branches.find((b) => b === 'main' || b === 'master');
|
||||
setBaseBranch(mainBranch || branches[0]);
|
||||
// Strip any existing remote prefix from the current base branch for comparison
|
||||
const strippedBaseBranch = baseBranch.includes('/')
|
||||
? baseBranch.substring(baseBranch.indexOf('/') + 1)
|
||||
: baseBranch;
|
||||
|
||||
// Check if the stripped version exists in the list
|
||||
if (branches.includes(strippedBaseBranch)) {
|
||||
setBaseBranch(strippedBaseBranch);
|
||||
} else {
|
||||
const mainBranch = branches.find((b) => b === 'main' || b === 'master');
|
||||
setBaseBranch(mainBranch || branches[0]);
|
||||
}
|
||||
}
|
||||
}, [branches, baseBranch]);
|
||||
|
||||
@@ -234,7 +297,16 @@ export function CreatePRDialog({
|
||||
|
||||
try {
|
||||
const api = getHttpApiClient();
|
||||
const result = await api.worktree.generatePRDescription(worktree.path, baseBranch);
|
||||
// Resolve the display name to the actual branch name for the API
|
||||
const resolvedRef = branchFullRefMap.get(baseBranch) || baseBranch;
|
||||
// Only strip the remote prefix if the resolved ref differs from the original
|
||||
// (indicating it was resolved from a full ref like "origin/main").
|
||||
// This preserves local branch names that contain slashes (e.g. "release/1.0").
|
||||
const branchNameForApi =
|
||||
resolvedRef !== baseBranch && resolvedRef.includes('/')
|
||||
? resolvedRef.substring(resolvedRef.indexOf('/') + 1)
|
||||
: resolvedRef;
|
||||
const result = await api.worktree.generatePRDescription(worktree.path, branchNameForApi);
|
||||
|
||||
if (result.success) {
|
||||
if (result.title) {
|
||||
@@ -270,12 +342,26 @@ export function CreatePRDialog({
|
||||
setError('Worktree API not available');
|
||||
return;
|
||||
}
|
||||
// Resolve the display branch name to the full ref for the API call.
|
||||
// The baseBranch state holds the display name (e.g. "main"), but the API
|
||||
// may need the short name without the remote prefix. We pass the display name
|
||||
// since the backend handles branch resolution. However, if the full ref is
|
||||
// available, we can use it for more precise targeting.
|
||||
const resolvedBaseBranch = branchFullRefMap.get(baseBranch) || baseBranch;
|
||||
// Only strip the remote prefix if the resolved ref differs from the original
|
||||
// (indicating it was resolved from a full ref like "origin/main").
|
||||
// This preserves local branch names that contain slashes (e.g. "release/1.0").
|
||||
const baseBranchForApi =
|
||||
resolvedBaseBranch !== baseBranch && resolvedBaseBranch.includes('/')
|
||||
? resolvedBaseBranch.substring(resolvedBaseBranch.indexOf('/') + 1)
|
||||
: resolvedBaseBranch;
|
||||
|
||||
const result = await api.worktree.createPR(worktree.path, {
|
||||
projectPath: projectPath || undefined,
|
||||
commitMessage: commitMessage || undefined,
|
||||
prTitle: title || worktree.branch,
|
||||
prBody: body || `Changes from branch ${worktree.branch}`,
|
||||
baseBranch,
|
||||
baseBranch: baseBranchForApi,
|
||||
draft: isDraft,
|
||||
remote: selectedRemote || undefined,
|
||||
targetRemote: remotes.length > 1 ? selectedTargetRemote || undefined : undefined,
|
||||
@@ -405,7 +491,7 @@ export function CreatePRDialog({
|
||||
|
||||
return (
|
||||
<Dialog open={open} onOpenChange={handleClose}>
|
||||
<DialogContent className="sm:max-w-[550px]">
|
||||
<DialogContent className="sm:max-w-[550px] flex flex-col">
|
||||
<DialogHeader>
|
||||
<DialogTitle className="flex items-center gap-2">
|
||||
<GitPullRequest className="w-5 h-5" />
|
||||
@@ -479,7 +565,7 @@ export function CreatePRDialog({
|
||||
</div>
|
||||
) : (
|
||||
<>
|
||||
<div className="grid gap-4 py-4">
|
||||
<div className="grid gap-4 py-4 overflow-y-auto min-h-0 flex-1">
|
||||
{worktree.hasChanges && (
|
||||
<div className="grid gap-2">
|
||||
<Label htmlFor="commit-message">
|
||||
@@ -626,9 +712,13 @@ export function CreatePRDialog({
|
||||
onChange={setBaseBranch}
|
||||
branches={branches}
|
||||
placeholder="Select base branch..."
|
||||
disabled={isLoadingBranches}
|
||||
disabled={isLoadingBranches || isLoadingRemotes}
|
||||
allowCreate={false}
|
||||
emptyMessage="No matching branches found."
|
||||
emptyMessage={
|
||||
activeRemote
|
||||
? `No branches found on remote "${activeRemote}".`
|
||||
: 'No matching branches found.'
|
||||
}
|
||||
data-testid="base-branch-autocomplete"
|
||||
/>
|
||||
</div>
|
||||
@@ -649,7 +739,7 @@ export function CreatePRDialog({
|
||||
{error && <p className="text-sm text-destructive">{error}</p>}
|
||||
</div>
|
||||
|
||||
<DialogFooter>
|
||||
<DialogFooter className="shrink-0 pt-2 border-t">
|
||||
<Button variant="ghost" onClick={handleClose} disabled={isLoading}>
|
||||
Cancel
|
||||
</Button>
|
||||
|
||||
@@ -284,11 +284,33 @@ export function CreateWorktreeDialog({
|
||||
|
||||
if (result.success && result.worktree) {
|
||||
const baseDesc = effectiveBaseBranch ? ` from ${effectiveBaseBranch}` : '';
|
||||
toast.success(`Worktree created for branch "${result.worktree.branch}"`, {
|
||||
description: result.worktree.isNew
|
||||
? `New branch created${baseDesc}`
|
||||
: 'Using existing branch',
|
||||
});
|
||||
const commitInfo = result.worktree.baseCommitHash
|
||||
? ` (${result.worktree.baseCommitHash})`
|
||||
: '';
|
||||
|
||||
// Show sync result feedback
|
||||
const syncResult = result.worktree.syncResult;
|
||||
if (syncResult?.diverged) {
|
||||
// Branch had diverged — warn the user
|
||||
toast.warning(`Worktree created for branch "${result.worktree.branch}"`, {
|
||||
description: `${syncResult.message}`,
|
||||
duration: 8000,
|
||||
});
|
||||
} else if (syncResult && !syncResult.synced && syncResult.message) {
|
||||
// Sync was attempted but failed (network error, etc.)
|
||||
toast.warning(`Worktree created for branch "${result.worktree.branch}"`, {
|
||||
description: `Created with local copy. ${syncResult.message}`,
|
||||
duration: 6000,
|
||||
});
|
||||
} else {
|
||||
// Normal success — include commit info if available
|
||||
toast.success(`Worktree created for branch "${result.worktree.branch}"`, {
|
||||
description: result.worktree.isNew
|
||||
? `New branch created${baseDesc}${commitInfo}`
|
||||
: `Using existing branch${commitInfo}`,
|
||||
});
|
||||
}
|
||||
|
||||
onCreated({ path: result.worktree.path, branch: result.worktree.branch });
|
||||
onOpenChange(false);
|
||||
setBranchName('');
|
||||
@@ -414,6 +436,12 @@ export function CreateWorktreeDialog({
|
||||
<span>Remote branch — will fetch latest before creating worktree</span>
|
||||
</div>
|
||||
)}
|
||||
{!isRemoteBaseBranch && baseBranch && !branchFetchError && (
|
||||
<div className="flex items-center gap-1.5 text-xs text-muted-foreground">
|
||||
<RefreshCw className="w-3 h-3" />
|
||||
<span>Will sync with remote tracking branch if available</span>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
@@ -454,7 +482,7 @@ export function CreateWorktreeDialog({
|
||||
{isLoading ? (
|
||||
<>
|
||||
<Spinner size="sm" className="mr-2" />
|
||||
{isRemoteBaseBranch ? 'Fetching & Creating...' : 'Creating...'}
|
||||
{baseBranch.trim() ? 'Syncing & Creating...' : 'Creating...'}
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
|
||||
@@ -72,9 +72,19 @@ export function DeleteWorktreeDialog({
|
||||
? `Branch "${worktree.branch}" was also deleted`
|
||||
: `Branch "${worktree.branch}" was kept`,
|
||||
});
|
||||
onDeleted(worktree, deleteBranch);
|
||||
// Close the dialog first, then notify the parent.
|
||||
// This ensures the dialog unmounts before the parent
|
||||
// triggers potentially heavy state updates (feature branch
|
||||
// resets, worktree refresh), reducing concurrent re-renders
|
||||
// that can cascade into React error #185.
|
||||
onOpenChange(false);
|
||||
setDeleteBranch(false);
|
||||
try {
|
||||
onDeleted(worktree, deleteBranch);
|
||||
} catch (error) {
|
||||
// Prevent errors in onDeleted from propagating to the error boundary
|
||||
console.error('onDeleted callback failed:', error);
|
||||
}
|
||||
} else {
|
||||
toast.error('Failed to delete worktree', {
|
||||
description: result.error,
|
||||
|
||||
@@ -84,17 +84,19 @@ export function useBoardActions({
|
||||
onWorktreeAutoSelect,
|
||||
currentWorktreeBranch,
|
||||
}: UseBoardActionsProps) {
|
||||
const {
|
||||
addFeature,
|
||||
updateFeature,
|
||||
removeFeature,
|
||||
moveFeature,
|
||||
useWorktrees,
|
||||
enableDependencyBlocking,
|
||||
skipVerificationInAutoMode,
|
||||
isPrimaryWorktreeBranch,
|
||||
getPrimaryWorktreeBranch,
|
||||
} = useAppStore();
|
||||
// IMPORTANT: Use individual selectors instead of bare useAppStore() to prevent
|
||||
// subscribing to the entire store. Bare useAppStore() causes the host component
|
||||
// (BoardView) to re-render on EVERY store change, which cascades through effects
|
||||
// and triggers React error #185 (maximum update depth exceeded).
|
||||
const addFeature = useAppStore((s) => s.addFeature);
|
||||
const updateFeature = useAppStore((s) => s.updateFeature);
|
||||
const removeFeature = useAppStore((s) => s.removeFeature);
|
||||
const moveFeature = useAppStore((s) => s.moveFeature);
|
||||
const worktreesEnabled = useAppStore((s) => s.useWorktrees);
|
||||
const enableDependencyBlocking = useAppStore((s) => s.enableDependencyBlocking);
|
||||
const skipVerificationInAutoMode = useAppStore((s) => s.skipVerificationInAutoMode);
|
||||
const isPrimaryWorktreeBranch = useAppStore((s) => s.isPrimaryWorktreeBranch);
|
||||
const getPrimaryWorktreeBranch = useAppStore((s) => s.getPrimaryWorktreeBranch);
|
||||
const autoMode = useAutoMode();
|
||||
|
||||
// React Query mutations for feature operations
|
||||
@@ -217,9 +219,15 @@ export function useBoardActions({
|
||||
const needsTitleGeneration =
|
||||
!titleWasGenerated && !featureData.title.trim() && featureData.description.trim();
|
||||
|
||||
const initialStatus = featureData.initialStatus || 'backlog';
|
||||
const {
|
||||
initialStatus: requestedStatus,
|
||||
workMode: _workMode,
|
||||
childDependencies,
|
||||
...restFeatureData
|
||||
} = featureData;
|
||||
const initialStatus = requestedStatus || 'backlog';
|
||||
const newFeatureData = {
|
||||
...featureData,
|
||||
...restFeatureData,
|
||||
title: titleWasGenerated ? titleForBranch : featureData.title,
|
||||
titleGenerating: needsTitleGeneration,
|
||||
status: initialStatus,
|
||||
@@ -239,8 +247,8 @@ export function useBoardActions({
|
||||
saveCategory(featureData.category);
|
||||
|
||||
// Handle child dependencies - update other features to depend on this new feature
|
||||
if (featureData.childDependencies && featureData.childDependencies.length > 0) {
|
||||
for (const childId of featureData.childDependencies) {
|
||||
if (childDependencies && childDependencies.length > 0) {
|
||||
for (const childId of childDependencies) {
|
||||
const childFeature = features.find((f) => f.id === childId);
|
||||
if (childFeature) {
|
||||
const childDeps = childFeature.dependencies || [];
|
||||
@@ -543,7 +551,7 @@ export function useBoardActions({
|
||||
const result = await api.autoMode.runFeature(
|
||||
currentProject.path,
|
||||
feature.id,
|
||||
useWorktrees
|
||||
worktreesEnabled
|
||||
// No worktreePath - server derives from feature.branchName
|
||||
);
|
||||
|
||||
@@ -554,7 +562,7 @@ export function useBoardActions({
|
||||
throw new Error(result.error || 'Failed to start feature');
|
||||
}
|
||||
},
|
||||
[currentProject, useWorktrees]
|
||||
[currentProject, worktreesEnabled]
|
||||
);
|
||||
|
||||
const handleStartImplementation = useCallback(
|
||||
@@ -687,9 +695,9 @@ export function useBoardActions({
|
||||
logger.error('No current project');
|
||||
return;
|
||||
}
|
||||
resumeFeatureMutation.mutate({ featureId: feature.id, useWorktrees });
|
||||
resumeFeatureMutation.mutate({ featureId: feature.id, useWorktrees: worktreesEnabled });
|
||||
},
|
||||
[currentProject, resumeFeatureMutation, useWorktrees]
|
||||
[currentProject, resumeFeatureMutation, worktreesEnabled]
|
||||
);
|
||||
|
||||
const handleManualVerify = useCallback(
|
||||
@@ -774,7 +782,7 @@ export function useBoardActions({
|
||||
followUpFeature.id,
|
||||
followUpPrompt,
|
||||
imagePaths,
|
||||
useWorktrees
|
||||
worktreesEnabled
|
||||
);
|
||||
|
||||
if (!result.success) {
|
||||
@@ -812,7 +820,7 @@ export function useBoardActions({
|
||||
setFollowUpPrompt,
|
||||
setFollowUpImagePaths,
|
||||
setFollowUpPreviewMap,
|
||||
useWorktrees,
|
||||
worktreesEnabled,
|
||||
]);
|
||||
|
||||
const handleCommitFeature = useCallback(
|
||||
@@ -1161,10 +1169,15 @@ export function useBoardActions({
|
||||
|
||||
const handleDuplicateFeature = useCallback(
|
||||
async (feature: Feature, asChild: boolean = false) => {
|
||||
// Copy all feature data, stripping id, status (handled by create), and runtime/state fields
|
||||
// Copy all feature data, stripping id, status (handled by create), and runtime/state fields.
|
||||
// Also strip initialStatus and workMode which are transient creation parameters that
|
||||
// should not carry over to duplicates (initialStatus: 'in_progress' would cause
|
||||
// the duplicate to immediately appear in "In Progress" instead of "Backlog").
|
||||
const {
|
||||
id: _id,
|
||||
status: _status,
|
||||
initialStatus: _initialStatus,
|
||||
workMode: _workMode,
|
||||
startedAt: _startedAt,
|
||||
error: _error,
|
||||
summary: _summary,
|
||||
@@ -1212,6 +1225,8 @@ export function useBoardActions({
|
||||
const {
|
||||
id: _id,
|
||||
status: _status,
|
||||
initialStatus: _initialStatus,
|
||||
workMode: _workMode,
|
||||
startedAt: _startedAt,
|
||||
error: _error,
|
||||
summary: _summary,
|
||||
|
||||
@@ -33,7 +33,12 @@ export function useBoardDragDrop({
|
||||
const [pendingDependencyLink, setPendingDependencyLink] = useState<PendingDependencyLink | null>(
|
||||
null
|
||||
);
|
||||
const { moveFeature, updateFeature } = useAppStore();
|
||||
// IMPORTANT: Use individual selectors instead of bare useAppStore() to prevent
|
||||
// subscribing to the entire store. Bare useAppStore() causes the host component
|
||||
// (BoardView) to re-render on EVERY store change, which cascades through effects
|
||||
// and triggers React error #185 (maximum update depth exceeded).
|
||||
const moveFeature = useAppStore((s) => s.moveFeature);
|
||||
const updateFeature = useAppStore((s) => s.updateFeature);
|
||||
const autoMode = useAutoMode();
|
||||
|
||||
// Note: getOrCreateWorktreeForFeature removed - worktrees are now created server-side
|
||||
|
||||
@@ -14,7 +14,11 @@ interface UseBoardPersistenceProps {
|
||||
}
|
||||
|
||||
export function useBoardPersistence({ currentProject }: UseBoardPersistenceProps) {
|
||||
const { updateFeature } = useAppStore();
|
||||
// IMPORTANT: Use individual selector instead of bare useAppStore() to prevent
|
||||
// subscribing to the entire store. Bare useAppStore() causes the host component
|
||||
// (BoardView) to re-render on EVERY store change, which cascades through effects
|
||||
// and triggers React error #185 (maximum update depth exceeded).
|
||||
const updateFeature = useAppStore((s) => s.updateFeature);
|
||||
const queryClient = useQueryClient();
|
||||
|
||||
// Persist feature update to API (replaces saveFeatures)
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import { useMemo } from 'react';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import {
|
||||
DropdownMenu,
|
||||
@@ -13,6 +14,7 @@ import {
|
||||
import {
|
||||
Trash2,
|
||||
MoreHorizontal,
|
||||
GitBranch,
|
||||
GitCommit,
|
||||
GitPullRequest,
|
||||
Download,
|
||||
@@ -40,6 +42,7 @@ import {
|
||||
AlertTriangle,
|
||||
XCircle,
|
||||
CheckCircle,
|
||||
Settings2,
|
||||
} from 'lucide-react';
|
||||
import { toast } from 'sonner';
|
||||
import { cn } from '@/lib/utils';
|
||||
@@ -54,6 +57,7 @@ import {
|
||||
import { getEditorIcon } from '@/components/icons/editor-icons';
|
||||
import { getTerminalIcon } from '@/components/icons/terminal-icons';
|
||||
import { useAppStore } from '@/store/app-store';
|
||||
import type { TerminalScript } from '@/components/views/project-settings-view/terminal-scripts-constants';
|
||||
|
||||
interface WorktreeActionsDropdownProps {
|
||||
worktree: WorktreeInfo;
|
||||
@@ -102,6 +106,7 @@ interface WorktreeActionsDropdownProps {
|
||||
onCommit: (worktree: WorktreeInfo) => void;
|
||||
onCreatePR: (worktree: WorktreeInfo) => void;
|
||||
onAddressPRComments: (worktree: WorktreeInfo, prInfo: PRInfo) => void;
|
||||
onAutoAddressPRComments: (worktree: WorktreeInfo, prInfo: PRInfo) => void;
|
||||
onResolveConflicts: (worktree: WorktreeInfo) => void;
|
||||
onDeleteWorktree: (worktree: WorktreeInfo) => void;
|
||||
onStartDevServer: (worktree: WorktreeInfo) => void;
|
||||
@@ -128,6 +133,91 @@ interface WorktreeActionsDropdownProps {
|
||||
/** Continue an in-progress merge/rebase/cherry-pick after resolving conflicts */
|
||||
onContinueOperation?: (worktree: WorktreeInfo) => void;
|
||||
hasInitScript: boolean;
|
||||
/** Terminal quick scripts configured for the project */
|
||||
terminalScripts?: TerminalScript[];
|
||||
/** Callback to run a terminal quick script in a new terminal session */
|
||||
onRunTerminalScript?: (worktree: WorktreeInfo, command: string) => void;
|
||||
/** Callback to open the script editor UI */
|
||||
onEditScripts?: () => void;
|
||||
/** Whether sync is in progress */
|
||||
isSyncing?: boolean;
|
||||
/** Sync (pull + push) callback */
|
||||
onSync?: (worktree: WorktreeInfo) => void;
|
||||
/** Sync with a specific remote */
|
||||
onSyncWithRemote?: (worktree: WorktreeInfo, remote: string) => void;
|
||||
/** Set tracking branch to a specific remote */
|
||||
onSetTracking?: (worktree: WorktreeInfo, remote: string) => void;
|
||||
}
|
||||
|
||||
/**
|
||||
* A remote item that either renders as a split-button with "Set as Tracking Branch"
|
||||
* sub-action, or a plain menu item if onSetTracking is not provided.
|
||||
*/
|
||||
function RemoteActionMenuItem({
|
||||
remote,
|
||||
icon: Icon,
|
||||
trackingRemote,
|
||||
isDisabled,
|
||||
isGitOpsAvailable,
|
||||
onAction,
|
||||
onSetTracking,
|
||||
}: {
|
||||
remote: { name: string; url: string };
|
||||
icon: typeof Download;
|
||||
trackingRemote?: string;
|
||||
isDisabled: boolean;
|
||||
isGitOpsAvailable: boolean;
|
||||
onAction: () => void;
|
||||
onSetTracking?: () => void;
|
||||
}) {
|
||||
if (onSetTracking) {
|
||||
return (
|
||||
<DropdownMenuSub key={remote.name}>
|
||||
<div className="flex items-center">
|
||||
<DropdownMenuItem
|
||||
onClick={onAction}
|
||||
disabled={isDisabled || !isGitOpsAvailable}
|
||||
className="text-xs flex-1 pr-0 rounded-r-none"
|
||||
>
|
||||
<Icon className="w-3.5 h-3.5 mr-2" />
|
||||
{remote.name}
|
||||
{trackingRemote === remote.name && (
|
||||
<span className="ml-auto text-[10px] text-muted-foreground mr-1">tracking</span>
|
||||
)}
|
||||
</DropdownMenuItem>
|
||||
<DropdownMenuSubTrigger
|
||||
className="text-xs px-1 rounded-l-none border-l border-border/30 h-8"
|
||||
disabled={!isGitOpsAvailable}
|
||||
/>
|
||||
</div>
|
||||
<DropdownMenuSubContent>
|
||||
<DropdownMenuItem
|
||||
onClick={onSetTracking}
|
||||
disabled={!isGitOpsAvailable}
|
||||
className="text-xs"
|
||||
>
|
||||
<GitBranch className="w-3.5 h-3.5 mr-2" />
|
||||
Set as Tracking Branch
|
||||
</DropdownMenuItem>
|
||||
</DropdownMenuSubContent>
|
||||
</DropdownMenuSub>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<DropdownMenuItem
|
||||
key={remote.name}
|
||||
onClick={onAction}
|
||||
disabled={isDisabled || !isGitOpsAvailable}
|
||||
className="text-xs"
|
||||
>
|
||||
<Icon className="w-3.5 h-3.5 mr-2" />
|
||||
{remote.name}
|
||||
<span className="ml-auto text-[10px] text-muted-foreground max-w-[100px] truncate">
|
||||
{remote.url}
|
||||
</span>
|
||||
</DropdownMenuItem>
|
||||
);
|
||||
}
|
||||
|
||||
export function WorktreeActionsDropdown({
|
||||
@@ -166,6 +256,7 @@ export function WorktreeActionsDropdown({
|
||||
onCommit,
|
||||
onCreatePR,
|
||||
onAddressPRComments,
|
||||
onAutoAddressPRComments,
|
||||
onResolveConflicts,
|
||||
onDeleteWorktree,
|
||||
onStartDevServer,
|
||||
@@ -184,6 +275,13 @@ export function WorktreeActionsDropdown({
|
||||
onAbortOperation,
|
||||
onContinueOperation,
|
||||
hasInitScript,
|
||||
terminalScripts,
|
||||
onRunTerminalScript,
|
||||
onEditScripts,
|
||||
isSyncing = false,
|
||||
onSync,
|
||||
onSyncWithRemote,
|
||||
onSetTracking,
|
||||
}: WorktreeActionsDropdownProps) {
|
||||
// Get available editors for the "Open In" submenu
|
||||
const { editors } = useAvailableEditors();
|
||||
@@ -238,6 +336,28 @@ export function WorktreeActionsDropdown({
|
||||
// Determine if the destructive/bottom section has any visible items
|
||||
const hasDestructiveSectionContent = worktree.hasChanges || !worktree.isMain;
|
||||
|
||||
// Pre-compute PR info for the PR submenu (avoids an IIFE in JSX)
|
||||
const prInfo = useMemo<PRInfo | null>(() => {
|
||||
if (!showPRInfo || !worktree.pr) return null;
|
||||
return {
|
||||
number: worktree.pr.number,
|
||||
title: worktree.pr.title,
|
||||
url: worktree.pr.url,
|
||||
state: worktree.pr.state,
|
||||
author: '',
|
||||
body: '',
|
||||
comments: [],
|
||||
reviewComments: [],
|
||||
};
|
||||
}, [showPRInfo, worktree.pr]);
|
||||
|
||||
const viewDevServerLogsItem = (
|
||||
<DropdownMenuItem onClick={() => onViewDevServerLogs(worktree)} className="text-xs">
|
||||
<ScrollText className="w-3.5 h-3.5 mr-2" />
|
||||
View Dev Server Logs
|
||||
</DropdownMenuItem>
|
||||
);
|
||||
|
||||
return (
|
||||
<DropdownMenu onOpenChange={onOpenChange}>
|
||||
<DropdownMenuTrigger asChild>
|
||||
@@ -358,42 +478,59 @@ export function WorktreeActionsDropdown({
|
||||
? 'Dev Server Starting...'
|
||||
: `Dev Server Running (:${devServerInfo?.port})`}
|
||||
</DropdownMenuLabel>
|
||||
<DropdownMenuItem
|
||||
onClick={() => onOpenDevServerUrl(worktree)}
|
||||
className="text-xs"
|
||||
disabled={devServerInfo?.urlDetected === false}
|
||||
aria-label={
|
||||
devServerInfo?.urlDetected === false
|
||||
? 'Open dev server in browser'
|
||||
: `Open dev server on port ${devServerInfo?.port} in browser`
|
||||
}
|
||||
>
|
||||
<Globe className="w-3.5 h-3.5 mr-2" aria-hidden="true" />
|
||||
Open in Browser
|
||||
</DropdownMenuItem>
|
||||
<DropdownMenuItem onClick={() => onViewDevServerLogs(worktree)} className="text-xs">
|
||||
<ScrollText className="w-3.5 h-3.5 mr-2" />
|
||||
View Logs
|
||||
</DropdownMenuItem>
|
||||
<DropdownMenuItem
|
||||
onClick={() => onStopDevServer(worktree)}
|
||||
className="text-xs text-destructive focus:text-destructive"
|
||||
>
|
||||
<Square className="w-3.5 h-3.5 mr-2" />
|
||||
Stop Dev Server
|
||||
</DropdownMenuItem>
|
||||
{devServerInfo != null &&
|
||||
devServerInfo.port != null &&
|
||||
devServerInfo.urlDetected !== false && (
|
||||
<DropdownMenuItem
|
||||
onClick={() => onOpenDevServerUrl(worktree)}
|
||||
className="text-xs"
|
||||
aria-label={`Open dev server on port ${devServerInfo.port} in browser`}
|
||||
>
|
||||
<Globe className="w-3.5 h-3.5 mr-2" aria-hidden="true" />
|
||||
Open in Browser
|
||||
</DropdownMenuItem>
|
||||
)}
|
||||
{/* Stop Dev Server - split button: click main area to stop, chevron for view logs */}
|
||||
<DropdownMenuSub>
|
||||
<div className="flex items-center">
|
||||
<DropdownMenuItem
|
||||
onClick={() => onStopDevServer(worktree)}
|
||||
className="text-xs flex-1 pr-0 rounded-r-none text-destructive focus:text-destructive"
|
||||
>
|
||||
<Square className="w-3.5 h-3.5 mr-2" />
|
||||
Stop Dev Server
|
||||
</DropdownMenuItem>
|
||||
<DropdownMenuSubTrigger className="text-xs px-1 rounded-l-none border-l border-border/30 h-8" />
|
||||
</div>
|
||||
<DropdownMenuSubContent>{viewDevServerLogsItem}</DropdownMenuSubContent>
|
||||
</DropdownMenuSub>
|
||||
<DropdownMenuSeparator />
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
<DropdownMenuItem
|
||||
onClick={() => onStartDevServer(worktree)}
|
||||
disabled={isStartingDevServer}
|
||||
className="text-xs"
|
||||
>
|
||||
<Play className={cn('w-3.5 h-3.5 mr-2', isStartingDevServer && 'animate-pulse')} />
|
||||
{isStartingDevServer ? 'Starting...' : 'Start Dev Server'}
|
||||
</DropdownMenuItem>
|
||||
{/* Start Dev Server - split button: click main area to start, chevron for view logs */}
|
||||
<DropdownMenuSub>
|
||||
<div className="flex items-center">
|
||||
<DropdownMenuItem
|
||||
onClick={() => onStartDevServer(worktree)}
|
||||
disabled={isStartingDevServer}
|
||||
className="text-xs flex-1 pr-0 rounded-r-none"
|
||||
>
|
||||
<Play
|
||||
className={cn('w-3.5 h-3.5 mr-2', isStartingDevServer && 'animate-pulse')}
|
||||
/>
|
||||
{isStartingDevServer ? 'Starting...' : 'Start Dev Server'}
|
||||
</DropdownMenuItem>
|
||||
<DropdownMenuSubTrigger
|
||||
className={cn(
|
||||
'text-xs px-1 rounded-l-none border-l border-border/30 h-8',
|
||||
isStartingDevServer && 'opacity-50 cursor-not-allowed'
|
||||
)}
|
||||
disabled={isStartingDevServer}
|
||||
/>
|
||||
</div>
|
||||
<DropdownMenuSubContent>{viewDevServerLogsItem}</DropdownMenuSubContent>
|
||||
</DropdownMenuSub>
|
||||
<DropdownMenuSeparator />
|
||||
</>
|
||||
)}
|
||||
@@ -575,12 +712,57 @@ export function WorktreeActionsDropdown({
|
||||
})}
|
||||
</DropdownMenuSubContent>
|
||||
</DropdownMenuSub>
|
||||
{!worktree.isMain && hasInitScript && (
|
||||
<DropdownMenuItem onClick={() => onRunInitScript(worktree)} className="text-xs">
|
||||
<RefreshCw className="w-3.5 h-3.5 mr-2" />
|
||||
Re-run Init Script
|
||||
</DropdownMenuItem>
|
||||
)}
|
||||
{/* Scripts submenu - consolidates init script and terminal quick scripts */}
|
||||
<DropdownMenuSub>
|
||||
<DropdownMenuSubTrigger className="text-xs">
|
||||
<ScrollText className="w-3.5 h-3.5 mr-2" />
|
||||
Scripts
|
||||
</DropdownMenuSubTrigger>
|
||||
<DropdownMenuSubContent className="w-52">
|
||||
{/* Re-run Init Script - always shown for non-main worktrees, disabled when no init script configured or no handler */}
|
||||
{!worktree.isMain && (
|
||||
<>
|
||||
<DropdownMenuItem
|
||||
onClick={() => onRunInitScript(worktree)}
|
||||
className="text-xs"
|
||||
disabled={!hasInitScript}
|
||||
>
|
||||
<RefreshCw className="w-3.5 h-3.5 mr-2" />
|
||||
Re-run Init Script
|
||||
</DropdownMenuItem>
|
||||
<DropdownMenuSeparator />
|
||||
</>
|
||||
)}
|
||||
{/* Terminal quick scripts */}
|
||||
{terminalScripts && terminalScripts.length > 0 ? (
|
||||
terminalScripts.map((script) => (
|
||||
<DropdownMenuItem
|
||||
key={script.id}
|
||||
onClick={() => onRunTerminalScript?.(worktree, script.command)}
|
||||
className="text-xs"
|
||||
disabled={!onRunTerminalScript}
|
||||
>
|
||||
<Play className="w-3.5 h-3.5 mr-2 shrink-0" />
|
||||
<span className="truncate">{script.name}</span>
|
||||
</DropdownMenuItem>
|
||||
))
|
||||
) : (
|
||||
<DropdownMenuItem disabled className="text-xs text-muted-foreground">
|
||||
No scripts configured
|
||||
</DropdownMenuItem>
|
||||
)}
|
||||
{/* Divider before Edit Commands & Scripts */}
|
||||
<DropdownMenuSeparator />
|
||||
<DropdownMenuItem
|
||||
onClick={() => onEditScripts?.()}
|
||||
className="text-xs"
|
||||
disabled={!onEditScripts}
|
||||
>
|
||||
<Settings2 className="w-3.5 h-3.5 mr-2" />
|
||||
Edit Commands & Scripts
|
||||
</DropdownMenuItem>
|
||||
</DropdownMenuSubContent>
|
||||
</DropdownMenuSub>
|
||||
<DropdownMenuSeparator />
|
||||
<TooltipWrapper showTooltip={!!gitOpsDisabledReason} tooltipContent={gitOpsDisabledReason}>
|
||||
{remotes && remotes.length > 1 && onPullWithRemote ? (
|
||||
@@ -621,18 +803,20 @@ export function WorktreeActionsDropdown({
|
||||
</DropdownMenuLabel>
|
||||
<DropdownMenuSeparator />
|
||||
{remotes.map((remote) => (
|
||||
<DropdownMenuItem
|
||||
<RemoteActionMenuItem
|
||||
key={remote.name}
|
||||
onClick={() => isGitOpsAvailable && onPullWithRemote(worktree, remote.name)}
|
||||
disabled={isPulling || !isGitOpsAvailable}
|
||||
className="text-xs"
|
||||
>
|
||||
<Download className="w-3.5 h-3.5 mr-2" />
|
||||
{remote.name}
|
||||
<span className="ml-auto text-[10px] text-muted-foreground max-w-[100px] truncate">
|
||||
{remote.url}
|
||||
</span>
|
||||
</DropdownMenuItem>
|
||||
remote={remote}
|
||||
icon={Download}
|
||||
trackingRemote={trackingRemote}
|
||||
isDisabled={isPulling}
|
||||
isGitOpsAvailable={isGitOpsAvailable}
|
||||
onAction={() => isGitOpsAvailable && onPullWithRemote(worktree, remote.name)}
|
||||
onSetTracking={
|
||||
onSetTracking
|
||||
? () => isGitOpsAvailable && onSetTracking(worktree, remote.name)
|
||||
: undefined
|
||||
}
|
||||
/>
|
||||
))}
|
||||
</DropdownMenuSubContent>
|
||||
</DropdownMenuSub>
|
||||
@@ -720,18 +904,20 @@ export function WorktreeActionsDropdown({
|
||||
</DropdownMenuLabel>
|
||||
<DropdownMenuSeparator />
|
||||
{remotes.map((remote) => (
|
||||
<DropdownMenuItem
|
||||
<RemoteActionMenuItem
|
||||
key={remote.name}
|
||||
onClick={() => isGitOpsAvailable && onPushWithRemote(worktree, remote.name)}
|
||||
disabled={isPushing || !isGitOpsAvailable}
|
||||
className="text-xs"
|
||||
>
|
||||
<Upload className="w-3.5 h-3.5 mr-2" />
|
||||
{remote.name}
|
||||
<span className="ml-auto text-[10px] text-muted-foreground max-w-[100px] truncate">
|
||||
{remote.url}
|
||||
</span>
|
||||
</DropdownMenuItem>
|
||||
remote={remote}
|
||||
icon={Upload}
|
||||
trackingRemote={trackingRemote}
|
||||
isDisabled={isPushing}
|
||||
isGitOpsAvailable={isGitOpsAvailable}
|
||||
onAction={() => isGitOpsAvailable && onPushWithRemote(worktree, remote.name)}
|
||||
onSetTracking={
|
||||
onSetTracking
|
||||
? () => isGitOpsAvailable && onSetTracking(worktree, remote.name)
|
||||
: undefined
|
||||
}
|
||||
/>
|
||||
))}
|
||||
</DropdownMenuSubContent>
|
||||
</DropdownMenuSub>
|
||||
@@ -778,6 +964,72 @@ export function WorktreeActionsDropdown({
|
||||
</DropdownMenuItem>
|
||||
)}
|
||||
</TooltipWrapper>
|
||||
{onSync && (
|
||||
<TooltipWrapper
|
||||
showTooltip={!!gitOpsDisabledReason}
|
||||
tooltipContent={gitOpsDisabledReason}
|
||||
>
|
||||
{remotes && remotes.length > 1 && onSyncWithRemote ? (
|
||||
<DropdownMenuSub>
|
||||
<div className="flex items-center">
|
||||
<DropdownMenuItem
|
||||
onClick={() => isGitOpsAvailable && onSync(worktree)}
|
||||
disabled={isSyncing || !isGitOpsAvailable}
|
||||
className={cn(
|
||||
'text-xs flex-1 pr-0 rounded-r-none',
|
||||
!isGitOpsAvailable && 'opacity-50 cursor-not-allowed'
|
||||
)}
|
||||
>
|
||||
<RefreshCw className={cn('w-3.5 h-3.5 mr-2', isSyncing && 'animate-spin')} />
|
||||
{isSyncing ? 'Syncing...' : 'Sync'}
|
||||
{!isGitOpsAvailable && (
|
||||
<AlertCircle className="w-3 h-3 ml-auto text-muted-foreground" />
|
||||
)}
|
||||
</DropdownMenuItem>
|
||||
<DropdownMenuSubTrigger
|
||||
className={cn(
|
||||
'text-xs px-1 rounded-l-none border-l border-border/30 h-8',
|
||||
(!isGitOpsAvailable || isSyncing) && 'opacity-50 cursor-not-allowed'
|
||||
)}
|
||||
disabled={!isGitOpsAvailable || isSyncing}
|
||||
/>
|
||||
</div>
|
||||
<DropdownMenuSubContent>
|
||||
<DropdownMenuLabel className="text-xs text-muted-foreground font-normal">
|
||||
Sync with remote
|
||||
</DropdownMenuLabel>
|
||||
<DropdownMenuSeparator />
|
||||
{remotes.map((remote) => (
|
||||
<DropdownMenuItem
|
||||
key={`sync-${remote.name}`}
|
||||
onClick={() => isGitOpsAvailable && onSyncWithRemote(worktree, remote.name)}
|
||||
disabled={isSyncing || !isGitOpsAvailable}
|
||||
className="text-xs"
|
||||
>
|
||||
<RefreshCw className="w-3.5 h-3.5 mr-2" />
|
||||
{remote.name}
|
||||
<span className="ml-auto text-[10px] text-muted-foreground max-w-[100px] truncate">
|
||||
{remote.url}
|
||||
</span>
|
||||
</DropdownMenuItem>
|
||||
))}
|
||||
</DropdownMenuSubContent>
|
||||
</DropdownMenuSub>
|
||||
) : (
|
||||
<DropdownMenuItem
|
||||
onClick={() => isGitOpsAvailable && onSync(worktree)}
|
||||
disabled={isSyncing || !isGitOpsAvailable}
|
||||
className={cn('text-xs', !isGitOpsAvailable && 'opacity-50 cursor-not-allowed')}
|
||||
>
|
||||
<RefreshCw className={cn('w-3.5 h-3.5 mr-2', isSyncing && 'animate-spin')} />
|
||||
{isSyncing ? 'Syncing...' : 'Sync'}
|
||||
{!isGitOpsAvailable && (
|
||||
<AlertCircle className="w-3 h-3 ml-auto text-muted-foreground" />
|
||||
)}
|
||||
</DropdownMenuItem>
|
||||
)}
|
||||
</TooltipWrapper>
|
||||
)}
|
||||
<TooltipWrapper showTooltip={!!gitOpsDisabledReason} tooltipContent={gitOpsDisabledReason}>
|
||||
<DropdownMenuItem
|
||||
onClick={() => isGitOpsAvailable && onResolveConflicts(worktree)}
|
||||
@@ -815,32 +1067,67 @@ export function WorktreeActionsDropdown({
|
||||
</DropdownMenuItem>
|
||||
</TooltipWrapper>
|
||||
)}
|
||||
<TooltipWrapper showTooltip={!!gitOpsDisabledReason} tooltipContent={gitOpsDisabledReason}>
|
||||
<DropdownMenuItem
|
||||
onClick={() => isGitOpsAvailable && onViewCommits(worktree)}
|
||||
disabled={!isGitOpsAvailable}
|
||||
className={cn('text-xs', !isGitOpsAvailable && 'opacity-50 cursor-not-allowed')}
|
||||
>
|
||||
<History className="w-3.5 h-3.5 mr-2" />
|
||||
View Commits
|
||||
{!isGitOpsAvailable && (
|
||||
<AlertCircle className="w-3 h-3 ml-auto text-muted-foreground" />
|
||||
)}
|
||||
</DropdownMenuItem>
|
||||
</TooltipWrapper>
|
||||
{/* Cherry-pick commits from another branch */}
|
||||
{onCherryPick && (
|
||||
{/* View Commits - split button when Cherry Pick is available:
|
||||
click main area to view commits directly, chevron opens sub-menu with Cherry Pick */}
|
||||
{onCherryPick ? (
|
||||
<DropdownMenuSub>
|
||||
<TooltipWrapper
|
||||
showTooltip={!!gitOpsDisabledReason}
|
||||
tooltipContent={gitOpsDisabledReason}
|
||||
>
|
||||
<div className="flex items-center">
|
||||
{/* Main clickable area - opens commit history directly */}
|
||||
<DropdownMenuItem
|
||||
onClick={() => isGitOpsAvailable && onViewCommits(worktree)}
|
||||
disabled={!isGitOpsAvailable}
|
||||
className={cn(
|
||||
'text-xs flex-1 pr-0 rounded-r-none',
|
||||
!isGitOpsAvailable && 'opacity-50 cursor-not-allowed'
|
||||
)}
|
||||
>
|
||||
<History className="w-3.5 h-3.5 mr-2" />
|
||||
View Commits
|
||||
{!isGitOpsAvailable && (
|
||||
<AlertCircle className="w-3 h-3 ml-auto text-muted-foreground" />
|
||||
)}
|
||||
</DropdownMenuItem>
|
||||
{/* Chevron trigger for sub-menu containing Cherry Pick */}
|
||||
<DropdownMenuSubTrigger
|
||||
disabled={!isGitOpsAvailable}
|
||||
className={cn(
|
||||
'text-xs px-1 rounded-l-none border-l border-border/30 h-8',
|
||||
!isGitOpsAvailable && 'opacity-50 cursor-not-allowed'
|
||||
)}
|
||||
/>
|
||||
</div>
|
||||
</TooltipWrapper>
|
||||
<DropdownMenuSubContent>
|
||||
{/* Cherry-pick commits from another branch */}
|
||||
<DropdownMenuItem
|
||||
onClick={() => isGitOpsAvailable && onCherryPick(worktree)}
|
||||
disabled={!isGitOpsAvailable}
|
||||
className={cn('text-xs', !isGitOpsAvailable && 'opacity-50 cursor-not-allowed')}
|
||||
>
|
||||
<Cherry className="w-3.5 h-3.5 mr-2" />
|
||||
Cherry Pick
|
||||
{!isGitOpsAvailable && (
|
||||
<AlertCircle className="w-3 h-3 ml-auto text-muted-foreground" />
|
||||
)}
|
||||
</DropdownMenuItem>
|
||||
</DropdownMenuSubContent>
|
||||
</DropdownMenuSub>
|
||||
) : (
|
||||
<TooltipWrapper
|
||||
showTooltip={!!gitOpsDisabledReason}
|
||||
tooltipContent={gitOpsDisabledReason}
|
||||
>
|
||||
<DropdownMenuItem
|
||||
onClick={() => isGitOpsAvailable && onCherryPick(worktree)}
|
||||
onClick={() => isGitOpsAvailable && onViewCommits(worktree)}
|
||||
disabled={!isGitOpsAvailable}
|
||||
className={cn('text-xs', !isGitOpsAvailable && 'opacity-50 cursor-not-allowed')}
|
||||
>
|
||||
<Cherry className="w-3.5 h-3.5 mr-2" />
|
||||
Cherry Pick
|
||||
<History className="w-3.5 h-3.5 mr-2" />
|
||||
View Commits
|
||||
{!isGitOpsAvailable && (
|
||||
<AlertCircle className="w-3 h-3 ml-auto text-muted-foreground" />
|
||||
)}
|
||||
@@ -849,81 +1136,67 @@ export function WorktreeActionsDropdown({
|
||||
)}
|
||||
{(hasChangesSectionContent || hasDestructiveSectionContent) && <DropdownMenuSeparator />}
|
||||
|
||||
{worktree.hasChanges && (
|
||||
<DropdownMenuItem onClick={() => onViewChanges(worktree)} className="text-xs">
|
||||
<Eye className="w-3.5 h-3.5 mr-2" />
|
||||
View Changes
|
||||
</DropdownMenuItem>
|
||||
)}
|
||||
{/* Stash operations - combined submenu or simple item.
|
||||
{/* View Changes split button - main action views changes directly, chevron reveals stash options.
|
||||
Only render when at least one action is meaningful:
|
||||
- (worktree.hasChanges && onStashChanges): stashing changes is possible
|
||||
- onViewStashes: viewing existing stashes is possible
|
||||
Without this guard, the item would appear clickable but be a silent no-op
|
||||
when hasChanges is false and onViewStashes is undefined. */}
|
||||
{((worktree.hasChanges && onStashChanges) || onViewStashes) && (
|
||||
<TooltipWrapper showTooltip={!isGitOpsAvailable} tooltipContent={gitOpsDisabledReason}>
|
||||
{onViewStashes && worktree.hasChanges && onStashChanges ? (
|
||||
// Both "Stash Changes" (primary) and "View Stashes" (secondary) are available - show split submenu
|
||||
<DropdownMenuSub>
|
||||
<div className="flex items-center">
|
||||
{/* Main clickable area - stash changes (primary action) */}
|
||||
- worktree.hasChanges: View Changes action is available
|
||||
- (worktree.hasChanges && onStashChanges): Create Stash action is possible
|
||||
- onViewStashes: viewing existing stashes is possible */}
|
||||
{/* View Changes split button - show submenu only when there are non-duplicate sub-actions */}
|
||||
{worktree.hasChanges && (onStashChanges || onViewStashes) ? (
|
||||
<DropdownMenuSub>
|
||||
<div className="flex items-center">
|
||||
{/* Main clickable area - view changes (primary action) */}
|
||||
<DropdownMenuItem
|
||||
onClick={() => onViewChanges(worktree)}
|
||||
className="text-xs flex-1 pr-0 rounded-r-none"
|
||||
>
|
||||
<Eye className="w-3.5 h-3.5 mr-2" />
|
||||
View Changes
|
||||
</DropdownMenuItem>
|
||||
{/* Chevron trigger for submenu with stash options */}
|
||||
<DropdownMenuSubTrigger className="text-xs px-1 rounded-l-none border-l border-border/30 h-8" />
|
||||
</div>
|
||||
<DropdownMenuSubContent>
|
||||
{onStashChanges && (
|
||||
<TooltipWrapper
|
||||
showTooltip={!isGitOpsAvailable}
|
||||
tooltipContent={gitOpsDisabledReason}
|
||||
>
|
||||
<DropdownMenuItem
|
||||
onClick={() => {
|
||||
if (!isGitOpsAvailable) return;
|
||||
onStashChanges(worktree);
|
||||
}}
|
||||
disabled={!isGitOpsAvailable}
|
||||
className={cn(
|
||||
'text-xs flex-1 pr-0 rounded-r-none',
|
||||
!isGitOpsAvailable && 'opacity-50 cursor-not-allowed'
|
||||
)}
|
||||
className={cn('text-xs', !isGitOpsAvailable && 'opacity-50 cursor-not-allowed')}
|
||||
>
|
||||
<Archive className="w-3.5 h-3.5 mr-2" />
|
||||
Stash Changes
|
||||
Create Stash
|
||||
{!isGitOpsAvailable && (
|
||||
<AlertCircle className="w-3 h-3 ml-auto text-muted-foreground" />
|
||||
)}
|
||||
</DropdownMenuItem>
|
||||
{/* Chevron trigger for submenu with stash options */}
|
||||
<DropdownMenuSubTrigger
|
||||
className={cn(
|
||||
'text-xs px-1 rounded-l-none border-l border-border/30 h-8',
|
||||
!isGitOpsAvailable && 'opacity-50 cursor-not-allowed'
|
||||
)}
|
||||
disabled={!isGitOpsAvailable}
|
||||
/>
|
||||
</div>
|
||||
<DropdownMenuSubContent>
|
||||
<DropdownMenuItem onClick={() => onViewStashes(worktree)} className="text-xs">
|
||||
<Eye className="w-3.5 h-3.5 mr-2" />
|
||||
View Stashes
|
||||
</DropdownMenuItem>
|
||||
</DropdownMenuSubContent>
|
||||
</DropdownMenuSub>
|
||||
) : (
|
||||
// Only one action is meaningful - render a simple menu item without submenu
|
||||
<DropdownMenuItem
|
||||
onClick={() => {
|
||||
if (!isGitOpsAvailable) return;
|
||||
if (worktree.hasChanges && onStashChanges) {
|
||||
onStashChanges(worktree);
|
||||
} else if (onViewStashes) {
|
||||
onViewStashes(worktree);
|
||||
}
|
||||
}}
|
||||
disabled={!isGitOpsAvailable}
|
||||
className={cn('text-xs', !isGitOpsAvailable && 'opacity-50 cursor-not-allowed')}
|
||||
>
|
||||
<Archive className="w-3.5 h-3.5 mr-2" />
|
||||
{worktree.hasChanges && onStashChanges ? 'Stash Changes' : 'Stashes'}
|
||||
{!isGitOpsAvailable && (
|
||||
<AlertCircle className="w-3 h-3 ml-auto text-muted-foreground" />
|
||||
)}
|
||||
</DropdownMenuItem>
|
||||
)}
|
||||
</TooltipWrapper>
|
||||
)}
|
||||
</TooltipWrapper>
|
||||
)}
|
||||
{onViewStashes && (
|
||||
<DropdownMenuItem onClick={() => onViewStashes(worktree)} className="text-xs">
|
||||
<Eye className="w-3.5 h-3.5 mr-2" />
|
||||
View Stashes
|
||||
</DropdownMenuItem>
|
||||
)}
|
||||
</DropdownMenuSubContent>
|
||||
</DropdownMenuSub>
|
||||
) : worktree.hasChanges ? (
|
||||
<DropdownMenuItem onClick={() => onViewChanges(worktree)} className="text-xs">
|
||||
<Eye className="w-3.5 h-3.5 mr-2" />
|
||||
View Changes
|
||||
</DropdownMenuItem>
|
||||
) : onViewStashes ? (
|
||||
<DropdownMenuItem onClick={() => onViewStashes(worktree)} className="text-xs">
|
||||
<Eye className="w-3.5 h-3.5 mr-2" />
|
||||
View Stashes
|
||||
</DropdownMenuItem>
|
||||
) : null}
|
||||
{worktree.hasChanges && (
|
||||
<TooltipWrapper
|
||||
showTooltip={!!gitOpsDisabledReason}
|
||||
@@ -961,43 +1234,52 @@ export function WorktreeActionsDropdown({
|
||||
</DropdownMenuItem>
|
||||
</TooltipWrapper>
|
||||
)}
|
||||
{/* Show PR info and Address Comments button if PR exists */}
|
||||
{showPRInfo && worktree.pr && (
|
||||
<>
|
||||
<DropdownMenuItem
|
||||
onClick={() => {
|
||||
window.open(worktree.pr!.url, '_blank', 'noopener,noreferrer');
|
||||
}}
|
||||
className="text-xs"
|
||||
>
|
||||
<GitPullRequest className="w-3 h-3 mr-2" />
|
||||
PR #{worktree.pr.number}
|
||||
<span className="ml-auto text-[10px] bg-green-500/20 text-green-600 px-1.5 py-0.5 rounded uppercase">
|
||||
{worktree.pr.state}
|
||||
</span>
|
||||
</DropdownMenuItem>
|
||||
<DropdownMenuItem
|
||||
onClick={() => {
|
||||
// Convert stored PR info to the full PRInfo format for the handler
|
||||
// The handler will fetch full comments from GitHub
|
||||
const prInfo: PRInfo = {
|
||||
number: worktree.pr!.number,
|
||||
title: worktree.pr!.title,
|
||||
url: worktree.pr!.url,
|
||||
state: worktree.pr!.state,
|
||||
author: '', // Will be fetched
|
||||
body: '', // Will be fetched
|
||||
comments: [],
|
||||
reviewComments: [],
|
||||
};
|
||||
onAddressPRComments(worktree, prInfo);
|
||||
}}
|
||||
className="text-xs text-blue-500 focus:text-blue-600"
|
||||
>
|
||||
<MessageSquare className="w-3.5 h-3.5 mr-2" />
|
||||
Address PR Comments
|
||||
</DropdownMenuItem>
|
||||
</>
|
||||
{/* Show PR info with Address Comments in sub-menu if PR exists */}
|
||||
{prInfo && worktree.pr && (
|
||||
<DropdownMenuSub>
|
||||
<div className="flex items-center">
|
||||
{/* Main clickable area - opens PR in browser */}
|
||||
<DropdownMenuItem
|
||||
onClick={() => {
|
||||
window.open(worktree.pr!.url, '_blank', 'noopener,noreferrer');
|
||||
}}
|
||||
className="text-xs flex-1 pr-0 rounded-r-none"
|
||||
>
|
||||
<GitPullRequest className="w-3 h-3 mr-2" />
|
||||
PR #{worktree.pr.number}
|
||||
<span
|
||||
className={cn(
|
||||
'ml-auto mr-1 text-[10px] px-1.5 py-0.5 rounded uppercase',
|
||||
worktree.pr.state === 'MERGED'
|
||||
? 'bg-purple-500/20 text-purple-600'
|
||||
: worktree.pr.state === 'CLOSED'
|
||||
? 'bg-gray-500/20 text-gray-500'
|
||||
: 'bg-green-500/20 text-green-600'
|
||||
)}
|
||||
>
|
||||
{worktree.pr.state}
|
||||
</span>
|
||||
</DropdownMenuItem>
|
||||
{/* Chevron trigger for submenu with PR actions */}
|
||||
<DropdownMenuSubTrigger className="text-xs px-1 rounded-l-none border-l border-border/30 h-8" />
|
||||
</div>
|
||||
<DropdownMenuSubContent>
|
||||
<DropdownMenuItem
|
||||
onClick={() => onAddressPRComments(worktree, prInfo)}
|
||||
className="text-xs text-blue-500 focus:text-blue-600"
|
||||
>
|
||||
<MessageSquare className="w-3.5 h-3.5 mr-2" />
|
||||
Manage PR Comments
|
||||
</DropdownMenuItem>
|
||||
<DropdownMenuItem
|
||||
onClick={() => onAutoAddressPRComments(worktree, prInfo)}
|
||||
className="text-xs text-blue-500 focus:text-blue-600"
|
||||
>
|
||||
<Zap className="w-3.5 h-3.5 mr-2" />
|
||||
Address PR Comments
|
||||
</DropdownMenuItem>
|
||||
</DropdownMenuSubContent>
|
||||
</DropdownMenuSub>
|
||||
)}
|
||||
{hasChangesSectionContent && hasDestructiveSectionContent && <DropdownMenuSeparator />}
|
||||
{worktree.hasChanges && (
|
||||
|
||||
@@ -144,8 +144,8 @@ export function WorktreeDropdownItem({
|
||||
</span>
|
||||
)}
|
||||
|
||||
{/* Dev server indicator */}
|
||||
{devServerRunning && (
|
||||
{/* Dev server indicator - hidden when URL detection explicitly failed */}
|
||||
{devServerRunning && devServerInfo?.urlDetected !== false && (
|
||||
<span
|
||||
className="inline-flex items-center justify-center h-4 w-4 text-green-500"
|
||||
title={`Dev server running on port ${devServerInfo?.port}`}
|
||||
|
||||
@@ -103,6 +103,7 @@ export interface WorktreeDropdownProps {
|
||||
onCommit: (worktree: WorktreeInfo) => void;
|
||||
onCreatePR: (worktree: WorktreeInfo) => void;
|
||||
onAddressPRComments: (worktree: WorktreeInfo, prInfo: PRInfo) => void;
|
||||
onAutoAddressPRComments: (worktree: WorktreeInfo, prInfo: PRInfo) => void;
|
||||
onResolveConflicts: (worktree: WorktreeInfo) => void;
|
||||
onMerge: (worktree: WorktreeInfo) => void;
|
||||
onDeleteWorktree: (worktree: WorktreeInfo) => void;
|
||||
@@ -131,6 +132,20 @@ export interface WorktreeDropdownProps {
|
||||
onPullWithRemote?: (worktree: WorktreeInfo, remote: string) => void;
|
||||
/** Push to a specific remote, bypassing the remote selection dialog */
|
||||
onPushWithRemote?: (worktree: WorktreeInfo, remote: string) => void;
|
||||
/** Terminal quick scripts configured for the project */
|
||||
terminalScripts?: import('@/components/views/project-settings-view/terminal-scripts-constants').TerminalScript[];
|
||||
/** Callback to run a terminal quick script in a new terminal session */
|
||||
onRunTerminalScript?: (worktree: WorktreeInfo, command: string) => void;
|
||||
/** Callback to open the script editor UI */
|
||||
onEditScripts?: () => void;
|
||||
/** Whether sync is in progress */
|
||||
isSyncing?: boolean;
|
||||
/** Sync (pull + push) callback */
|
||||
onSync?: (worktree: WorktreeInfo) => void;
|
||||
/** Sync with a specific remote */
|
||||
onSyncWithRemote?: (worktree: WorktreeInfo, remote: string) => void;
|
||||
/** Set tracking branch to a specific remote */
|
||||
onSetTracking?: (worktree: WorktreeInfo, remote: string) => void;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -199,6 +214,7 @@ export function WorktreeDropdown({
|
||||
onCommit,
|
||||
onCreatePR,
|
||||
onAddressPRComments,
|
||||
onAutoAddressPRComments,
|
||||
onResolveConflicts,
|
||||
onMerge,
|
||||
onDeleteWorktree,
|
||||
@@ -219,6 +235,13 @@ export function WorktreeDropdown({
|
||||
remotesCache,
|
||||
onPullWithRemote,
|
||||
onPushWithRemote,
|
||||
terminalScripts,
|
||||
onRunTerminalScript,
|
||||
onEditScripts,
|
||||
isSyncing = false,
|
||||
onSync,
|
||||
onSyncWithRemote,
|
||||
onSetTracking,
|
||||
}: WorktreeDropdownProps) {
|
||||
// Find the currently selected worktree to display in the trigger
|
||||
const selectedWorktree = worktrees.find((w) => isWorktreeSelected(w));
|
||||
@@ -304,15 +327,11 @@ export function WorktreeDropdown({
|
||||
</span>
|
||||
)}
|
||||
|
||||
{/* Dev server indicator */}
|
||||
{selectedStatus.devServerRunning && (
|
||||
{/* Dev server indicator - only shown when port is confirmed detected */}
|
||||
{selectedStatus.devServerRunning && selectedStatus.devServerInfo?.urlDetected !== false && (
|
||||
<span
|
||||
className="inline-flex items-center justify-center h-4 w-4 text-green-500 shrink-0"
|
||||
title={
|
||||
selectedStatus.devServerInfo?.urlDetected === false
|
||||
? 'Dev server starting...'
|
||||
: `Dev server running on port ${selectedStatus.devServerInfo?.port}`
|
||||
}
|
||||
title={`Dev server running on port ${selectedStatus.devServerInfo?.port}`}
|
||||
>
|
||||
<Globe className="w-3 h-3" />
|
||||
</span>
|
||||
@@ -520,6 +539,7 @@ export function WorktreeDropdown({
|
||||
onCommit={onCommit}
|
||||
onCreatePR={onCreatePR}
|
||||
onAddressPRComments={onAddressPRComments}
|
||||
onAutoAddressPRComments={onAutoAddressPRComments}
|
||||
onResolveConflicts={onResolveConflicts}
|
||||
onMerge={onMerge}
|
||||
onDeleteWorktree={onDeleteWorktree}
|
||||
@@ -538,6 +558,13 @@ export function WorktreeDropdown({
|
||||
onAbortOperation={onAbortOperation}
|
||||
onContinueOperation={onContinueOperation}
|
||||
hasInitScript={hasInitScript}
|
||||
terminalScripts={terminalScripts}
|
||||
onRunTerminalScript={onRunTerminalScript}
|
||||
onEditScripts={onEditScripts}
|
||||
isSyncing={isSyncing}
|
||||
onSync={onSync}
|
||||
onSyncWithRemote={onSyncWithRemote}
|
||||
onSetTracking={onSetTracking}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
|
||||
@@ -67,6 +67,7 @@ interface WorktreeTabProps {
|
||||
onCommit: (worktree: WorktreeInfo) => void;
|
||||
onCreatePR: (worktree: WorktreeInfo) => void;
|
||||
onAddressPRComments: (worktree: WorktreeInfo, prInfo: PRInfo) => void;
|
||||
onAutoAddressPRComments: (worktree: WorktreeInfo, prInfo: PRInfo) => void;
|
||||
onResolveConflicts: (worktree: WorktreeInfo) => void;
|
||||
onMerge: (worktree: WorktreeInfo) => void;
|
||||
onDeleteWorktree: (worktree: WorktreeInfo) => void;
|
||||
@@ -101,6 +102,20 @@ interface WorktreeTabProps {
|
||||
onPullWithRemote?: (worktree: WorktreeInfo, remote: string) => void;
|
||||
/** Push to a specific remote, bypassing the remote selection dialog */
|
||||
onPushWithRemote?: (worktree: WorktreeInfo, remote: string) => void;
|
||||
/** Terminal quick scripts configured for the project */
|
||||
terminalScripts?: import('@/components/views/project-settings-view/terminal-scripts-constants').TerminalScript[];
|
||||
/** Callback to run a terminal quick script in a new terminal session */
|
||||
onRunTerminalScript?: (worktree: WorktreeInfo, command: string) => void;
|
||||
/** Callback to open the script editor UI */
|
||||
onEditScripts?: () => void;
|
||||
/** Whether sync is in progress */
|
||||
isSyncing?: boolean;
|
||||
/** Sync (pull + push) callback */
|
||||
onSync?: (worktree: WorktreeInfo) => void;
|
||||
/** Sync with a specific remote */
|
||||
onSyncWithRemote?: (worktree: WorktreeInfo, remote: string) => void;
|
||||
/** Set tracking branch to a specific remote */
|
||||
onSetTracking?: (worktree: WorktreeInfo, remote: string) => void;
|
||||
}
|
||||
|
||||
export function WorktreeTab({
|
||||
@@ -148,6 +163,7 @@ export function WorktreeTab({
|
||||
onCommit,
|
||||
onCreatePR,
|
||||
onAddressPRComments,
|
||||
onAutoAddressPRComments,
|
||||
onResolveConflicts,
|
||||
onMerge,
|
||||
onDeleteWorktree,
|
||||
@@ -170,6 +186,13 @@ export function WorktreeTab({
|
||||
remotes,
|
||||
onPullWithRemote,
|
||||
onPushWithRemote,
|
||||
terminalScripts,
|
||||
onRunTerminalScript,
|
||||
onEditScripts,
|
||||
isSyncing = false,
|
||||
onSync,
|
||||
onSyncWithRemote,
|
||||
onSetTracking,
|
||||
}: WorktreeTabProps) {
|
||||
// Make the worktree tab a drop target for feature cards
|
||||
const { setNodeRef, isOver } = useDroppable({
|
||||
@@ -440,7 +463,7 @@ export function WorktreeTab({
|
||||
</Button>
|
||||
)}
|
||||
|
||||
{isDevServerRunning && (
|
||||
{isDevServerRunning && devServerInfo?.urlDetected !== false && (
|
||||
<Tooltip>
|
||||
<TooltipTrigger asChild>
|
||||
<Button
|
||||
@@ -517,6 +540,7 @@ export function WorktreeTab({
|
||||
onCommit={onCommit}
|
||||
onCreatePR={onCreatePR}
|
||||
onAddressPRComments={onAddressPRComments}
|
||||
onAutoAddressPRComments={onAutoAddressPRComments}
|
||||
onResolveConflicts={onResolveConflicts}
|
||||
onMerge={onMerge}
|
||||
onDeleteWorktree={onDeleteWorktree}
|
||||
@@ -535,6 +559,13 @@ export function WorktreeTab({
|
||||
onAbortOperation={onAbortOperation}
|
||||
onContinueOperation={onContinueOperation}
|
||||
hasInitScript={hasInitScript}
|
||||
terminalScripts={terminalScripts}
|
||||
onRunTerminalScript={onRunTerminalScript}
|
||||
onEditScripts={onEditScripts}
|
||||
isSyncing={isSyncing}
|
||||
onSync={onSync}
|
||||
onSyncWithRemote={onSyncWithRemote}
|
||||
onSetTracking={onSetTracking}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { useState, useEffect, useCallback } from 'react';
|
||||
import { useState, useEffect, useCallback, useRef } from 'react';
|
||||
import { createLogger } from '@automaker/utils/logger';
|
||||
import { getElectronAPI } from '@/lib/electron';
|
||||
import { normalizePath } from '@/lib/utils';
|
||||
@@ -7,14 +7,175 @@ import type { DevServerInfo, WorktreeInfo } from '../types';
|
||||
|
||||
const logger = createLogger('DevServers');
|
||||
|
||||
// Timeout (ms) for port detection before showing a warning to the user
|
||||
const PORT_DETECTION_TIMEOUT_MS = 30_000;
|
||||
// Interval (ms) for periodic state reconciliation with the backend
|
||||
const STATE_RECONCILE_INTERVAL_MS = 5_000;
|
||||
|
||||
interface UseDevServersOptions {
|
||||
projectPath: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* Helper to build the browser-accessible dev server URL by rewriting the hostname
|
||||
* to match the current window's hostname (supports remote access).
|
||||
* Returns null if the URL is invalid or uses an unsupported protocol.
|
||||
*/
|
||||
function buildDevServerBrowserUrl(serverUrl: string): string | null {
|
||||
try {
|
||||
const devServerUrl = new URL(serverUrl);
|
||||
// Security: Only allow http/https protocols
|
||||
if (devServerUrl.protocol !== 'http:' && devServerUrl.protocol !== 'https:') {
|
||||
return null;
|
||||
}
|
||||
devServerUrl.hostname = window.location.hostname;
|
||||
return devServerUrl.toString();
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Show a toast notification for a detected dev server URL.
|
||||
* Extracted to avoid duplication between event handler and reconciliation paths.
|
||||
*/
|
||||
function showUrlDetectedToast(url: string, port: number): void {
|
||||
const browserUrl = buildDevServerBrowserUrl(url);
|
||||
toast.success(`Dev server running on port ${port}`, {
|
||||
description: browserUrl ? browserUrl : url,
|
||||
action: browserUrl
|
||||
? {
|
||||
label: 'Open in Browser',
|
||||
onClick: () => {
|
||||
window.open(browserUrl, '_blank', 'noopener,noreferrer');
|
||||
},
|
||||
}
|
||||
: undefined,
|
||||
duration: 8000,
|
||||
});
|
||||
}
|
||||
|
||||
export function useDevServers({ projectPath }: UseDevServersOptions) {
|
||||
const [isStartingDevServer, setIsStartingDevServer] = useState(false);
|
||||
const [runningDevServers, setRunningDevServers] = useState<Map<string, DevServerInfo>>(new Map());
|
||||
|
||||
// Track which worktrees have had their url-detected toast shown to prevent re-triggering
|
||||
const toastShownForRef = useRef<Set<string>>(new Set());
|
||||
|
||||
// Track port detection timeouts per worktree key
|
||||
const portDetectionTimers = useRef<Map<string, NodeJS.Timeout>>(new Map());
|
||||
|
||||
// Track whether initial fetch has completed to avoid reconciliation race
|
||||
const initialFetchDone = useRef(false);
|
||||
|
||||
/**
|
||||
* Clear a port detection timeout for a given key
|
||||
*/
|
||||
const clearPortDetectionTimer = useCallback((key: string) => {
|
||||
const timer = portDetectionTimers.current.get(key);
|
||||
if (timer) {
|
||||
clearTimeout(timer);
|
||||
portDetectionTimers.current.delete(key);
|
||||
}
|
||||
}, []);
|
||||
|
||||
/**
|
||||
* Start a port detection timeout for a server that hasn't detected its URL yet.
|
||||
* After PORT_DETECTION_TIMEOUT_MS, if still undetected, show a warning toast
|
||||
* and attempt to reconcile state with the backend.
|
||||
*/
|
||||
const startPortDetectionTimer = useCallback(
|
||||
(key: string) => {
|
||||
// Clear any existing timer for this key
|
||||
clearPortDetectionTimer(key);
|
||||
|
||||
const timer = setTimeout(async () => {
|
||||
portDetectionTimers.current.delete(key);
|
||||
|
||||
// Check if the server is still in undetected state.
|
||||
// Use a setState-updater-as-reader to access the latest state snapshot,
|
||||
// but keep the updater pure (no side effects, just reads).
|
||||
let needsReconciliation = false;
|
||||
setRunningDevServers((prev) => {
|
||||
const server = prev.get(key);
|
||||
needsReconciliation = !!server && !server.urlDetected;
|
||||
return prev; // no state change
|
||||
});
|
||||
|
||||
if (!needsReconciliation) return;
|
||||
|
||||
logger.warn(`Port detection timeout for ${key} after ${PORT_DETECTION_TIMEOUT_MS}ms`);
|
||||
|
||||
// Try to reconcile with backend - the server may have detected the URL
|
||||
// but the WebSocket event was missed
|
||||
try {
|
||||
const api = getElectronAPI();
|
||||
if (!api?.worktree?.listDevServers) return;
|
||||
const result = await api.worktree.listDevServers();
|
||||
if (result.success && result.result?.servers) {
|
||||
const backendServer = result.result.servers.find(
|
||||
(s) => normalizePath(s.worktreePath) === key
|
||||
);
|
||||
if (backendServer && backendServer.urlDetected) {
|
||||
// Backend has detected the URL - update our state
|
||||
logger.info(`Port detection reconciled from backend for ${key}`);
|
||||
setRunningDevServers((prev) => {
|
||||
const next = new Map(prev);
|
||||
next.set(key, {
|
||||
...backendServer,
|
||||
urlDetected: true,
|
||||
});
|
||||
return next;
|
||||
});
|
||||
if (!toastShownForRef.current.has(key)) {
|
||||
toastShownForRef.current.add(key);
|
||||
showUrlDetectedToast(backendServer.url, backendServer.port);
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
if (!backendServer) {
|
||||
// Server is no longer running on the backend - remove from state
|
||||
logger.info(`Server ${key} no longer running on backend, removing from state`);
|
||||
setRunningDevServers((prev) => {
|
||||
if (!prev.has(key)) return prev;
|
||||
const next = new Map(prev);
|
||||
next.delete(key);
|
||||
return next;
|
||||
});
|
||||
toastShownForRef.current.delete(key);
|
||||
return;
|
||||
}
|
||||
}
|
||||
} catch (error) {
|
||||
logger.error('Failed to reconcile port detection:', error);
|
||||
}
|
||||
|
||||
// If we get here, the backend also hasn't detected the URL - show warning
|
||||
toast.warning('Port detection is taking longer than expected', {
|
||||
description:
|
||||
'The dev server may be slow to start, or the port output format is not recognized.',
|
||||
action: {
|
||||
label: 'Retry',
|
||||
onClick: () => {
|
||||
// Use ref to get the latest startPortDetectionTimer, avoiding stale closure
|
||||
startPortDetectionTimerRef.current(key);
|
||||
},
|
||||
},
|
||||
duration: 10000,
|
||||
});
|
||||
}, PORT_DETECTION_TIMEOUT_MS);
|
||||
|
||||
portDetectionTimers.current.set(key, timer);
|
||||
},
|
||||
[clearPortDetectionTimer]
|
||||
);
|
||||
|
||||
// Ref to hold the latest startPortDetectionTimer callback, avoiding stale closures
|
||||
// in long-lived callbacks like toast action handlers
|
||||
const startPortDetectionTimerRef = useRef(startPortDetectionTimer);
|
||||
startPortDetectionTimerRef.current = startPortDetectionTimer;
|
||||
|
||||
const fetchDevServers = useCallback(async () => {
|
||||
try {
|
||||
const api = getElectronAPI();
|
||||
@@ -25,23 +186,142 @@ export function useDevServers({ projectPath }: UseDevServersOptions) {
|
||||
if (result.success && result.result?.servers) {
|
||||
const serversMap = new Map<string, DevServerInfo>();
|
||||
for (const server of result.result.servers) {
|
||||
serversMap.set(normalizePath(server.worktreePath), {
|
||||
const key = normalizePath(server.worktreePath);
|
||||
serversMap.set(key, {
|
||||
...server,
|
||||
urlDetected: server.urlDetected ?? true,
|
||||
});
|
||||
// Mark already-detected servers as having shown the toast
|
||||
// so we don't re-trigger on initial load
|
||||
if (server.urlDetected !== false) {
|
||||
toastShownForRef.current.add(key);
|
||||
// Clear any pending detection timer since URL is already detected
|
||||
clearPortDetectionTimer(key);
|
||||
} else {
|
||||
// Server running but URL not yet detected - start timeout
|
||||
startPortDetectionTimer(key);
|
||||
}
|
||||
}
|
||||
setRunningDevServers(serversMap);
|
||||
}
|
||||
initialFetchDone.current = true;
|
||||
} catch (error) {
|
||||
logger.error('Failed to fetch dev servers:', error);
|
||||
initialFetchDone.current = true;
|
||||
}
|
||||
}, []);
|
||||
}, [clearPortDetectionTimer, startPortDetectionTimer]);
|
||||
|
||||
useEffect(() => {
|
||||
fetchDevServers();
|
||||
}, [fetchDevServers]);
|
||||
|
||||
// Subscribe to url-detected events to update port/url when the actual dev server port is detected
|
||||
// Periodic state reconciliation: poll backend to catch missed WebSocket events
|
||||
// This handles edge cases like PWA restart, WebSocket reconnection gaps, etc.
|
||||
useEffect(() => {
|
||||
const reconcile = async () => {
|
||||
if (!initialFetchDone.current) return;
|
||||
// Skip reconciliation when the tab/panel is not visible to avoid
|
||||
// unnecessary API calls while the user isn't looking at the panel.
|
||||
if (document.hidden) return;
|
||||
|
||||
try {
|
||||
const api = getElectronAPI();
|
||||
if (!api?.worktree?.listDevServers) return;
|
||||
|
||||
const result = await api.worktree.listDevServers();
|
||||
if (!result.success || !result.result?.servers) return;
|
||||
|
||||
const backendServers = new Map<string, (typeof result.result.servers)[number]>();
|
||||
for (const server of result.result.servers) {
|
||||
backendServers.set(normalizePath(server.worktreePath), server);
|
||||
}
|
||||
|
||||
// Collect side-effect actions in a local array so the setState updater
|
||||
// remains pure. Side effects are executed after the state update.
|
||||
const sideEffects: Array<() => void> = [];
|
||||
|
||||
setRunningDevServers((prev) => {
|
||||
let changed = false;
|
||||
const next = new Map(prev);
|
||||
|
||||
// Add or update servers from backend
|
||||
for (const [key, server] of backendServers) {
|
||||
const existing = next.get(key);
|
||||
if (!existing) {
|
||||
// Server running on backend but not in our state - add it
|
||||
sideEffects.push(() => logger.info(`Reconciliation: adding missing server ${key}`));
|
||||
next.set(key, {
|
||||
...server,
|
||||
urlDetected: server.urlDetected ?? true,
|
||||
});
|
||||
if (server.urlDetected !== false) {
|
||||
sideEffects.push(() => {
|
||||
toastShownForRef.current.add(key);
|
||||
clearPortDetectionTimer(key);
|
||||
});
|
||||
} else {
|
||||
sideEffects.push(() => startPortDetectionTimer(key));
|
||||
}
|
||||
changed = true;
|
||||
} else if (!existing.urlDetected && server.urlDetected) {
|
||||
// URL was detected on backend but we missed the event - update
|
||||
sideEffects.push(() => {
|
||||
logger.info(`Reconciliation: URL detected for ${key}`);
|
||||
clearPortDetectionTimer(key);
|
||||
if (!toastShownForRef.current.has(key)) {
|
||||
toastShownForRef.current.add(key);
|
||||
showUrlDetectedToast(server.url, server.port);
|
||||
}
|
||||
});
|
||||
next.set(key, {
|
||||
...server,
|
||||
urlDetected: true,
|
||||
});
|
||||
changed = true;
|
||||
} else if (
|
||||
existing.urlDetected &&
|
||||
server.urlDetected &&
|
||||
(existing.port !== server.port || existing.url !== server.url)
|
||||
) {
|
||||
// Port or URL changed between sessions - update
|
||||
sideEffects.push(() => logger.info(`Reconciliation: port/URL changed for ${key}`));
|
||||
next.set(key, {
|
||||
...server,
|
||||
urlDetected: true,
|
||||
});
|
||||
changed = true;
|
||||
}
|
||||
}
|
||||
|
||||
// Remove servers from our state that are no longer on the backend
|
||||
for (const [key] of next) {
|
||||
if (!backendServers.has(key)) {
|
||||
sideEffects.push(() => {
|
||||
logger.info(`Reconciliation: removing stale server ${key}`);
|
||||
toastShownForRef.current.delete(key);
|
||||
clearPortDetectionTimer(key);
|
||||
});
|
||||
next.delete(key);
|
||||
changed = true;
|
||||
}
|
||||
}
|
||||
|
||||
return changed ? next : prev;
|
||||
});
|
||||
|
||||
// Execute side effects outside the updater
|
||||
for (const fn of sideEffects) fn();
|
||||
} catch (error) {
|
||||
// Reconciliation failures are non-critical - just log and continue
|
||||
logger.debug('State reconciliation failed:', error);
|
||||
}
|
||||
};
|
||||
|
||||
const intervalId = setInterval(reconcile, STATE_RECONCILE_INTERVAL_MS);
|
||||
return () => clearInterval(intervalId);
|
||||
}, [clearPortDetectionTimer, startPortDetectionTimer]);
|
||||
|
||||
// Subscribe to all dev server lifecycle events for reactive state updates
|
||||
useEffect(() => {
|
||||
const api = getElectronAPI();
|
||||
if (!api?.worktree?.onDevServerLogEvent) return;
|
||||
@@ -50,10 +330,26 @@ export function useDevServers({ projectPath }: UseDevServersOptions) {
|
||||
if (event.type === 'dev-server:url-detected') {
|
||||
const { worktreePath, url, port } = event.payload;
|
||||
const key = normalizePath(worktreePath);
|
||||
// Clear the port detection timeout since URL was successfully detected
|
||||
clearPortDetectionTimer(key);
|
||||
let didUpdate = false;
|
||||
setRunningDevServers((prev) => {
|
||||
const existing = prev.get(key);
|
||||
if (!existing) return prev;
|
||||
// If the server isn't in our state yet (e.g., race condition on first load
|
||||
// where url-detected arrives before fetchDevServers completes), create the entry
|
||||
if (!existing) {
|
||||
const next = new Map(prev);
|
||||
next.set(key, {
|
||||
worktreePath,
|
||||
url,
|
||||
port,
|
||||
urlDetected: true,
|
||||
});
|
||||
didUpdate = true;
|
||||
return next;
|
||||
}
|
||||
// Avoid updating if already detected with same url/port
|
||||
if (existing.urlDetected && existing.url === url && existing.port === port) return prev;
|
||||
const next = new Map(prev);
|
||||
next.set(key, {
|
||||
...existing,
|
||||
@@ -66,12 +362,59 @@ export function useDevServers({ projectPath }: UseDevServersOptions) {
|
||||
});
|
||||
if (didUpdate) {
|
||||
logger.info(`Dev server URL detected for ${worktreePath}: ${url} (port ${port})`);
|
||||
toast.success(`Dev server running on port ${port}`);
|
||||
// Only show toast on the transition from undetected → detected (not on re-renders/polls)
|
||||
if (!toastShownForRef.current.has(key)) {
|
||||
toastShownForRef.current.add(key);
|
||||
showUrlDetectedToast(url, port);
|
||||
}
|
||||
}
|
||||
} else if (event.type === 'dev-server:stopped') {
|
||||
// Reactively remove the server from state when it stops
|
||||
const { worktreePath } = event.payload;
|
||||
const key = normalizePath(worktreePath);
|
||||
// Clear any pending port detection timeout
|
||||
clearPortDetectionTimer(key);
|
||||
setRunningDevServers((prev) => {
|
||||
if (!prev.has(key)) return prev;
|
||||
const next = new Map(prev);
|
||||
next.delete(key);
|
||||
return next;
|
||||
});
|
||||
// Clear the toast tracking so a fresh detection will show a new toast
|
||||
toastShownForRef.current.delete(key);
|
||||
logger.info(`Dev server stopped for ${worktreePath} (reactive update)`);
|
||||
} else if (event.type === 'dev-server:started') {
|
||||
// Reactively add/update the server when it starts
|
||||
const { worktreePath, port, url } = event.payload;
|
||||
const key = normalizePath(worktreePath);
|
||||
// Clear previous toast tracking for this key so a new detection triggers a fresh toast
|
||||
toastShownForRef.current.delete(key);
|
||||
setRunningDevServers((prev) => {
|
||||
const next = new Map(prev);
|
||||
next.set(key, {
|
||||
worktreePath,
|
||||
port,
|
||||
url,
|
||||
urlDetected: false,
|
||||
});
|
||||
return next;
|
||||
});
|
||||
// Start port detection timeout for the new server
|
||||
startPortDetectionTimer(key);
|
||||
}
|
||||
});
|
||||
|
||||
return unsubscribe;
|
||||
}, [clearPortDetectionTimer, startPortDetectionTimer]);
|
||||
|
||||
// Cleanup all port detection timers on unmount
|
||||
useEffect(() => {
|
||||
return () => {
|
||||
for (const timer of portDetectionTimers.current.values()) {
|
||||
clearTimeout(timer);
|
||||
}
|
||||
portDetectionTimers.current.clear();
|
||||
};
|
||||
}, []);
|
||||
|
||||
const getWorktreeKey = useCallback(
|
||||
@@ -98,9 +441,12 @@ export function useDevServers({ projectPath }: UseDevServersOptions) {
|
||||
const result = await api.worktree.startDevServer(projectPath, targetPath);
|
||||
|
||||
if (result.success && result.result) {
|
||||
const key = normalizePath(targetPath);
|
||||
// Clear toast tracking so the new port detection shows a fresh toast
|
||||
toastShownForRef.current.delete(key);
|
||||
setRunningDevServers((prev) => {
|
||||
const next = new Map(prev);
|
||||
next.set(normalizePath(targetPath), {
|
||||
next.set(key, {
|
||||
worktreePath: result.result!.worktreePath,
|
||||
port: result.result!.port,
|
||||
url: result.result!.url,
|
||||
@@ -108,18 +454,26 @@ export function useDevServers({ projectPath }: UseDevServersOptions) {
|
||||
});
|
||||
return next;
|
||||
});
|
||||
toast.success('Dev server started, detecting port...');
|
||||
// Start port detection timeout
|
||||
startPortDetectionTimer(key);
|
||||
toast.success('Dev server started, detecting port...', {
|
||||
description: 'Logs are now visible in the dev server panel.',
|
||||
});
|
||||
} else {
|
||||
toast.error(result.error || 'Failed to start dev server');
|
||||
toast.error(result.error || 'Failed to start dev server', {
|
||||
description: 'Check the dev server logs panel for details.',
|
||||
});
|
||||
}
|
||||
} catch (error) {
|
||||
logger.error('Start dev server failed:', error);
|
||||
toast.error('Failed to start dev server');
|
||||
toast.error('Failed to start dev server', {
|
||||
description: error instanceof Error ? error.message : undefined,
|
||||
});
|
||||
} finally {
|
||||
setIsStartingDevServer(false);
|
||||
}
|
||||
},
|
||||
[isStartingDevServer, projectPath]
|
||||
[isStartingDevServer, projectPath, startPortDetectionTimer]
|
||||
);
|
||||
|
||||
const handleStopDevServer = useCallback(
|
||||
@@ -135,11 +489,16 @@ export function useDevServers({ projectPath }: UseDevServersOptions) {
|
||||
const result = await api.worktree.stopDevServer(targetPath);
|
||||
|
||||
if (result.success) {
|
||||
const key = normalizePath(targetPath);
|
||||
// Clear port detection timeout
|
||||
clearPortDetectionTimer(key);
|
||||
setRunningDevServers((prev) => {
|
||||
const next = new Map(prev);
|
||||
next.delete(normalizePath(targetPath));
|
||||
next.delete(key);
|
||||
return next;
|
||||
});
|
||||
// Clear toast tracking so future restarts get a fresh toast
|
||||
toastShownForRef.current.delete(key);
|
||||
toast.success(result.result?.message || 'Dev server stopped');
|
||||
} else {
|
||||
toast.error(result.error || 'Failed to stop dev server');
|
||||
@@ -149,7 +508,7 @@ export function useDevServers({ projectPath }: UseDevServersOptions) {
|
||||
toast.error('Failed to stop dev server');
|
||||
}
|
||||
},
|
||||
[projectPath]
|
||||
[projectPath, clearPortDetectionTimer]
|
||||
);
|
||||
|
||||
const handleOpenDevServerUrl = useCallback(
|
||||
@@ -163,30 +522,16 @@ export function useDevServers({ projectPath }: UseDevServersOptions) {
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
// Rewrite URL hostname to match the current browser's hostname.
|
||||
// This ensures dev server URLs work when accessing Automaker from
|
||||
// remote machines (e.g., 192.168.x.x or hostname.local instead of localhost).
|
||||
const devServerUrl = new URL(serverInfo.url);
|
||||
|
||||
// Security: Only allow http/https protocols to prevent potential attacks
|
||||
// via data:, javascript:, file:, or other dangerous URL schemes
|
||||
if (devServerUrl.protocol !== 'http:' && devServerUrl.protocol !== 'https:') {
|
||||
logger.error('Invalid dev server URL protocol:', devServerUrl.protocol);
|
||||
toast.error('Invalid dev server URL', {
|
||||
description: 'The server returned an unsupported URL protocol.',
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
devServerUrl.hostname = window.location.hostname;
|
||||
window.open(devServerUrl.toString(), '_blank', 'noopener,noreferrer');
|
||||
} catch (error) {
|
||||
logger.error('Failed to parse dev server URL:', error);
|
||||
toast.error('Failed to open dev server', {
|
||||
description: 'The server URL could not be processed. Please try again.',
|
||||
const browserUrl = buildDevServerBrowserUrl(serverInfo.url);
|
||||
if (!browserUrl) {
|
||||
logger.error('Invalid dev server URL:', serverInfo.url);
|
||||
toast.error('Invalid dev server URL', {
|
||||
description: 'The server returned an unsupported URL protocol.',
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
window.open(browserUrl, '_blank', 'noopener,noreferrer');
|
||||
},
|
||||
[runningDevServers, getWorktreeKey]
|
||||
);
|
||||
|
||||
@@ -8,6 +8,8 @@ import {
|
||||
useSwitchBranch,
|
||||
usePullWorktree,
|
||||
usePushWorktree,
|
||||
useSyncWorktree,
|
||||
useSetTracking,
|
||||
useOpenInEditor,
|
||||
} from '@/hooks/mutations';
|
||||
import type { WorktreeInfo } from '../types';
|
||||
@@ -51,6 +53,8 @@ export function useWorktreeActions(options?: UseWorktreeActionsOptions) {
|
||||
});
|
||||
const pullMutation = usePullWorktree();
|
||||
const pushMutation = usePushWorktree();
|
||||
const syncMutation = useSyncWorktree();
|
||||
const setTrackingMutation = useSetTracking();
|
||||
const openInEditorMutation = useOpenInEditor();
|
||||
|
||||
/**
|
||||
@@ -150,6 +154,28 @@ export function useWorktreeActions(options?: UseWorktreeActionsOptions) {
|
||||
[pushMutation]
|
||||
);
|
||||
|
||||
const handleSync = useCallback(
|
||||
async (worktree: WorktreeInfo, remote?: string) => {
|
||||
if (syncMutation.isPending) return;
|
||||
syncMutation.mutate({
|
||||
worktreePath: worktree.path,
|
||||
remote,
|
||||
});
|
||||
},
|
||||
[syncMutation]
|
||||
);
|
||||
|
||||
const handleSetTracking = useCallback(
|
||||
async (worktree: WorktreeInfo, remote: string) => {
|
||||
if (setTrackingMutation.isPending) return;
|
||||
setTrackingMutation.mutate({
|
||||
worktreePath: worktree.path,
|
||||
remote,
|
||||
});
|
||||
},
|
||||
[setTrackingMutation]
|
||||
);
|
||||
|
||||
const handleOpenInIntegratedTerminal = useCallback(
|
||||
(worktree: WorktreeInfo, mode?: 'tab' | 'split') => {
|
||||
// Navigate to the terminal view with the worktree path and branch name
|
||||
@@ -163,6 +189,24 @@ export function useWorktreeActions(options?: UseWorktreeActionsOptions) {
|
||||
[navigate]
|
||||
);
|
||||
|
||||
const handleRunTerminalScript = useCallback(
|
||||
(worktree: WorktreeInfo, command: string) => {
|
||||
// Navigate to the terminal view with the worktree path, branch, and command to run
|
||||
// The terminal view will create a new terminal and automatically execute the command
|
||||
navigate({
|
||||
to: '/terminal',
|
||||
search: {
|
||||
cwd: worktree.path,
|
||||
branch: worktree.branch,
|
||||
mode: 'tab' as const,
|
||||
nonce: Date.now(),
|
||||
command,
|
||||
},
|
||||
});
|
||||
},
|
||||
[navigate]
|
||||
);
|
||||
|
||||
const handleOpenInEditor = useCallback(
|
||||
async (worktree: WorktreeInfo, editorCommand?: string) => {
|
||||
openInEditorMutation.mutate({
|
||||
@@ -197,13 +241,17 @@ export function useWorktreeActions(options?: UseWorktreeActionsOptions) {
|
||||
return {
|
||||
isPulling: pullMutation.isPending,
|
||||
isPushing: pushMutation.isPending,
|
||||
isSyncing: syncMutation.isPending,
|
||||
isSwitching: switchBranchMutation.isPending,
|
||||
isActivating,
|
||||
setIsActivating,
|
||||
handleSwitchBranch,
|
||||
handlePull,
|
||||
handlePush,
|
||||
handleSync,
|
||||
handleSetTracking,
|
||||
handleOpenInIntegratedTerminal,
|
||||
handleRunTerminalScript,
|
||||
handleOpenInEditor,
|
||||
handleOpenInExternalTerminal,
|
||||
// Stash confirmation state for branch switching
|
||||
|
||||
@@ -28,10 +28,21 @@ export function useWorktrees({
|
||||
const { data, isLoading, refetch } = useWorktreesQuery(projectPath);
|
||||
const worktrees = (data?.worktrees ?? []) as WorktreeInfo[];
|
||||
|
||||
// Sync worktrees to Zustand store when they change
|
||||
// Sync worktrees to Zustand store when they change.
|
||||
// Use a ref to track the previous worktrees and skip the store update when the
|
||||
// data hasn't structurally changed. Without this check, every React Query refetch
|
||||
// (triggered by WebSocket event invalidations) would update the store even when
|
||||
// the worktree list is identical, causing a cascade of re-renders in BoardView →
|
||||
// selectedWorktree → useAutoMode → refreshStatus that can trigger React error #185.
|
||||
const prevWorktreesJsonRef = useRef<string>('');
|
||||
useEffect(() => {
|
||||
if (worktrees.length > 0) {
|
||||
setWorktreesInStore(projectPath, worktrees);
|
||||
// Compare serialized worktrees to skip no-op store updates
|
||||
const json = JSON.stringify(worktrees);
|
||||
if (json !== prevWorktreesJsonRef.current) {
|
||||
prevWorktreesJsonRef.current = json;
|
||||
setWorktreesInStore(projectPath, worktrees);
|
||||
}
|
||||
}
|
||||
}, [worktrees, projectPath, setWorktreesInStore]);
|
||||
|
||||
@@ -87,11 +98,32 @@ export function useWorktrees({
|
||||
}
|
||||
}, [worktrees, projectPath, setCurrentWorktree]);
|
||||
|
||||
const currentWorktreePath = currentWorktree?.path ?? null;
|
||||
|
||||
const handleSelectWorktree = useCallback(
|
||||
(worktree: WorktreeInfo) => {
|
||||
// Skip invalidation when re-selecting the already-active worktree
|
||||
const isSameWorktree = worktree.isMain
|
||||
? currentWorktreePath === null
|
||||
: pathsEqual(worktree.path, currentWorktreePath ?? '');
|
||||
|
||||
if (isSameWorktree) return;
|
||||
|
||||
setCurrentWorktree(projectPath, worktree.isMain ? null : worktree.path, worktree.branch);
|
||||
|
||||
// Defer feature query invalidation so the store update and client-side
|
||||
// re-filtering happen in the current render cycle first. The features
|
||||
// list is the same regardless of worktree (filtering is client-side),
|
||||
// so the board updates instantly. The deferred invalidation ensures
|
||||
// feature card details (planSpec, todo lists) are refreshed in the
|
||||
// background without blocking the worktree switch.
|
||||
setTimeout(() => {
|
||||
queryClient.invalidateQueries({
|
||||
queryKey: queryKeys.features.all(projectPath),
|
||||
});
|
||||
}, 0);
|
||||
},
|
||||
[projectPath, setCurrentWorktree]
|
||||
[projectPath, setCurrentWorktree, queryClient, currentWorktreePath]
|
||||
);
|
||||
|
||||
// fetchWorktrees for backward compatibility - now just triggers a refetch
|
||||
@@ -110,7 +142,6 @@ export function useWorktrees({
|
||||
[projectPath, queryClient, refetch]
|
||||
);
|
||||
|
||||
const currentWorktreePath = currentWorktree?.path ?? null;
|
||||
const selectedWorktree = currentWorktreePath
|
||||
? worktrees.find((w) => pathsEqual(w.path, currentWorktreePath))
|
||||
: worktrees.find((w) => w.isMain);
|
||||
|
||||
@@ -122,6 +122,7 @@ export interface WorktreePanelProps {
|
||||
onCreatePR: (worktree: WorktreeInfo) => void;
|
||||
onCreateBranch: (worktree: WorktreeInfo) => void;
|
||||
onAddressPRComments: (worktree: WorktreeInfo, prInfo: PRInfo) => void;
|
||||
onAutoAddressPRComments: (worktree: WorktreeInfo, prInfo: PRInfo) => void;
|
||||
onResolveConflicts: (worktree: WorktreeInfo) => void;
|
||||
onCreateMergeConflictResolutionFeature?: (conflictInfo: MergeConflictInfo) => void;
|
||||
/** Called when branch switch stash reapply results in merge conflicts */
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import { useEffect, useRef, useCallback, useState } from 'react';
|
||||
import { useEffect, useRef, useCallback, useState, useMemo } from 'react';
|
||||
import { useNavigate } from '@tanstack/react-router';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { GitBranch, Plus, RefreshCw } from 'lucide-react';
|
||||
import { Spinner } from '@/components/ui/spinner';
|
||||
@@ -9,6 +10,7 @@ import { useIsMobile } from '@/hooks/use-media-query';
|
||||
import { useWorktreeInitScript, useProjectSettings } from '@/hooks/queries';
|
||||
import { useTestRunnerEvents } from '@/hooks/use-test-runners';
|
||||
import { useTestRunnersStore } from '@/store/test-runners-store';
|
||||
import { DEFAULT_TERMINAL_SCRIPTS } from '@/components/views/project-settings-view/terminal-scripts-constants';
|
||||
import type {
|
||||
TestRunnerStartedEvent,
|
||||
TestRunnerOutputEvent,
|
||||
@@ -59,6 +61,7 @@ export function WorktreePanel({
|
||||
onCreatePR,
|
||||
onCreateBranch,
|
||||
onAddressPRComments,
|
||||
onAutoAddressPRComments,
|
||||
onResolveConflicts,
|
||||
onCreateMergeConflictResolutionFeature,
|
||||
onBranchSwitchConflict,
|
||||
@@ -110,12 +113,16 @@ export function WorktreePanel({
|
||||
const {
|
||||
isPulling,
|
||||
isPushing,
|
||||
isSyncing,
|
||||
isSwitching,
|
||||
isActivating,
|
||||
handleSwitchBranch,
|
||||
handlePull: _handlePull,
|
||||
handlePush,
|
||||
handleSync,
|
||||
handleSetTracking,
|
||||
handleOpenInIntegratedTerminal,
|
||||
handleRunTerminalScript,
|
||||
handleOpenInEditor,
|
||||
handleOpenInExternalTerminal,
|
||||
pendingSwitch,
|
||||
@@ -209,6 +216,21 @@ export function WorktreePanel({
|
||||
const { data: projectSettings } = useProjectSettings(projectPath);
|
||||
const hasTestCommand = !!projectSettings?.testCommand;
|
||||
|
||||
// Get terminal quick scripts from project settings (or fall back to defaults)
|
||||
const terminalScripts = useMemo(() => {
|
||||
const configured = projectSettings?.terminalScripts;
|
||||
if (configured && configured.length > 0) {
|
||||
return configured;
|
||||
}
|
||||
return DEFAULT_TERMINAL_SCRIPTS;
|
||||
}, [projectSettings?.terminalScripts]);
|
||||
|
||||
// Navigate to project settings to edit scripts
|
||||
const navigate = useNavigate();
|
||||
const handleEditScripts = useCallback(() => {
|
||||
navigate({ to: '/project-settings', search: { section: 'commands-scripts' } });
|
||||
}, [navigate]);
|
||||
|
||||
// Test runner state management
|
||||
// Use the test runners store to get global state for all worktrees
|
||||
const testRunnersStore = useTestRunnersStore();
|
||||
@@ -640,6 +662,18 @@ export function WorktreePanel({
|
||||
// Keep logPanelWorktree set for smooth close animation
|
||||
}, []);
|
||||
|
||||
// Wrap handleStartDevServer to auto-open the logs panel so the user
|
||||
// can see output immediately (including failure reasons)
|
||||
const handleStartDevServerAndShowLogs = useCallback(
|
||||
async (worktree: WorktreeInfo) => {
|
||||
// Open logs panel immediately so output is visible from the start
|
||||
setLogPanelWorktree(worktree);
|
||||
setLogPanelOpen(true);
|
||||
await handleStartDevServer(worktree);
|
||||
},
|
||||
[handleStartDevServer]
|
||||
);
|
||||
|
||||
// Handle opening the push to remote dialog
|
||||
const handlePushNewBranch = useCallback((worktree: WorktreeInfo) => {
|
||||
setPushToRemoteWorktree(worktree);
|
||||
@@ -797,6 +831,30 @@ export function WorktreePanel({
|
||||
[handlePush, fetchBranches, fetchWorktrees]
|
||||
);
|
||||
|
||||
// Handle sync (pull + push) with optional remote selection
|
||||
const handleSyncWithRemoteSelection = useCallback(
|
||||
(worktree: WorktreeInfo) => {
|
||||
handleSync(worktree);
|
||||
},
|
||||
[handleSync]
|
||||
);
|
||||
|
||||
// Handle sync with a specific remote selected from the submenu
|
||||
const handleSyncWithSpecificRemote = useCallback(
|
||||
(worktree: WorktreeInfo, remote: string) => {
|
||||
handleSync(worktree, remote);
|
||||
},
|
||||
[handleSync]
|
||||
);
|
||||
|
||||
// Handle set tracking branch for a specific remote
|
||||
const handleSetTrackingForRemote = useCallback(
|
||||
(worktree: WorktreeInfo, remote: string) => {
|
||||
handleSetTracking(worktree, remote);
|
||||
},
|
||||
[handleSetTracking]
|
||||
);
|
||||
|
||||
// Handle confirming the push to remote dialog
|
||||
const handleConfirmPushToRemote = useCallback(
|
||||
async (worktree: WorktreeInfo, remote: string) => {
|
||||
@@ -905,6 +963,10 @@ export function WorktreePanel({
|
||||
onPushNewBranch={handlePushNewBranch}
|
||||
onPullWithRemote={handlePullWithSpecificRemote}
|
||||
onPushWithRemote={handlePushWithSpecificRemote}
|
||||
isSyncing={isSyncing}
|
||||
onSync={handleSyncWithRemoteSelection}
|
||||
onSyncWithRemote={handleSyncWithSpecificRemote}
|
||||
onSetTracking={handleSetTrackingForRemote}
|
||||
onOpenInEditor={handleOpenInEditor}
|
||||
onOpenInIntegratedTerminal={handleOpenInIntegratedTerminal}
|
||||
onOpenInExternalTerminal={handleOpenInExternalTerminal}
|
||||
@@ -914,10 +976,11 @@ export function WorktreePanel({
|
||||
onCommit={onCommit}
|
||||
onCreatePR={onCreatePR}
|
||||
onAddressPRComments={onAddressPRComments}
|
||||
onAutoAddressPRComments={onAutoAddressPRComments}
|
||||
onResolveConflicts={onResolveConflicts}
|
||||
onMerge={handleMerge}
|
||||
onDeleteWorktree={onDeleteWorktree}
|
||||
onStartDevServer={handleStartDevServer}
|
||||
onStartDevServer={handleStartDevServerAndShowLogs}
|
||||
onStopDevServer={handleStopDevServer}
|
||||
onOpenDevServerUrl={handleOpenDevServerUrl}
|
||||
onViewDevServerLogs={handleViewDevServerLogs}
|
||||
@@ -932,6 +995,9 @@ export function WorktreePanel({
|
||||
onAbortOperation={handleAbortOperation}
|
||||
onContinueOperation={handleContinueOperation}
|
||||
hasInitScript={hasInitScript}
|
||||
terminalScripts={terminalScripts}
|
||||
onRunTerminalScript={handleRunTerminalScript}
|
||||
onEditScripts={handleEditScripts}
|
||||
/>
|
||||
)}
|
||||
|
||||
@@ -1144,6 +1210,10 @@ export function WorktreePanel({
|
||||
onPushNewBranch={handlePushNewBranch}
|
||||
onPullWithRemote={handlePullWithSpecificRemote}
|
||||
onPushWithRemote={handlePushWithSpecificRemote}
|
||||
isSyncing={isSyncing}
|
||||
onSync={handleSyncWithRemoteSelection}
|
||||
onSyncWithRemote={handleSyncWithSpecificRemote}
|
||||
onSetTracking={handleSetTrackingForRemote}
|
||||
remotesCache={remotesCache}
|
||||
onOpenInEditor={handleOpenInEditor}
|
||||
onOpenInIntegratedTerminal={handleOpenInIntegratedTerminal}
|
||||
@@ -1154,10 +1224,11 @@ export function WorktreePanel({
|
||||
onCommit={onCommit}
|
||||
onCreatePR={onCreatePR}
|
||||
onAddressPRComments={onAddressPRComments}
|
||||
onAutoAddressPRComments={onAutoAddressPRComments}
|
||||
onResolveConflicts={onResolveConflicts}
|
||||
onMerge={handleMerge}
|
||||
onDeleteWorktree={onDeleteWorktree}
|
||||
onStartDevServer={handleStartDevServer}
|
||||
onStartDevServer={handleStartDevServerAndShowLogs}
|
||||
onStopDevServer={handleStopDevServer}
|
||||
onOpenDevServerUrl={handleOpenDevServerUrl}
|
||||
onViewDevServerLogs={handleViewDevServerLogs}
|
||||
@@ -1171,6 +1242,9 @@ export function WorktreePanel({
|
||||
onCherryPick={handleCherryPick}
|
||||
onAbortOperation={handleAbortOperation}
|
||||
onContinueOperation={handleContinueOperation}
|
||||
terminalScripts={terminalScripts}
|
||||
onRunTerminalScript={handleRunTerminalScript}
|
||||
onEditScripts={handleEditScripts}
|
||||
/>
|
||||
|
||||
{useWorktreesEnabled && (
|
||||
@@ -1247,6 +1321,10 @@ export function WorktreePanel({
|
||||
onPushNewBranch={handlePushNewBranch}
|
||||
onPullWithRemote={handlePullWithSpecificRemote}
|
||||
onPushWithRemote={handlePushWithSpecificRemote}
|
||||
isSyncing={isSyncing}
|
||||
onSync={handleSyncWithRemoteSelection}
|
||||
onSyncWithRemote={handleSyncWithSpecificRemote}
|
||||
onSetTracking={handleSetTrackingForRemote}
|
||||
remotes={remotesCache[mainWorktree.path]}
|
||||
onOpenInEditor={handleOpenInEditor}
|
||||
onOpenInIntegratedTerminal={handleOpenInIntegratedTerminal}
|
||||
@@ -1257,10 +1335,11 @@ export function WorktreePanel({
|
||||
onCommit={onCommit}
|
||||
onCreatePR={onCreatePR}
|
||||
onAddressPRComments={onAddressPRComments}
|
||||
onAutoAddressPRComments={onAutoAddressPRComments}
|
||||
onResolveConflicts={onResolveConflicts}
|
||||
onMerge={handleMerge}
|
||||
onDeleteWorktree={onDeleteWorktree}
|
||||
onStartDevServer={handleStartDevServer}
|
||||
onStartDevServer={handleStartDevServerAndShowLogs}
|
||||
onStopDevServer={handleStopDevServer}
|
||||
onOpenDevServerUrl={handleOpenDevServerUrl}
|
||||
onViewDevServerLogs={handleViewDevServerLogs}
|
||||
@@ -1276,6 +1355,9 @@ export function WorktreePanel({
|
||||
onContinueOperation={handleContinueOperation}
|
||||
hasInitScript={hasInitScript}
|
||||
hasTestCommand={hasTestCommand}
|
||||
terminalScripts={terminalScripts}
|
||||
onRunTerminalScript={handleRunTerminalScript}
|
||||
onEditScripts={handleEditScripts}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
@@ -1330,6 +1412,10 @@ export function WorktreePanel({
|
||||
onPushNewBranch={handlePushNewBranch}
|
||||
onPullWithRemote={handlePullWithSpecificRemote}
|
||||
onPushWithRemote={handlePushWithSpecificRemote}
|
||||
isSyncing={isSyncing}
|
||||
onSync={handleSyncWithRemoteSelection}
|
||||
onSyncWithRemote={handleSyncWithSpecificRemote}
|
||||
onSetTracking={handleSetTrackingForRemote}
|
||||
remotes={remotesCache[worktree.path]}
|
||||
onOpenInEditor={handleOpenInEditor}
|
||||
onOpenInIntegratedTerminal={handleOpenInIntegratedTerminal}
|
||||
@@ -1340,10 +1426,11 @@ export function WorktreePanel({
|
||||
onCommit={onCommit}
|
||||
onCreatePR={onCreatePR}
|
||||
onAddressPRComments={onAddressPRComments}
|
||||
onAutoAddressPRComments={onAutoAddressPRComments}
|
||||
onResolveConflicts={onResolveConflicts}
|
||||
onMerge={handleMerge}
|
||||
onDeleteWorktree={onDeleteWorktree}
|
||||
onStartDevServer={handleStartDevServer}
|
||||
onStartDevServer={handleStartDevServerAndShowLogs}
|
||||
onStopDevServer={handleStopDevServer}
|
||||
onOpenDevServerUrl={handleOpenDevServerUrl}
|
||||
onViewDevServerLogs={handleViewDevServerLogs}
|
||||
@@ -1359,6 +1446,9 @@ export function WorktreePanel({
|
||||
onContinueOperation={handleContinueOperation}
|
||||
hasInitScript={hasInitScript}
|
||||
hasTestCommand={hasTestCommand}
|
||||
terminalScripts={terminalScripts}
|
||||
onRunTerminalScript={handleRunTerminalScript}
|
||||
onEditScripts={handleEditScripts}
|
||||
/>
|
||||
);
|
||||
})}
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { X, Circle, MoreHorizontal } from 'lucide-react';
|
||||
import { X, Circle, MoreHorizontal, Save } from 'lucide-react';
|
||||
import { cn } from '@/lib/utils';
|
||||
import type { EditorTab } from '../use-file-editor-store';
|
||||
import {
|
||||
@@ -14,6 +14,12 @@ interface EditorTabsProps {
|
||||
onTabSelect: (tabId: string) => void;
|
||||
onTabClose: (tabId: string) => void;
|
||||
onCloseAll: () => void;
|
||||
/** Called when the save button is clicked (mobile only) */
|
||||
onSave?: () => void;
|
||||
/** Whether there are unsaved changes (controls enabled state of save button) */
|
||||
isDirty?: boolean;
|
||||
/** Whether to show the save button in the tab bar (intended for mobile) */
|
||||
showSaveButton?: boolean;
|
||||
}
|
||||
|
||||
/** Get a file icon color based on extension */
|
||||
@@ -74,6 +80,9 @@ export function EditorTabs({
|
||||
onTabSelect,
|
||||
onTabClose,
|
||||
onCloseAll,
|
||||
onSave,
|
||||
isDirty,
|
||||
showSaveButton,
|
||||
}: EditorTabsProps) {
|
||||
if (tabs.length === 0) return null;
|
||||
|
||||
@@ -128,8 +137,26 @@ export function EditorTabs({
|
||||
);
|
||||
})}
|
||||
|
||||
{/* Tab actions dropdown (close all, etc.) */}
|
||||
<div className="ml-auto shrink-0 flex items-center px-1">
|
||||
{/* Tab actions: save button (mobile) + close-all dropdown */}
|
||||
<div className="ml-auto shrink-0 flex items-center px-1 gap-0.5">
|
||||
{/* Save button — shown in the tab bar on mobile */}
|
||||
{showSaveButton && onSave && (
|
||||
<button
|
||||
onClick={onSave}
|
||||
disabled={!isDirty}
|
||||
className={cn(
|
||||
'p-1 rounded transition-colors',
|
||||
isDirty
|
||||
? 'text-primary hover:text-primary hover:bg-muted/50'
|
||||
: 'text-muted-foreground/40 cursor-not-allowed'
|
||||
)}
|
||||
title="Save file (Ctrl+S)"
|
||||
aria-label="Save file"
|
||||
>
|
||||
<Save className="w-4 h-4" />
|
||||
</button>
|
||||
)}
|
||||
|
||||
<DropdownMenu>
|
||||
<DropdownMenuTrigger asChild>
|
||||
<button
|
||||
|
||||
@@ -32,6 +32,7 @@ import {
|
||||
DropdownMenuTrigger,
|
||||
} from '@/components/ui/dropdown-menu';
|
||||
import { useFileEditorStore, type FileTreeNode } from '../use-file-editor-store';
|
||||
import { useFileBrowser } from '@/contexts/file-browser-context';
|
||||
|
||||
interface FileTreeProps {
|
||||
onFileSelect: (path: string) => void;
|
||||
@@ -104,6 +105,21 @@ function getGitStatusLabel(status: string | undefined): string {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Validate a file/folder name for safety.
|
||||
* Rejects names containing path separators, relative path components,
|
||||
* or names that are just dots (which resolve to parent/current directory).
|
||||
*/
|
||||
function isValidFileName(name: string): boolean {
|
||||
// Reject names containing path separators
|
||||
if (name.includes('/') || name.includes('\\')) return false;
|
||||
// Reject current/parent directory references
|
||||
if (name === '.' || name === '..') return false;
|
||||
// Reject empty or whitespace-only names
|
||||
if (!name.trim()) return false;
|
||||
return true;
|
||||
}
|
||||
|
||||
/** Inline input for creating/renaming items */
|
||||
function InlineInput({
|
||||
defaultValue,
|
||||
@@ -117,6 +133,7 @@ function InlineInput({
|
||||
placeholder?: string;
|
||||
}) {
|
||||
const [value, setValue] = useState(defaultValue || '');
|
||||
const [errorMessage, setErrorMessage] = useState<string | null>(null);
|
||||
const inputRef = useRef<HTMLInputElement>(null);
|
||||
// Guard against double-submission: pressing Enter triggers onKeyDown AND may
|
||||
// immediately trigger onBlur (e.g. when the component unmounts after submit).
|
||||
@@ -125,7 +142,9 @@ function InlineInput({
|
||||
useEffect(() => {
|
||||
inputRef.current?.focus();
|
||||
if (defaultValue) {
|
||||
// Select name without extension for rename
|
||||
// Select name without extension for rename.
|
||||
// For dotfiles (e.g. ".gitignore"), lastIndexOf('.') returns 0,
|
||||
// so we fall through to select() which selects the entire name.
|
||||
const dotIndex = defaultValue.lastIndexOf('.');
|
||||
if (dotIndex > 0) {
|
||||
inputRef.current?.setSelectionRange(0, dotIndex);
|
||||
@@ -135,97 +154,62 @@ function InlineInput({
|
||||
}
|
||||
}, [defaultValue]);
|
||||
|
||||
const handleSubmit = useCallback(() => {
|
||||
if (submittedRef.current) return;
|
||||
const trimmed = value.trim();
|
||||
if (!trimmed) {
|
||||
onCancel();
|
||||
return;
|
||||
}
|
||||
if (!isValidFileName(trimmed)) {
|
||||
// Invalid name — surface error, keep editing so the user can fix it
|
||||
setErrorMessage('Invalid name: avoid /, \\, ".", or ".."');
|
||||
inputRef.current?.focus();
|
||||
return;
|
||||
}
|
||||
setErrorMessage(null);
|
||||
submittedRef.current = true;
|
||||
onSubmit(trimmed);
|
||||
}, [value, onSubmit, onCancel]);
|
||||
|
||||
return (
|
||||
<input
|
||||
ref={inputRef}
|
||||
value={value}
|
||||
onChange={(e) => setValue(e.target.value)}
|
||||
onKeyDown={(e) => {
|
||||
if (e.key === 'Enter' && value.trim()) {
|
||||
<div className="flex flex-col gap-0.5">
|
||||
<input
|
||||
ref={inputRef}
|
||||
value={value}
|
||||
onChange={(e) => {
|
||||
setValue(e.target.value);
|
||||
if (errorMessage) setErrorMessage(null);
|
||||
}}
|
||||
onKeyDown={(e) => {
|
||||
if (e.key === 'Enter') {
|
||||
handleSubmit();
|
||||
} else if (e.key === 'Escape') {
|
||||
onCancel();
|
||||
}
|
||||
}}
|
||||
onBlur={() => {
|
||||
// Prevent duplicate submission if onKeyDown already triggered onSubmit
|
||||
if (submittedRef.current) return;
|
||||
submittedRef.current = true;
|
||||
onSubmit(value.trim());
|
||||
} else if (e.key === 'Escape') {
|
||||
onCancel();
|
||||
}
|
||||
}}
|
||||
onBlur={() => {
|
||||
// Prevent duplicate submission if onKeyDown already triggered onSubmit
|
||||
if (submittedRef.current) return;
|
||||
if (value.trim()) {
|
||||
submittedRef.current = true;
|
||||
onSubmit(value.trim());
|
||||
} else {
|
||||
onCancel();
|
||||
}
|
||||
}}
|
||||
placeholder={placeholder}
|
||||
className="text-sm bg-muted border border-border rounded px-1 py-0.5 w-full outline-none focus:border-primary"
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
/** Destination path picker dialog for copy/move operations */
|
||||
function DestinationPicker({
|
||||
onSubmit,
|
||||
onCancel,
|
||||
defaultPath,
|
||||
action,
|
||||
}: {
|
||||
onSubmit: (path: string) => void;
|
||||
onCancel: () => void;
|
||||
defaultPath: string;
|
||||
action: 'Copy' | 'Move';
|
||||
}) {
|
||||
const [path, setPath] = useState(defaultPath);
|
||||
const inputRef = useRef<HTMLInputElement>(null);
|
||||
|
||||
useEffect(() => {
|
||||
inputRef.current?.focus();
|
||||
inputRef.current?.select();
|
||||
}, []);
|
||||
|
||||
return (
|
||||
<div className="fixed inset-0 z-50 flex items-center justify-center bg-black/50 p-4">
|
||||
<div className="bg-background border border-border rounded-lg shadow-lg w-full max-w-md">
|
||||
<div className="px-4 py-3 border-b border-border">
|
||||
<h3 className="text-sm font-medium">{action} To...</h3>
|
||||
<p className="text-xs text-muted-foreground mt-0.5">
|
||||
Enter the destination path for the {action.toLowerCase()} operation
|
||||
</p>
|
||||
</div>
|
||||
<div className="px-4 py-3">
|
||||
<input
|
||||
ref={inputRef}
|
||||
value={path}
|
||||
onChange={(e) => setPath(e.target.value)}
|
||||
onKeyDown={(e) => {
|
||||
if (e.key === 'Enter' && path.trim()) {
|
||||
onSubmit(path.trim());
|
||||
} else if (e.key === 'Escape') {
|
||||
onCancel();
|
||||
}
|
||||
}}
|
||||
placeholder="Enter destination path..."
|
||||
className="w-full text-sm bg-muted border border-border rounded px-3 py-2 outline-none focus:border-primary font-mono"
|
||||
/>
|
||||
</div>
|
||||
<div className="flex items-center justify-end gap-2 px-4 py-3 border-t border-border">
|
||||
<button
|
||||
onClick={onCancel}
|
||||
className="px-3 py-1.5 text-sm rounded hover:bg-muted transition-colors"
|
||||
>
|
||||
Cancel
|
||||
</button>
|
||||
<button
|
||||
onClick={() => path.trim() && onSubmit(path.trim())}
|
||||
disabled={!path.trim()}
|
||||
className="px-3 py-1.5 text-sm rounded bg-primary text-primary-foreground hover:bg-primary/90 transition-colors disabled:opacity-50"
|
||||
>
|
||||
{action}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
const trimmed = value.trim();
|
||||
if (trimmed && isValidFileName(trimmed)) {
|
||||
submittedRef.current = true;
|
||||
onSubmit(trimmed);
|
||||
}
|
||||
// If the name is empty or invalid, do NOT call onCancel — keep the
|
||||
// input open so the user can correct the value (mirrors handleSubmit).
|
||||
// Optionally re-focus so the user can continue editing.
|
||||
else {
|
||||
inputRef.current?.focus();
|
||||
}
|
||||
}}
|
||||
placeholder={placeholder}
|
||||
className={cn(
|
||||
'text-sm bg-muted border rounded px-1 py-0.5 w-full outline-none focus:border-primary',
|
||||
errorMessage ? 'border-red-500' : 'border-border'
|
||||
)}
|
||||
/>
|
||||
{errorMessage && <span className="text-[10px] text-red-500 px-0.5">{errorMessage}</span>}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -276,12 +260,11 @@ function TreeNode({
|
||||
selectedPaths,
|
||||
toggleSelectedPath,
|
||||
} = useFileEditorStore();
|
||||
const { openFileBrowser } = useFileBrowser();
|
||||
const [isCreatingFile, setIsCreatingFile] = useState(false);
|
||||
const [isCreatingFolder, setIsCreatingFolder] = useState(false);
|
||||
const [isRenaming, setIsRenaming] = useState(false);
|
||||
const [menuOpen, setMenuOpen] = useState(false);
|
||||
const [showCopyPicker, setShowCopyPicker] = useState(false);
|
||||
const [showMovePicker, setShowMovePicker] = useState(false);
|
||||
|
||||
const isExpanded = expandedFolders.has(node.path);
|
||||
const isActive = activeFilePath === node.path;
|
||||
@@ -409,30 +392,6 @@ function TreeNode({
|
||||
|
||||
return (
|
||||
<div key={node.path}>
|
||||
{/* Destination picker dialogs */}
|
||||
{showCopyPicker && onCopyItem && (
|
||||
<DestinationPicker
|
||||
action="Copy"
|
||||
defaultPath={node.path}
|
||||
onSubmit={async (destPath) => {
|
||||
setShowCopyPicker(false);
|
||||
await onCopyItem(node.path, destPath);
|
||||
}}
|
||||
onCancel={() => setShowCopyPicker(false)}
|
||||
/>
|
||||
)}
|
||||
{showMovePicker && onMoveItem && (
|
||||
<DestinationPicker
|
||||
action="Move"
|
||||
defaultPath={node.path}
|
||||
onSubmit={async (destPath) => {
|
||||
setShowMovePicker(false);
|
||||
await onMoveItem(node.path, destPath);
|
||||
}}
|
||||
onCancel={() => setShowMovePicker(false)}
|
||||
/>
|
||||
)}
|
||||
|
||||
{isRenaming ? (
|
||||
<div style={{ paddingLeft: `${depth * 16 + 8}px` }} className="py-0.5 px-2">
|
||||
<InlineInput
|
||||
@@ -630,9 +589,21 @@ function TreeNode({
|
||||
{/* Copy To... */}
|
||||
{onCopyItem && (
|
||||
<DropdownMenuItem
|
||||
onClick={(e) => {
|
||||
onClick={async (e) => {
|
||||
e.stopPropagation();
|
||||
setShowCopyPicker(true);
|
||||
try {
|
||||
const parentPath = node.path.substring(0, node.path.lastIndexOf('/')) || '/';
|
||||
const destPath = await openFileBrowser({
|
||||
title: `Copy "${node.name}" To...`,
|
||||
description: 'Select the destination folder for the copy operation',
|
||||
initialPath: parentPath,
|
||||
});
|
||||
if (destPath) {
|
||||
await onCopyItem(node.path, destPath);
|
||||
}
|
||||
} catch (err) {
|
||||
console.error('Copy operation failed:', err);
|
||||
}
|
||||
}}
|
||||
className="gap-2"
|
||||
>
|
||||
@@ -644,9 +615,21 @@ function TreeNode({
|
||||
{/* Move To... */}
|
||||
{onMoveItem && (
|
||||
<DropdownMenuItem
|
||||
onClick={(e) => {
|
||||
onClick={async (e) => {
|
||||
e.stopPropagation();
|
||||
setShowMovePicker(true);
|
||||
try {
|
||||
const parentPath = node.path.substring(0, node.path.lastIndexOf('/')) || '/';
|
||||
const destPath = await openFileBrowser({
|
||||
title: `Move "${node.name}" To...`,
|
||||
description: 'Select the destination folder for the move operation',
|
||||
initialPath: parentPath,
|
||||
});
|
||||
if (destPath) {
|
||||
await onMoveItem(node.path, destPath);
|
||||
}
|
||||
} catch (err) {
|
||||
console.error('Move operation failed:', err);
|
||||
}
|
||||
}}
|
||||
className="gap-2"
|
||||
>
|
||||
@@ -775,8 +758,15 @@ export function FileTree({
|
||||
onDragDropMove,
|
||||
effectivePath,
|
||||
}: FileTreeProps) {
|
||||
const { fileTree, showHiddenFiles, setShowHiddenFiles, gitStatusMap, setDragState, gitBranch } =
|
||||
useFileEditorStore();
|
||||
const {
|
||||
fileTree,
|
||||
showHiddenFiles,
|
||||
setShowHiddenFiles,
|
||||
gitStatusMap,
|
||||
dragState,
|
||||
setDragState,
|
||||
gitBranch,
|
||||
} = useFileEditorStore();
|
||||
const [isCreatingFile, setIsCreatingFile] = useState(false);
|
||||
const [isCreatingFolder, setIsCreatingFolder] = useState(false);
|
||||
|
||||
@@ -791,10 +781,13 @@ export function FileTree({
|
||||
e.preventDefault();
|
||||
if (effectivePath) {
|
||||
e.dataTransfer.dropEffect = 'move';
|
||||
setDragState({ draggedPaths: [], dropTargetPath: effectivePath });
|
||||
// Skip redundant state update if already targeting the same path
|
||||
if (dragState.dropTargetPath !== effectivePath) {
|
||||
setDragState({ ...dragState, dropTargetPath: effectivePath });
|
||||
}
|
||||
}
|
||||
},
|
||||
[effectivePath, setDragState]
|
||||
[effectivePath, dragState, setDragState]
|
||||
);
|
||||
|
||||
const handleRootDrop = useCallback(
|
||||
@@ -818,47 +811,54 @@ export function FileTree({
|
||||
return (
|
||||
<div className="flex flex-col h-full" data-testid="file-tree">
|
||||
{/* Tree toolbar */}
|
||||
<div className="flex items-center justify-between px-2 py-1.5 border-b border-border">
|
||||
<div className="flex items-center gap-1.5">
|
||||
<span className="text-xs font-semibold uppercase tracking-wider text-muted-foreground">
|
||||
Explorer
|
||||
</span>
|
||||
{gitBranch && (
|
||||
<span className="text-[10px] text-primary font-medium px-1 py-0.5 bg-primary/10 rounded">
|
||||
<div className="px-2 py-1.5 border-b border-border">
|
||||
<div className="flex items-center justify-between">
|
||||
<div className="flex items-center gap-1.5 min-w-0">
|
||||
<span className="text-xs font-semibold uppercase tracking-wider text-muted-foreground">
|
||||
Explorer
|
||||
</span>
|
||||
</div>
|
||||
<div className="flex items-center gap-0.5">
|
||||
<button
|
||||
onClick={() => setIsCreatingFile(true)}
|
||||
className="p-1 hover:bg-accent rounded"
|
||||
title="New file"
|
||||
>
|
||||
<FilePlus className="w-3.5 h-3.5 text-muted-foreground" />
|
||||
</button>
|
||||
<button
|
||||
onClick={() => setIsCreatingFolder(true)}
|
||||
className="p-1 hover:bg-accent rounded"
|
||||
title="New folder"
|
||||
>
|
||||
<FolderPlus className="w-3.5 h-3.5 text-muted-foreground" />
|
||||
</button>
|
||||
<button
|
||||
onClick={() => setShowHiddenFiles(!showHiddenFiles)}
|
||||
className="p-1 hover:bg-accent rounded"
|
||||
title={showHiddenFiles ? 'Hide dotfiles' : 'Show dotfiles'}
|
||||
>
|
||||
{showHiddenFiles ? (
|
||||
<Eye className="w-3.5 h-3.5 text-muted-foreground" />
|
||||
) : (
|
||||
<EyeOff className="w-3.5 h-3.5 text-muted-foreground" />
|
||||
)}
|
||||
</button>
|
||||
<button onClick={onRefresh} className="p-1 hover:bg-accent rounded" title="Refresh">
|
||||
<RefreshCw className="w-3.5 h-3.5 text-muted-foreground" />
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
{gitBranch && (
|
||||
<div className="mt-1 min-w-0">
|
||||
<span
|
||||
className="inline-block max-w-full truncate whitespace-nowrap text-[10px] text-primary font-medium px-1 py-0.5 bg-primary/10 rounded"
|
||||
title={gitBranch}
|
||||
>
|
||||
{gitBranch}
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
<div className="flex items-center gap-0.5">
|
||||
<button
|
||||
onClick={() => setIsCreatingFile(true)}
|
||||
className="p-1 hover:bg-accent rounded"
|
||||
title="New file"
|
||||
>
|
||||
<FilePlus className="w-3.5 h-3.5 text-muted-foreground" />
|
||||
</button>
|
||||
<button
|
||||
onClick={() => setIsCreatingFolder(true)}
|
||||
className="p-1 hover:bg-accent rounded"
|
||||
title="New folder"
|
||||
>
|
||||
<FolderPlus className="w-3.5 h-3.5 text-muted-foreground" />
|
||||
</button>
|
||||
<button
|
||||
onClick={() => setShowHiddenFiles(!showHiddenFiles)}
|
||||
className="p-1 hover:bg-accent rounded"
|
||||
title={showHiddenFiles ? 'Hide dotfiles' : 'Show dotfiles'}
|
||||
>
|
||||
{showHiddenFiles ? (
|
||||
<Eye className="w-3.5 h-3.5 text-muted-foreground" />
|
||||
) : (
|
||||
<EyeOff className="w-3.5 h-3.5 text-muted-foreground" />
|
||||
)}
|
||||
</button>
|
||||
<button onClick={onRefresh} className="p-1 hover:bg-accent rounded" title="Refresh">
|
||||
<RefreshCw className="w-3.5 h-3.5 text-muted-foreground" />
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* Tree content */}
|
||||
|
||||
@@ -650,6 +650,12 @@ export function FileEditorView({ initialPath }: FileEditorViewProps) {
|
||||
|
||||
const handleRenameItem = useCallback(
|
||||
async (oldPath: string, newName: string) => {
|
||||
// Extract the current file/folder name from the old path
|
||||
const oldName = oldPath.split('/').pop() || '';
|
||||
|
||||
// If the name hasn't changed, skip the rename entirely (no-op)
|
||||
if (newName === oldName) return;
|
||||
|
||||
const parentPath = oldPath.substring(0, oldPath.lastIndexOf('/'));
|
||||
const newPath = `${parentPath}/${newName}`;
|
||||
|
||||
@@ -1028,6 +1034,9 @@ export function FileEditorView({ initialPath }: FileEditorViewProps) {
|
||||
onTabSelect={setActiveTab}
|
||||
onTabClose={handleTabClose}
|
||||
onCloseAll={handleCloseAll}
|
||||
onSave={handleSave}
|
||||
isDirty={activeTab?.isDirty && !activeTab?.isBinary && !activeTab?.isTooLarge}
|
||||
showSaveButton={isMobile && !!activeTab && !activeTab.isBinary && !activeTab.isTooLarge}
|
||||
/>
|
||||
|
||||
{/* Editor content */}
|
||||
@@ -1320,24 +1329,6 @@ export function FileEditorView({ initialPath }: FileEditorViewProps) {
|
||||
</PopoverContent>
|
||||
</Popover>
|
||||
|
||||
{/* Mobile: Save button in main toolbar */}
|
||||
{activeTab &&
|
||||
!activeTab.isBinary &&
|
||||
!activeTab.isTooLarge &&
|
||||
isMobile &&
|
||||
!mobileBrowserVisible && (
|
||||
<Button
|
||||
variant="outline"
|
||||
size="icon-sm"
|
||||
onClick={handleSave}
|
||||
disabled={!activeTab.isDirty}
|
||||
className="lg:hidden"
|
||||
title={editorAutoSave ? 'Auto-save enabled (Ctrl+S)' : 'Save file (Ctrl+S)'}
|
||||
>
|
||||
<Save className="w-4 h-4" />
|
||||
</Button>
|
||||
)}
|
||||
|
||||
{/* Tablet/Mobile: actions panel trigger */}
|
||||
<HeaderActionsPanelTrigger
|
||||
isOpen={showActionsPanel}
|
||||
|
||||
@@ -10,12 +10,15 @@ import { ConfirmDialog } from '@/components/ui/confirm-dialog';
|
||||
import { LoadingState } from '@/components/ui/loading-state';
|
||||
import { ErrorState } from '@/components/ui/error-state';
|
||||
import { cn, pathsEqual, generateUUID } from '@/lib/utils';
|
||||
import { useIsMobile } from '@/hooks/use-media-query';
|
||||
import { toast } from 'sonner';
|
||||
import { queryKeys } from '@/lib/query-keys';
|
||||
import { useGithubIssues, useIssueValidation, useIssuesFilter } from './github-issues-view/hooks';
|
||||
import { IssueRow, IssueDetailPanel, IssuesListHeader } from './github-issues-view/components';
|
||||
import { ValidationDialog } from './github-issues-view/dialogs';
|
||||
import { AddFeatureDialog } from './board-view/dialogs';
|
||||
import { formatDate, getFeaturePriority } from './github-issues-view/utils';
|
||||
import { resolveModelString } from '@automaker/model-resolver';
|
||||
import { useModelOverride } from '@/components/shared';
|
||||
import type {
|
||||
ValidateIssueOptions,
|
||||
@@ -34,15 +37,22 @@ export function GitHubIssuesView() {
|
||||
const [pendingRevalidateOptions, setPendingRevalidateOptions] =
|
||||
useState<ValidateIssueOptions | null>(null);
|
||||
|
||||
// Add Feature dialog state
|
||||
const [showAddFeatureDialog, setShowAddFeatureDialog] = useState(false);
|
||||
const [createFeatureIssue, setCreateFeatureIssue] = useState<GitHubIssue | null>(null);
|
||||
|
||||
// Filter state
|
||||
const [filterState, setFilterState] = useState<IssuesFilterState>(DEFAULT_ISSUES_FILTER_STATE);
|
||||
|
||||
const { currentProject, getCurrentWorktree, worktreesByProject } = useAppStore();
|
||||
const { currentProject, getCurrentWorktree, worktreesByProject, defaultSkipTests } =
|
||||
useAppStore();
|
||||
const queryClient = useQueryClient();
|
||||
|
||||
// Model override for validation
|
||||
const validationModelOverride = useModelOverride({ phase: 'validationModel' });
|
||||
|
||||
const isMobile = useIsMobile();
|
||||
|
||||
const { openIssues, closedIssues, loading, refreshing, error, refresh } = useGithubIssues();
|
||||
|
||||
const { validatingIssues, cachedValidations, handleValidateIssue, handleViewCachedValidation } =
|
||||
@@ -108,6 +118,132 @@ export function GitHubIssuesView() {
|
||||
api.openExternalLink(url);
|
||||
}, []);
|
||||
|
||||
// Build a prefilled description from a GitHub issue for the feature dialog
|
||||
const buildIssueDescription = useCallback(
|
||||
(issue: GitHubIssue) => {
|
||||
const parts = [
|
||||
`**From GitHub Issue #${issue.number}**`,
|
||||
'',
|
||||
issue.body || 'No description provided.',
|
||||
];
|
||||
|
||||
// Include labels if present
|
||||
if (issue.labels.length > 0) {
|
||||
parts.push('', `**Labels:** ${issue.labels.map((l) => l.name).join(', ')}`);
|
||||
}
|
||||
|
||||
// Include linked PRs info if present
|
||||
if (issue.linkedPRs && issue.linkedPRs.length > 0) {
|
||||
parts.push(
|
||||
'',
|
||||
'**Linked Pull Requests:**',
|
||||
...issue.linkedPRs.map((pr) => `- #${pr.number}: ${pr.title} (${pr.state})`)
|
||||
);
|
||||
}
|
||||
|
||||
// Include cached validation analysis if available
|
||||
const cached = cachedValidations.get(issue.number);
|
||||
if (cached?.result) {
|
||||
const validation = cached.result;
|
||||
parts.push('', '---', '', '**AI Validation Analysis:**', validation.reasoning);
|
||||
if (validation.suggestedFix) {
|
||||
parts.push('', `**Suggested Approach:**`, validation.suggestedFix);
|
||||
}
|
||||
if (validation.relatedFiles?.length) {
|
||||
parts.push('', '**Related Files:**', ...validation.relatedFiles.map((f) => `- \`${f}\``));
|
||||
}
|
||||
}
|
||||
|
||||
return parts.join('\n');
|
||||
},
|
||||
[cachedValidations]
|
||||
);
|
||||
|
||||
// Memoize the prefilled description to avoid recomputing on every render
|
||||
const prefilledDescription = useMemo(
|
||||
() => (createFeatureIssue ? buildIssueDescription(createFeatureIssue) : undefined),
|
||||
[createFeatureIssue, buildIssueDescription]
|
||||
);
|
||||
|
||||
// Open the Add Feature dialog with pre-filled data from a GitHub issue
|
||||
const handleCreateFeature = useCallback((issue: GitHubIssue) => {
|
||||
setCreateFeatureIssue(issue);
|
||||
setShowAddFeatureDialog(true);
|
||||
}, []);
|
||||
|
||||
// Handle feature creation from the AddFeatureDialog
|
||||
const handleAddFeatureFromIssue = useCallback(
|
||||
async (featureData: {
|
||||
title: string;
|
||||
category: string;
|
||||
description: string;
|
||||
priority: number;
|
||||
model: string;
|
||||
thinkingLevel: string;
|
||||
reasoningEffort: string;
|
||||
skipTests: boolean;
|
||||
branchName: string;
|
||||
planningMode: string;
|
||||
requirePlanApproval: boolean;
|
||||
excludedPipelineSteps?: string[];
|
||||
workMode: string;
|
||||
imagePaths?: Array<{ id: string; path: string; description?: string }>;
|
||||
textFilePaths?: Array<{ id: string; path: string; description?: string }>;
|
||||
}) => {
|
||||
if (!currentProject?.path) {
|
||||
toast.error('No project selected');
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
const api = getElectronAPI();
|
||||
if (api.features?.create) {
|
||||
const feature = {
|
||||
id: `issue-${createFeatureIssue?.number || 'new'}-${generateUUID()}`,
|
||||
title: featureData.title,
|
||||
description: featureData.description,
|
||||
category: featureData.category,
|
||||
status: 'backlog' as const,
|
||||
passes: false,
|
||||
priority: featureData.priority,
|
||||
model: featureData.model,
|
||||
thinkingLevel: featureData.thinkingLevel,
|
||||
reasoningEffort: featureData.reasoningEffort,
|
||||
skipTests: featureData.skipTests,
|
||||
branchName: featureData.workMode === 'current' ? currentBranch : featureData.branchName,
|
||||
planningMode: featureData.planningMode,
|
||||
requirePlanApproval: featureData.requirePlanApproval,
|
||||
excludedPipelineSteps: featureData.excludedPipelineSteps,
|
||||
...(featureData.imagePaths?.length ? { imagePaths: featureData.imagePaths } : {}),
|
||||
...(featureData.textFilePaths?.length
|
||||
? { textFilePaths: featureData.textFilePaths }
|
||||
: {}),
|
||||
createdAt: new Date().toISOString(),
|
||||
updatedAt: new Date().toISOString(),
|
||||
};
|
||||
|
||||
const result = await api.features.create(currentProject.path, feature);
|
||||
if (result.success) {
|
||||
queryClient.invalidateQueries({
|
||||
queryKey: queryKeys.features.all(currentProject.path),
|
||||
});
|
||||
toast.success(
|
||||
`Created feature: ${featureData.title || featureData.description.slice(0, 50)}`
|
||||
);
|
||||
setShowAddFeatureDialog(false);
|
||||
setCreateFeatureIssue(null);
|
||||
} else {
|
||||
toast.error(result.error || 'Failed to create feature');
|
||||
}
|
||||
}
|
||||
} catch (err) {
|
||||
logger.error('Create feature from issue error:', err);
|
||||
toast.error(err instanceof Error ? err.message : 'Failed to create feature');
|
||||
}
|
||||
},
|
||||
[currentProject?.path, currentBranch, queryClient, createFeatureIssue]
|
||||
);
|
||||
|
||||
const handleConvertToTask = useCallback(
|
||||
async (issue: GitHubIssue, validation: IssueValidationResult) => {
|
||||
if (!currentProject?.path) {
|
||||
@@ -119,7 +255,7 @@ export function GitHubIssuesView() {
|
||||
const api = getElectronAPI();
|
||||
if (api.features?.create) {
|
||||
// Build description from issue body + validation info
|
||||
const description = [
|
||||
const parts = [
|
||||
`**From GitHub Issue #${issue.number}**`,
|
||||
'',
|
||||
issue.body || 'No description provided.',
|
||||
@@ -128,13 +264,18 @@ export function GitHubIssuesView() {
|
||||
'',
|
||||
'**AI Validation Analysis:**',
|
||||
validation.reasoning,
|
||||
validation.suggestedFix ? `\n**Suggested Approach:**\n${validation.suggestedFix}` : '',
|
||||
validation.relatedFiles?.length
|
||||
? `\n**Related Files:**\n${validation.relatedFiles.map((f) => `- \`${f}\``).join('\n')}`
|
||||
: '',
|
||||
]
|
||||
.filter(Boolean)
|
||||
.join('\n');
|
||||
];
|
||||
if (validation.suggestedFix) {
|
||||
parts.push('', `**Suggested Approach:**`, validation.suggestedFix);
|
||||
}
|
||||
if (validation.relatedFiles?.length) {
|
||||
parts.push(
|
||||
'',
|
||||
'**Related Files:**',
|
||||
...validation.relatedFiles.map((f) => `- \`${f}\``)
|
||||
);
|
||||
}
|
||||
const description = parts.join('\n');
|
||||
|
||||
const feature = {
|
||||
id: `issue-${issue.number}-${generateUUID()}`,
|
||||
@@ -144,7 +285,7 @@ export function GitHubIssuesView() {
|
||||
status: 'backlog' as const,
|
||||
passes: false,
|
||||
priority: getFeaturePriority(validation.estimatedComplexity),
|
||||
model: 'opus',
|
||||
model: resolveModelString('opus'),
|
||||
thinkingLevel: 'none' as const,
|
||||
branchName: currentBranch,
|
||||
createdAt: new Date().toISOString(),
|
||||
@@ -185,11 +326,12 @@ export function GitHubIssuesView() {
|
||||
|
||||
return (
|
||||
<div className="flex-1 flex overflow-hidden">
|
||||
{/* Issues List */}
|
||||
{/* Issues List - hidden on mobile when an issue is selected */}
|
||||
<div
|
||||
className={cn(
|
||||
'flex flex-col overflow-hidden border-r border-border',
|
||||
selectedIssue ? 'w-80' : 'flex-1'
|
||||
selectedIssue ? 'w-80' : 'flex-1',
|
||||
isMobile && selectedIssue && 'hidden'
|
||||
)}
|
||||
>
|
||||
{/* Header */}
|
||||
@@ -296,8 +438,10 @@ export function GitHubIssuesView() {
|
||||
setPendingRevalidateOptions(options);
|
||||
setShowRevalidateConfirm(true);
|
||||
}}
|
||||
onCreateFeature={handleCreateFeature}
|
||||
formatDate={formatDate}
|
||||
modelOverride={validationModelOverride}
|
||||
isMobile={isMobile}
|
||||
/>
|
||||
)}
|
||||
|
||||
@@ -310,6 +454,28 @@ export function GitHubIssuesView() {
|
||||
onConvertToTask={handleConvertToTask}
|
||||
/>
|
||||
|
||||
{/* Add Feature Dialog - opened from issue detail panel */}
|
||||
<AddFeatureDialog
|
||||
open={showAddFeatureDialog}
|
||||
onOpenChange={(open) => {
|
||||
setShowAddFeatureDialog(open);
|
||||
if (!open) {
|
||||
setCreateFeatureIssue(null);
|
||||
}
|
||||
}}
|
||||
onAdd={handleAddFeatureFromIssue}
|
||||
categorySuggestions={['From GitHub']}
|
||||
branchSuggestions={[]}
|
||||
defaultSkipTests={defaultSkipTests}
|
||||
defaultBranch={currentBranch}
|
||||
currentBranch={currentBranch || undefined}
|
||||
isMaximized={false}
|
||||
projectPath={currentProject?.path}
|
||||
prefilledTitle={createFeatureIssue?.title}
|
||||
prefilledDescription={prefilledDescription}
|
||||
prefilledCategory="From GitHub"
|
||||
/>
|
||||
|
||||
{/* Revalidate Confirmation Dialog */}
|
||||
<ConfirmDialog
|
||||
open={showRevalidateConfirm}
|
||||
|
||||
@@ -12,6 +12,8 @@ import {
|
||||
MessageSquare,
|
||||
ChevronDown,
|
||||
ChevronUp,
|
||||
Plus,
|
||||
ArrowLeft,
|
||||
} from 'lucide-react';
|
||||
import { Spinner } from '@/components/ui/spinner';
|
||||
import { useState } from 'react';
|
||||
@@ -34,8 +36,10 @@ export function IssueDetailPanel({
|
||||
onOpenInGitHub,
|
||||
onClose,
|
||||
onShowRevalidateConfirm,
|
||||
onCreateFeature,
|
||||
formatDate,
|
||||
modelOverride,
|
||||
isMobile = false,
|
||||
}: IssueDetailPanelProps) {
|
||||
const isValidating = validatingIssues.has(issue.number);
|
||||
const cached = cachedValidations.get(issue.number);
|
||||
@@ -71,8 +75,20 @@ export function IssueDetailPanel({
|
||||
return (
|
||||
<div className="flex-1 flex flex-col overflow-hidden">
|
||||
{/* Detail Header */}
|
||||
<div className="flex items-center justify-between p-3 border-b border-border bg-muted/30">
|
||||
<div className="flex items-center justify-between p-3 border-b border-border bg-muted/30 gap-2">
|
||||
<div className="flex items-center gap-2 min-w-0">
|
||||
{isMobile && (
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
onClick={onClose}
|
||||
className="shrink-0 -ml-1"
|
||||
aria-label="Back"
|
||||
title="Back"
|
||||
>
|
||||
<ArrowLeft className="h-4 w-4" />
|
||||
</Button>
|
||||
)}
|
||||
{issue.state === 'OPEN' ? (
|
||||
<Circle className="h-4 w-4 text-green-500 shrink-0" />
|
||||
) : (
|
||||
@@ -82,12 +98,12 @@ export function IssueDetailPanel({
|
||||
#{issue.number} {issue.title}
|
||||
</span>
|
||||
</div>
|
||||
<div className="flex items-center gap-2 shrink-0">
|
||||
<div className={cn('flex items-center gap-2 shrink-0', isMobile && 'gap-1')}>
|
||||
{(() => {
|
||||
if (isValidating) {
|
||||
return (
|
||||
<Button variant="default" size="sm" loading>
|
||||
Validating...
|
||||
{isMobile ? '...' : 'Validating...'}
|
||||
</Button>
|
||||
);
|
||||
}
|
||||
@@ -95,9 +111,15 @@ export function IssueDetailPanel({
|
||||
if (cached && !isStale) {
|
||||
return (
|
||||
<>
|
||||
<Button variant="outline" size="sm" onClick={() => onViewCachedValidation(issue)}>
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
onClick={() => onViewCachedValidation(issue)}
|
||||
aria-label="View Result"
|
||||
title="View Result"
|
||||
>
|
||||
<CheckCircle className="h-4 w-4 mr-1 text-green-500" />
|
||||
View Result
|
||||
{!isMobile && 'View Result'}
|
||||
</Button>
|
||||
<Button
|
||||
variant="ghost"
|
||||
@@ -114,9 +136,15 @@ export function IssueDetailPanel({
|
||||
if (cached && isStale) {
|
||||
return (
|
||||
<>
|
||||
<Button variant="outline" size="sm" onClick={() => onViewCachedValidation(issue)}>
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
onClick={() => onViewCachedValidation(issue)}
|
||||
aria-label="View (stale)"
|
||||
title="View (stale)"
|
||||
>
|
||||
<Clock className="h-4 w-4 mr-1 text-yellow-500" />
|
||||
View (stale)
|
||||
{!isMobile && 'View (stale)'}
|
||||
</Button>
|
||||
<ModelOverrideTrigger
|
||||
currentModelEntry={modelOverride.effectiveModelEntry}
|
||||
@@ -131,9 +159,11 @@ export function IssueDetailPanel({
|
||||
variant="default"
|
||||
size="sm"
|
||||
onClick={() => onValidateIssue(issue, getValidationOptions(true))}
|
||||
aria-label="Re-validate"
|
||||
title="Re-validate"
|
||||
>
|
||||
<Wand2 className="h-4 w-4 mr-1" />
|
||||
Re-validate
|
||||
{!isMobile && 'Re-validate'}
|
||||
</Button>
|
||||
</>
|
||||
);
|
||||
@@ -154,25 +184,46 @@ export function IssueDetailPanel({
|
||||
variant="default"
|
||||
size="sm"
|
||||
onClick={() => onValidateIssue(issue, getValidationOptions())}
|
||||
aria-label="Validate with AI"
|
||||
title="Validate with AI"
|
||||
>
|
||||
<Wand2 className="h-4 w-4 mr-1" />
|
||||
Validate with AI
|
||||
{!isMobile && 'Validate with AI'}
|
||||
</Button>
|
||||
</>
|
||||
);
|
||||
})()}
|
||||
<Button variant="outline" size="sm" onClick={() => onOpenInGitHub(issue.url)}>
|
||||
<ExternalLink className="h-4 w-4 mr-1" />
|
||||
Open in GitHub
|
||||
</Button>
|
||||
<Button variant="ghost" size="sm" onClick={onClose}>
|
||||
<X className="h-4 w-4" />
|
||||
{!isMobile && (
|
||||
<Button
|
||||
variant="secondary"
|
||||
size="sm"
|
||||
onClick={() => onCreateFeature(issue)}
|
||||
title="Create a new feature to address this issue"
|
||||
>
|
||||
<Plus className="h-4 w-4 mr-1" />
|
||||
Create Feature
|
||||
</Button>
|
||||
)}
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
onClick={() => onOpenInGitHub(issue.url)}
|
||||
aria-label="Open in GitHub"
|
||||
title="Open in GitHub"
|
||||
>
|
||||
<ExternalLink className="h-4 w-4" />
|
||||
{!isMobile && <span className="ml-1">Open in GitHub</span>}
|
||||
</Button>
|
||||
{!isMobile && (
|
||||
<Button variant="ghost" size="sm" onClick={onClose}>
|
||||
<X className="h-4 w-4" />
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Issue Detail Content */}
|
||||
<div className="flex-1 overflow-auto p-6">
|
||||
<div className={cn('flex-1 overflow-auto', isMobile ? 'p-4' : 'p-6')}>
|
||||
{/* Title */}
|
||||
<h1 className="text-xl font-bold mb-2">{issue.title}</h1>
|
||||
|
||||
@@ -344,8 +395,25 @@ export function IssueDetailPanel({
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* Create Feature CTA - shown on mobile since it's hidden from the header */}
|
||||
{isMobile && (
|
||||
<div className="mt-6 p-4 rounded-lg bg-primary/5 border border-primary/20">
|
||||
<div className="flex items-center gap-2 mb-2">
|
||||
<Plus className="h-4 w-4 text-primary" />
|
||||
<span className="text-sm font-medium">Create Feature</span>
|
||||
</div>
|
||||
<p className="text-sm text-muted-foreground mb-3">
|
||||
Create a new feature task to address this issue.
|
||||
</p>
|
||||
<Button variant="secondary" onClick={() => onCreateFeature(issue)}>
|
||||
<Plus className="h-4 w-4 mr-2" />
|
||||
Create Feature
|
||||
</Button>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Open in GitHub CTA */}
|
||||
<div className="mt-8 p-4 rounded-lg bg-muted/50 border border-border">
|
||||
<div className="mt-4 p-4 rounded-lg bg-muted/50 border border-border">
|
||||
<p className="text-sm text-muted-foreground mb-3">
|
||||
View comments, add reactions, and more on GitHub.
|
||||
</p>
|
||||
|
||||
@@ -138,6 +138,8 @@ export interface IssueDetailPanelProps {
|
||||
onClose: () => void;
|
||||
/** Called when user wants to revalidate - receives the validation options including comments/linkedPRs */
|
||||
onShowRevalidateConfirm: (options: ValidateIssueOptions) => void;
|
||||
/** Called when user wants to create a feature to address this issue */
|
||||
onCreateFeature: (issue: GitHubIssue) => void;
|
||||
formatDate: (date: string) => string;
|
||||
/** Model override state */
|
||||
modelOverride: {
|
||||
@@ -146,4 +148,6 @@ export interface IssueDetailPanelProps {
|
||||
isOverridden: boolean;
|
||||
setOverride: (entry: PhaseModelEntry | null) => void;
|
||||
};
|
||||
/** Whether the view is in mobile mode - shows back button and full-screen detail */
|
||||
isMobile?: boolean;
|
||||
}
|
||||
|
||||
@@ -5,18 +5,42 @@
|
||||
*/
|
||||
|
||||
import { useState, useCallback } from 'react';
|
||||
import { GitPullRequest, RefreshCw, ExternalLink, GitMerge, X } from 'lucide-react';
|
||||
import {
|
||||
GitPullRequest,
|
||||
RefreshCw,
|
||||
ExternalLink,
|
||||
GitMerge,
|
||||
X,
|
||||
MessageSquare,
|
||||
MoreHorizontal,
|
||||
Zap,
|
||||
ArrowLeft,
|
||||
} from 'lucide-react';
|
||||
import { Spinner } from '@/components/ui/spinner';
|
||||
import { getElectronAPI, type GitHubPR } from '@/lib/electron';
|
||||
import { useAppStore } from '@/store/app-store';
|
||||
import { useAppStore, type Feature } from '@/store/app-store';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { Markdown } from '@/components/ui/markdown';
|
||||
import { cn } from '@/lib/utils';
|
||||
import { cn, generateUUID } from '@/lib/utils';
|
||||
import { useIsMobile } from '@/hooks/use-media-query';
|
||||
import { useGitHubPRs } from '@/hooks/queries';
|
||||
import { useCreateFeature } from '@/hooks/mutations/use-feature-mutations';
|
||||
import { PRCommentResolutionDialog } from '@/components/dialogs';
|
||||
import { resolveModelString } from '@automaker/model-resolver';
|
||||
import { toast } from 'sonner';
|
||||
import {
|
||||
DropdownMenu,
|
||||
DropdownMenuContent,
|
||||
DropdownMenuItem,
|
||||
DropdownMenuSeparator,
|
||||
DropdownMenuTrigger,
|
||||
} from '@/components/ui/dropdown-menu';
|
||||
|
||||
export function GitHubPRsView() {
|
||||
const [selectedPR, setSelectedPR] = useState<GitHubPR | null>(null);
|
||||
const [commentDialogPR, setCommentDialogPR] = useState<GitHubPR | null>(null);
|
||||
const { currentProject } = useAppStore();
|
||||
const isMobile = useIsMobile();
|
||||
|
||||
const {
|
||||
data,
|
||||
@@ -38,6 +62,65 @@ export function GitHubPRsView() {
|
||||
api.openExternalLink(url);
|
||||
}, []);
|
||||
|
||||
const createFeature = useCreateFeature(currentProject?.path ?? '');
|
||||
|
||||
const handleAutoAddressComments = useCallback(
|
||||
async (pr: GitHubPR) => {
|
||||
if (!pr.number || !currentProject?.path) {
|
||||
toast.error('Cannot address PR comments', {
|
||||
description: 'No PR number or project available.',
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
const featureId = `pr-${pr.number}-${generateUUID()}`;
|
||||
const feature: Feature = {
|
||||
id: featureId,
|
||||
title: `Address PR #${pr.number} Review Comments`,
|
||||
category: 'bug-fix',
|
||||
description: `Read the review requests on PR #${pr.number} and address any feedback the best you can.`,
|
||||
steps: [],
|
||||
status: 'backlog',
|
||||
model: resolveModelString('opus'),
|
||||
thinkingLevel: 'none',
|
||||
planningMode: 'skip',
|
||||
...(pr.headRefName ? { branchName: pr.headRefName } : {}),
|
||||
};
|
||||
|
||||
try {
|
||||
await createFeature.mutateAsync(feature);
|
||||
|
||||
// Start the feature immediately after creation
|
||||
const api = getElectronAPI();
|
||||
if (api.autoMode?.runFeature) {
|
||||
try {
|
||||
await api.autoMode.runFeature(currentProject.path, featureId);
|
||||
toast.success('Feature created and started', {
|
||||
description: `Addressing review comments on PR #${pr.number}`,
|
||||
});
|
||||
} catch (runError) {
|
||||
toast.error('Feature created but failed to start', {
|
||||
description:
|
||||
runError instanceof Error
|
||||
? runError.message
|
||||
: 'An error occurred while starting the feature',
|
||||
});
|
||||
}
|
||||
} else {
|
||||
toast.error('Cannot start feature', {
|
||||
description:
|
||||
'Feature API is not available. The feature was created but could not be started.',
|
||||
});
|
||||
}
|
||||
} catch (error) {
|
||||
toast.error('Failed to create feature', {
|
||||
description: error instanceof Error ? error.message : 'An error occurred',
|
||||
});
|
||||
}
|
||||
},
|
||||
[currentProject, createFeature]
|
||||
);
|
||||
|
||||
const formatDate = (dateString: string) => {
|
||||
const date = new Date(dateString);
|
||||
return date.toLocaleDateString('en-US', {
|
||||
@@ -91,11 +174,12 @@ export function GitHubPRsView() {
|
||||
|
||||
return (
|
||||
<div className="flex-1 flex overflow-hidden">
|
||||
{/* PR List */}
|
||||
{/* PR List - hidden on mobile when a PR is selected */}
|
||||
<div
|
||||
className={cn(
|
||||
'flex flex-col overflow-hidden border-r border-border',
|
||||
selectedPR ? 'w-80' : 'flex-1'
|
||||
selectedPR ? 'w-80' : 'flex-1',
|
||||
isMobile && selectedPR && 'hidden'
|
||||
)}
|
||||
>
|
||||
{/* Header */}
|
||||
@@ -140,6 +224,8 @@ export function GitHubPRsView() {
|
||||
isSelected={selectedPR?.number === pr.number}
|
||||
onClick={() => setSelectedPR(pr)}
|
||||
onOpenExternal={() => handleOpenInGitHub(pr.url)}
|
||||
onManageComments={() => setCommentDialogPR(pr)}
|
||||
onAutoAddressComments={() => handleAutoAddressComments(pr)}
|
||||
formatDate={formatDate}
|
||||
getReviewStatus={getReviewStatus}
|
||||
/>
|
||||
@@ -158,6 +244,8 @@ export function GitHubPRsView() {
|
||||
isSelected={selectedPR?.number === pr.number}
|
||||
onClick={() => setSelectedPR(pr)}
|
||||
onOpenExternal={() => handleOpenInGitHub(pr.url)}
|
||||
onManageComments={() => setCommentDialogPR(pr)}
|
||||
onAutoAddressComments={() => handleAutoAddressComments(pr)}
|
||||
formatDate={formatDate}
|
||||
getReviewStatus={getReviewStatus}
|
||||
/>
|
||||
@@ -170,124 +258,187 @@ export function GitHubPRsView() {
|
||||
</div>
|
||||
|
||||
{/* PR Detail Panel */}
|
||||
{selectedPR && (
|
||||
<div className="flex-1 flex flex-col overflow-hidden">
|
||||
{/* Detail Header */}
|
||||
<div className="flex items-center justify-between p-3 border-b border-border bg-muted/30">
|
||||
<div className="flex items-center gap-2 min-w-0">
|
||||
{selectedPR.state === 'MERGED' ? (
|
||||
<GitMerge className="h-4 w-4 text-purple-500 shrink-0" />
|
||||
) : (
|
||||
<GitPullRequest className="h-4 w-4 text-green-500 shrink-0" />
|
||||
)}
|
||||
<span className="text-sm font-medium truncate">
|
||||
#{selectedPR.number} {selectedPR.title}
|
||||
</span>
|
||||
{selectedPR.isDraft && (
|
||||
<span className="px-1.5 py-0.5 text-[10px] font-medium rounded bg-muted text-muted-foreground">
|
||||
Draft
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
<div className="flex items-center gap-2 shrink-0">
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
onClick={() => handleOpenInGitHub(selectedPR.url)}
|
||||
>
|
||||
<ExternalLink className="h-4 w-4 mr-1" />
|
||||
Open in GitHub
|
||||
</Button>
|
||||
<Button variant="ghost" size="sm" onClick={() => setSelectedPR(null)}>
|
||||
<X className="h-4 w-4" />
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* PR Detail Content */}
|
||||
<div className="flex-1 overflow-auto p-6">
|
||||
{/* Title */}
|
||||
<h1 className="text-xl font-bold mb-2">{selectedPR.title}</h1>
|
||||
|
||||
{/* Meta info */}
|
||||
<div className="flex items-center gap-3 text-sm text-muted-foreground mb-4 flex-wrap">
|
||||
<span
|
||||
className={cn(
|
||||
'px-2 py-0.5 rounded-full text-xs font-medium',
|
||||
selectedPR.state === 'MERGED'
|
||||
? 'bg-purple-500/10 text-purple-500'
|
||||
: selectedPR.isDraft
|
||||
? 'bg-muted text-muted-foreground'
|
||||
: 'bg-green-500/10 text-green-500'
|
||||
)}
|
||||
>
|
||||
{selectedPR.state === 'MERGED' ? 'Merged' : selectedPR.isDraft ? 'Draft' : 'Open'}
|
||||
</span>
|
||||
{getReviewStatus(selectedPR) && (
|
||||
<span
|
||||
className={cn(
|
||||
'px-2 py-0.5 rounded-full text-xs font-medium',
|
||||
getReviewStatus(selectedPR)!.bg,
|
||||
getReviewStatus(selectedPR)!.color
|
||||
{selectedPR &&
|
||||
(() => {
|
||||
const reviewStatus = getReviewStatus(selectedPR);
|
||||
return (
|
||||
<div className="flex-1 flex flex-col overflow-hidden">
|
||||
{/* Detail Header */}
|
||||
<div className="flex items-center justify-between p-3 border-b border-border bg-muted/30 gap-2">
|
||||
<div className="flex items-center gap-2 min-w-0">
|
||||
{isMobile && (
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
onClick={() => setSelectedPR(null)}
|
||||
className="shrink-0 -ml-1"
|
||||
>
|
||||
<ArrowLeft className="h-4 w-4" />
|
||||
</Button>
|
||||
)}
|
||||
>
|
||||
{getReviewStatus(selectedPR)!.label}
|
||||
</span>
|
||||
)}
|
||||
<span>
|
||||
#{selectedPR.number} opened {formatDate(selectedPR.createdAt)} by{' '}
|
||||
<span className="font-medium text-foreground">{selectedPR.author.login}</span>
|
||||
</span>
|
||||
</div>
|
||||
|
||||
{/* Branch info */}
|
||||
{selectedPR.headRefName && (
|
||||
<div className="flex items-center gap-2 mb-4">
|
||||
<span className="text-xs text-muted-foreground">Branch:</span>
|
||||
<span className="text-xs font-mono bg-muted px-2 py-0.5 rounded">
|
||||
{selectedPR.headRefName}
|
||||
</span>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Labels */}
|
||||
{selectedPR.labels.length > 0 && (
|
||||
<div className="flex items-center gap-2 mb-6 flex-wrap">
|
||||
{selectedPR.labels.map((label) => (
|
||||
<span
|
||||
key={label.name}
|
||||
className="px-2 py-0.5 text-xs font-medium rounded-full"
|
||||
style={{
|
||||
backgroundColor: `#${label.color}20`,
|
||||
color: `#${label.color}`,
|
||||
border: `1px solid #${label.color}40`,
|
||||
}}
|
||||
>
|
||||
{label.name}
|
||||
{selectedPR.state === 'MERGED' ? (
|
||||
<GitMerge className="h-4 w-4 text-purple-500 shrink-0" />
|
||||
) : (
|
||||
<GitPullRequest className="h-4 w-4 text-green-500 shrink-0" />
|
||||
)}
|
||||
<span className="text-sm font-medium truncate">
|
||||
#{selectedPR.number} {selectedPR.title}
|
||||
</span>
|
||||
))}
|
||||
{selectedPR.isDraft && (
|
||||
<span className="px-1.5 py-0.5 text-[10px] font-medium rounded bg-muted text-muted-foreground">
|
||||
Draft
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
<div className={cn('flex items-center gap-2 shrink-0', isMobile && 'gap-1')}>
|
||||
{!isMobile && (
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
onClick={() => setCommentDialogPR(selectedPR)}
|
||||
>
|
||||
<MessageSquare className="h-4 w-4 mr-1" />
|
||||
Manage Comments
|
||||
</Button>
|
||||
)}
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
onClick={() => handleOpenInGitHub(selectedPR.url)}
|
||||
>
|
||||
<ExternalLink className="h-4 w-4" />
|
||||
{!isMobile && <span className="ml-1">Open in GitHub</span>}
|
||||
</Button>
|
||||
{!isMobile && (
|
||||
<Button variant="ghost" size="sm" onClick={() => setSelectedPR(null)}>
|
||||
<X className="h-4 w-4" />
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Body */}
|
||||
{selectedPR.body ? (
|
||||
<Markdown className="text-sm">{selectedPR.body}</Markdown>
|
||||
) : (
|
||||
<p className="text-sm text-muted-foreground italic">No description provided.</p>
|
||||
)}
|
||||
{/* PR Detail Content */}
|
||||
<div className={cn('flex-1 overflow-auto', isMobile ? 'p-4' : 'p-6')}>
|
||||
{/* Title */}
|
||||
<h1 className="text-xl font-bold mb-2">{selectedPR.title}</h1>
|
||||
|
||||
{/* Open in GitHub CTA */}
|
||||
<div className="mt-8 p-4 rounded-lg bg-muted/50 border border-border">
|
||||
<p className="text-sm text-muted-foreground mb-3">
|
||||
View code changes, comments, and reviews on GitHub.
|
||||
</p>
|
||||
<Button onClick={() => handleOpenInGitHub(selectedPR.url)}>
|
||||
<ExternalLink className="h-4 w-4 mr-2" />
|
||||
View Full PR on GitHub
|
||||
</Button>
|
||||
{/* Meta info */}
|
||||
<div className="flex items-center gap-3 text-sm text-muted-foreground mb-4 flex-wrap">
|
||||
<span
|
||||
className={cn(
|
||||
'px-2 py-0.5 rounded-full text-xs font-medium',
|
||||
selectedPR.state === 'MERGED'
|
||||
? 'bg-purple-500/10 text-purple-500'
|
||||
: selectedPR.isDraft
|
||||
? 'bg-muted text-muted-foreground'
|
||||
: 'bg-green-500/10 text-green-500'
|
||||
)}
|
||||
>
|
||||
{selectedPR.state === 'MERGED'
|
||||
? 'Merged'
|
||||
: selectedPR.isDraft
|
||||
? 'Draft'
|
||||
: 'Open'}
|
||||
</span>
|
||||
{reviewStatus && (
|
||||
<span
|
||||
className={cn(
|
||||
'px-2 py-0.5 rounded-full text-xs font-medium',
|
||||
reviewStatus.bg,
|
||||
reviewStatus.color
|
||||
)}
|
||||
>
|
||||
{reviewStatus.label}
|
||||
</span>
|
||||
)}
|
||||
<span>
|
||||
#{selectedPR.number} opened {formatDate(selectedPR.createdAt)} by{' '}
|
||||
<span className="font-medium text-foreground">{selectedPR.author.login}</span>
|
||||
</span>
|
||||
</div>
|
||||
|
||||
{/* Branch info */}
|
||||
{selectedPR.headRefName && (
|
||||
<div className="flex items-center gap-2 mb-4">
|
||||
<span className="text-xs text-muted-foreground">Branch:</span>
|
||||
<span className="text-xs font-mono bg-muted px-2 py-0.5 rounded">
|
||||
{selectedPR.headRefName}
|
||||
</span>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Labels */}
|
||||
{selectedPR.labels.length > 0 && (
|
||||
<div className="flex items-center gap-2 mb-6 flex-wrap">
|
||||
{selectedPR.labels.map((label) => (
|
||||
<span
|
||||
key={label.name}
|
||||
className="px-2 py-0.5 text-xs font-medium rounded-full"
|
||||
style={{
|
||||
backgroundColor: `#${label.color}20`,
|
||||
color: `#${label.color}`,
|
||||
border: `1px solid #${label.color}40`,
|
||||
}}
|
||||
>
|
||||
{label.name}
|
||||
</span>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Body */}
|
||||
{selectedPR.body ? (
|
||||
<Markdown className="text-sm">{selectedPR.body}</Markdown>
|
||||
) : (
|
||||
<p className="text-sm text-muted-foreground italic">No description provided.</p>
|
||||
)}
|
||||
|
||||
{/* Review Comments CTA */}
|
||||
<div className="mt-8 p-4 rounded-lg bg-blue-500/5 border border-blue-500/20">
|
||||
<div className="flex items-center gap-2 mb-2">
|
||||
<MessageSquare className="h-4 w-4 text-blue-500" />
|
||||
<span className="text-sm font-medium">Review Comments</span>
|
||||
</div>
|
||||
<p className="text-sm text-muted-foreground mb-3">
|
||||
Manage review comments individually or let AI address all feedback
|
||||
automatically.
|
||||
</p>
|
||||
<div className={cn('flex gap-2', isMobile ? 'flex-col' : 'items-center')}>
|
||||
<Button variant="outline" onClick={() => setCommentDialogPR(selectedPR)}>
|
||||
<MessageSquare className="h-4 w-4 mr-2" />
|
||||
Manage Review Comments
|
||||
</Button>
|
||||
<Button variant="outline" onClick={() => handleAutoAddressComments(selectedPR)}>
|
||||
<Zap className="h-4 w-4 mr-2" />
|
||||
Address Review Comments
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Open in GitHub CTA */}
|
||||
<div className="mt-4 p-4 rounded-lg bg-muted/50 border border-border">
|
||||
<p className="text-sm text-muted-foreground mb-3">
|
||||
View code changes, comments, and reviews on GitHub.
|
||||
</p>
|
||||
<Button onClick={() => handleOpenInGitHub(selectedPR.url)}>
|
||||
<ExternalLink className="h-4 w-4 mr-2" />
|
||||
View Full PR on GitHub
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
})()}
|
||||
|
||||
{/* PR Comment Resolution Dialog */}
|
||||
{commentDialogPR && (
|
||||
<PRCommentResolutionDialog
|
||||
open={!!commentDialogPR}
|
||||
onOpenChange={(open) => {
|
||||
if (!open) setCommentDialogPR(null);
|
||||
}}
|
||||
pr={commentDialogPR}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
@@ -298,6 +449,8 @@ interface PRRowProps {
|
||||
isSelected: boolean;
|
||||
onClick: () => void;
|
||||
onOpenExternal: () => void;
|
||||
onManageComments: () => void;
|
||||
onAutoAddressComments: () => void;
|
||||
formatDate: (date: string) => string;
|
||||
getReviewStatus: (pr: GitHubPR) => { label: string; color: string; bg: string } | null;
|
||||
}
|
||||
@@ -307,6 +460,8 @@ function PRRow({
|
||||
isSelected,
|
||||
onClick,
|
||||
onOpenExternal,
|
||||
onManageComments,
|
||||
onAutoAddressComments,
|
||||
formatDate,
|
||||
getReviewStatus,
|
||||
}: PRRowProps) {
|
||||
@@ -378,17 +533,52 @@ function PRRow({
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
className="shrink-0 opacity-0 group-hover:opacity-100"
|
||||
onClick={(e) => {
|
||||
e.stopPropagation();
|
||||
onOpenExternal();
|
||||
}}
|
||||
>
|
||||
<ExternalLink className="h-3.5 w-3.5" />
|
||||
</Button>
|
||||
{/* Actions dropdown menu */}
|
||||
<DropdownMenu>
|
||||
<DropdownMenuTrigger asChild>
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
className="shrink-0 h-7 w-7 p-0"
|
||||
onClick={(e) => e.stopPropagation()}
|
||||
>
|
||||
<MoreHorizontal className="h-3.5 w-3.5" />
|
||||
</Button>
|
||||
</DropdownMenuTrigger>
|
||||
<DropdownMenuContent align="end" className="w-48">
|
||||
<DropdownMenuItem
|
||||
onClick={(e) => {
|
||||
e.stopPropagation();
|
||||
onManageComments();
|
||||
}}
|
||||
className="text-xs text-blue-500 focus:text-blue-600"
|
||||
>
|
||||
<MessageSquare className="h-3.5 w-3.5 mr-2" />
|
||||
Manage PR Comments
|
||||
</DropdownMenuItem>
|
||||
<DropdownMenuItem
|
||||
onClick={(e) => {
|
||||
e.stopPropagation();
|
||||
onAutoAddressComments();
|
||||
}}
|
||||
className="text-xs text-blue-500 focus:text-blue-600"
|
||||
>
|
||||
<Zap className="h-3.5 w-3.5 mr-2" />
|
||||
Address PR Comments
|
||||
</DropdownMenuItem>
|
||||
<DropdownMenuSeparator />
|
||||
<DropdownMenuItem
|
||||
onClick={(e) => {
|
||||
e.stopPropagation();
|
||||
onOpenExternal();
|
||||
}}
|
||||
className="text-xs"
|
||||
>
|
||||
<ExternalLink className="h-3.5 w-3.5 mr-2" />
|
||||
Open in GitHub
|
||||
</DropdownMenuItem>
|
||||
</DropdownMenuContent>
|
||||
</DropdownMenu>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -0,0 +1,657 @@
|
||||
import { useState, useEffect, useCallback, useMemo, useRef, type KeyboardEvent } from 'react';
|
||||
import { Input } from '@/components/ui/input';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import {
|
||||
Terminal,
|
||||
Save,
|
||||
RotateCcw,
|
||||
Info,
|
||||
X,
|
||||
Play,
|
||||
FlaskConical,
|
||||
ScrollText,
|
||||
Plus,
|
||||
GripVertical,
|
||||
Trash2,
|
||||
} from 'lucide-react';
|
||||
import { Spinner } from '@/components/ui/spinner';
|
||||
import { cn } from '@/lib/utils';
|
||||
import { useProjectSettings } from '@/hooks/queries';
|
||||
import { useUpdateProjectSettings } from '@/hooks/mutations';
|
||||
import type { Project } from '@/lib/electron';
|
||||
import { toast } from 'sonner';
|
||||
import { DEFAULT_TERMINAL_SCRIPTS } from './terminal-scripts-constants';
|
||||
|
||||
/** Preset dev server commands for quick selection */
|
||||
const DEV_SERVER_PRESETS = [
|
||||
{ label: 'npm run dev', command: 'npm run dev' },
|
||||
{ label: 'yarn dev', command: 'yarn dev' },
|
||||
{ label: 'pnpm dev', command: 'pnpm dev' },
|
||||
{ label: 'bun dev', command: 'bun dev' },
|
||||
{ label: 'npm start', command: 'npm start' },
|
||||
{ label: 'cargo watch', command: 'cargo watch -x run' },
|
||||
{ label: 'go run', command: 'go run .' },
|
||||
] as const;
|
||||
|
||||
/** Preset test commands for quick selection */
|
||||
const TEST_PRESETS = [
|
||||
{ label: 'npm test', command: 'npm test' },
|
||||
{ label: 'yarn test', command: 'yarn test' },
|
||||
{ label: 'pnpm test', command: 'pnpm test' },
|
||||
{ label: 'bun test', command: 'bun test' },
|
||||
{ label: 'pytest', command: 'pytest' },
|
||||
{ label: 'cargo test', command: 'cargo test' },
|
||||
{ label: 'go test', command: 'go test ./...' },
|
||||
] as const;
|
||||
|
||||
/** Preset scripts for quick addition */
|
||||
const SCRIPT_PRESETS = [
|
||||
{ name: 'Dev Server', command: 'npm run dev' },
|
||||
{ name: 'Build', command: 'npm run build' },
|
||||
{ name: 'Test', command: 'npm run test' },
|
||||
{ name: 'Lint', command: 'npm run lint' },
|
||||
{ name: 'Format', command: 'npm run format' },
|
||||
{ name: 'Type Check', command: 'npm run typecheck' },
|
||||
{ name: 'Start', command: 'npm start' },
|
||||
{ name: 'Clean', command: 'npm run clean' },
|
||||
] as const;
|
||||
|
||||
interface ScriptEntry {
|
||||
id: string;
|
||||
name: string;
|
||||
command: string;
|
||||
}
|
||||
|
||||
interface CommandsAndScriptsSectionProps {
|
||||
project: Project;
|
||||
}
|
||||
|
||||
/** Generate a unique ID for a new script */
|
||||
function generateId(): string {
|
||||
return `script-${Date.now()}-${Math.random().toString(36).slice(2, 7)}`;
|
||||
}
|
||||
|
||||
export function CommandsAndScriptsSection({ project }: CommandsAndScriptsSectionProps) {
|
||||
// Fetch project settings using TanStack Query
|
||||
const { data: projectSettings, isLoading, isError } = useProjectSettings(project.path);
|
||||
|
||||
// Mutation hook for updating project settings
|
||||
const updateSettingsMutation = useUpdateProjectSettings(project.path);
|
||||
|
||||
// ── Commands state ──
|
||||
const [devCommand, setDevCommand] = useState('');
|
||||
const [originalDevCommand, setOriginalDevCommand] = useState('');
|
||||
const [testCommand, setTestCommand] = useState('');
|
||||
const [originalTestCommand, setOriginalTestCommand] = useState('');
|
||||
|
||||
// ── Scripts state ──
|
||||
const [scripts, setScripts] = useState<ScriptEntry[]>([]);
|
||||
const [originalScripts, setOriginalScripts] = useState<ScriptEntry[]>([]);
|
||||
|
||||
// Dragging state for scripts
|
||||
const [draggedIndex, setDraggedIndex] = useState<number | null>(null);
|
||||
const [dragOverIndex, setDragOverIndex] = useState<number | null>(null);
|
||||
|
||||
// Track previous project path to detect project switches
|
||||
const prevProjectPathRef = useRef(project.path);
|
||||
// Track whether we've done the initial sync for the current project
|
||||
const isInitializedRef = useRef(false);
|
||||
|
||||
// Sync commands and scripts state when project settings load or project changes
|
||||
useEffect(() => {
|
||||
const projectChanged = prevProjectPathRef.current !== project.path;
|
||||
prevProjectPathRef.current = project.path;
|
||||
|
||||
// Always clear local state on project change to avoid flashing stale data
|
||||
if (projectChanged) {
|
||||
isInitializedRef.current = false;
|
||||
setDevCommand('');
|
||||
setOriginalDevCommand('');
|
||||
setTestCommand('');
|
||||
setOriginalTestCommand('');
|
||||
setScripts([]);
|
||||
setOriginalScripts([]);
|
||||
}
|
||||
|
||||
// Apply project settings only when they are available
|
||||
if (projectSettings) {
|
||||
// Only sync from server if this is the initial load or if there are no unsaved edits.
|
||||
// This prevents background refetches from overwriting in-progress local edits.
|
||||
const isDirty =
|
||||
isInitializedRef.current &&
|
||||
(devCommand !== originalDevCommand ||
|
||||
testCommand !== originalTestCommand ||
|
||||
JSON.stringify(scripts) !== JSON.stringify(originalScripts));
|
||||
|
||||
if (!isInitializedRef.current || !isDirty) {
|
||||
// Commands
|
||||
const dev = projectSettings.devCommand || '';
|
||||
const test = projectSettings.testCommand || '';
|
||||
setDevCommand(dev);
|
||||
setOriginalDevCommand(dev);
|
||||
setTestCommand(test);
|
||||
setOriginalTestCommand(test);
|
||||
|
||||
// Scripts
|
||||
const configured = projectSettings.terminalScripts;
|
||||
const scriptList =
|
||||
configured && configured.length > 0
|
||||
? configured.map((s) => ({ id: s.id, name: s.name, command: s.command }))
|
||||
: DEFAULT_TERMINAL_SCRIPTS.map((s) => ({ ...s }));
|
||||
setScripts(scriptList);
|
||||
setOriginalScripts(structuredClone(scriptList));
|
||||
|
||||
isInitializedRef.current = true;
|
||||
}
|
||||
}
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, [projectSettings, project.path]);
|
||||
|
||||
// ── Change detection ──
|
||||
const hasDevChanges = devCommand !== originalDevCommand;
|
||||
const hasTestChanges = testCommand !== originalTestCommand;
|
||||
const hasCommandChanges = hasDevChanges || hasTestChanges;
|
||||
const hasScriptChanges = useMemo(
|
||||
() => JSON.stringify(scripts) !== JSON.stringify(originalScripts),
|
||||
[scripts, originalScripts]
|
||||
);
|
||||
const hasChanges = hasCommandChanges || hasScriptChanges;
|
||||
const isSaving = updateSettingsMutation.isPending;
|
||||
|
||||
// ── Save all (commands + scripts) ──
|
||||
const handleSave = useCallback(() => {
|
||||
const normalizedDevCommand = devCommand.trim();
|
||||
const normalizedTestCommand = testCommand.trim();
|
||||
const validScripts = scripts.filter((s) => s.name.trim() && s.command.trim());
|
||||
const normalizedScripts = validScripts.map((s) => ({
|
||||
id: s.id,
|
||||
name: s.name.trim(),
|
||||
command: s.command.trim(),
|
||||
}));
|
||||
|
||||
updateSettingsMutation.mutate(
|
||||
{
|
||||
devCommand: normalizedDevCommand || null,
|
||||
testCommand: normalizedTestCommand || null,
|
||||
terminalScripts: normalizedScripts,
|
||||
},
|
||||
{
|
||||
onSuccess: () => {
|
||||
setDevCommand(normalizedDevCommand);
|
||||
setOriginalDevCommand(normalizedDevCommand);
|
||||
setTestCommand(normalizedTestCommand);
|
||||
setOriginalTestCommand(normalizedTestCommand);
|
||||
setScripts(normalizedScripts);
|
||||
setOriginalScripts(structuredClone(normalizedScripts));
|
||||
},
|
||||
onError: (error) => {
|
||||
toast.error('Failed to save settings', {
|
||||
description: error instanceof Error ? error.message : 'An unexpected error occurred',
|
||||
});
|
||||
},
|
||||
}
|
||||
);
|
||||
}, [devCommand, testCommand, scripts, updateSettingsMutation]);
|
||||
|
||||
// ── Reset all ──
|
||||
const handleReset = useCallback(() => {
|
||||
setDevCommand(originalDevCommand);
|
||||
setTestCommand(originalTestCommand);
|
||||
setScripts(structuredClone(originalScripts));
|
||||
}, [originalDevCommand, originalTestCommand, originalScripts]);
|
||||
|
||||
// ── Command handlers ──
|
||||
const handleUseDevPreset = useCallback((command: string) => {
|
||||
setDevCommand(command);
|
||||
}, []);
|
||||
|
||||
const handleUseTestPreset = useCallback((command: string) => {
|
||||
setTestCommand(command);
|
||||
}, []);
|
||||
|
||||
const handleClearDev = useCallback(() => {
|
||||
setDevCommand('');
|
||||
}, []);
|
||||
|
||||
const handleClearTest = useCallback(() => {
|
||||
setTestCommand('');
|
||||
}, []);
|
||||
|
||||
// ── Script handlers ──
|
||||
const handleAddScript = useCallback(() => {
|
||||
setScripts((prev) => [...prev, { id: generateId(), name: '', command: '' }]);
|
||||
}, []);
|
||||
|
||||
const handleAddPreset = useCallback((preset: { name: string; command: string }) => {
|
||||
setScripts((prev) => [
|
||||
...prev,
|
||||
{ id: generateId(), name: preset.name, command: preset.command },
|
||||
]);
|
||||
}, []);
|
||||
|
||||
const handleRemoveScript = useCallback((index: number) => {
|
||||
setScripts((prev) => prev.filter((_, i) => i !== index));
|
||||
}, []);
|
||||
|
||||
const handleUpdateScript = useCallback(
|
||||
(index: number, field: 'name' | 'command', value: string) => {
|
||||
setScripts((prev) => prev.map((s, i) => (i === index ? { ...s, [field]: value } : s)));
|
||||
},
|
||||
[]
|
||||
);
|
||||
|
||||
// Handle keyboard shortcuts (Enter to save)
|
||||
const handleKeyDown = useCallback(
|
||||
(e: KeyboardEvent<HTMLInputElement>) => {
|
||||
if (e.key === 'Enter' && hasChanges && !isSaving) {
|
||||
e.preventDefault();
|
||||
handleSave();
|
||||
}
|
||||
},
|
||||
[hasChanges, isSaving, handleSave]
|
||||
);
|
||||
|
||||
// ── Drag and drop handlers for script reordering ──
|
||||
const handleDragStart = useCallback((index: number) => {
|
||||
setDraggedIndex(index);
|
||||
}, []);
|
||||
|
||||
const handleDragOver = useCallback(
|
||||
(e: React.DragEvent, index: number) => {
|
||||
e.preventDefault();
|
||||
if (draggedIndex === null || draggedIndex === index) return;
|
||||
setDragOverIndex(index);
|
||||
},
|
||||
[draggedIndex]
|
||||
);
|
||||
|
||||
const handleDrop = useCallback(
|
||||
(e: React.DragEvent) => {
|
||||
e.preventDefault();
|
||||
if (draggedIndex !== null && dragOverIndex !== null && draggedIndex !== dragOverIndex) {
|
||||
setScripts((prev) => {
|
||||
const newScripts = [...prev];
|
||||
const [removed] = newScripts.splice(draggedIndex, 1);
|
||||
newScripts.splice(dragOverIndex, 0, removed);
|
||||
return newScripts;
|
||||
});
|
||||
}
|
||||
setDraggedIndex(null);
|
||||
setDragOverIndex(null);
|
||||
},
|
||||
[draggedIndex, dragOverIndex]
|
||||
);
|
||||
|
||||
const handleDragEnd = useCallback((_e: React.DragEvent) => {
|
||||
setDraggedIndex(null);
|
||||
setDragOverIndex(null);
|
||||
}, []);
|
||||
|
||||
// ── Keyboard reorder helpers for accessibility ──
|
||||
const moveScript = useCallback((fromIndex: number, toIndex: number) => {
|
||||
setScripts((prev) => {
|
||||
if (toIndex < 0 || toIndex >= prev.length) return prev;
|
||||
const newScripts = [...prev];
|
||||
const [removed] = newScripts.splice(fromIndex, 1);
|
||||
newScripts.splice(toIndex, 0, removed);
|
||||
return newScripts;
|
||||
});
|
||||
}, []);
|
||||
|
||||
const handleDragHandleKeyDown = useCallback(
|
||||
(e: React.KeyboardEvent, index: number) => {
|
||||
if (e.key === 'ArrowUp') {
|
||||
e.preventDefault();
|
||||
moveScript(index, index - 1);
|
||||
} else if (e.key === 'ArrowDown') {
|
||||
e.preventDefault();
|
||||
moveScript(index, index + 1);
|
||||
} else if (e.key === 'Home') {
|
||||
e.preventDefault();
|
||||
moveScript(index, 0);
|
||||
} else if (e.key === 'End') {
|
||||
e.preventDefault();
|
||||
moveScript(index, scripts.length - 1);
|
||||
}
|
||||
},
|
||||
[moveScript, scripts.length]
|
||||
);
|
||||
|
||||
return (
|
||||
<div className="space-y-6">
|
||||
{/* ── Commands Card ── */}
|
||||
<div
|
||||
className={cn(
|
||||
'rounded-2xl overflow-hidden',
|
||||
'border border-border/50',
|
||||
'bg-gradient-to-br from-card/90 via-card/70 to-card/80 backdrop-blur-xl',
|
||||
'shadow-sm shadow-black/5'
|
||||
)}
|
||||
data-testid="commands-section"
|
||||
>
|
||||
<div className="p-6 border-b border-border/50 bg-gradient-to-r from-transparent via-accent/5 to-transparent">
|
||||
<div className="flex items-center gap-3 mb-2">
|
||||
<div className="w-9 h-9 rounded-xl bg-gradient-to-br from-brand-500/20 to-brand-600/10 flex items-center justify-center border border-brand-500/20">
|
||||
<Terminal className="w-5 h-5 text-brand-500" />
|
||||
</div>
|
||||
<h2 className="text-lg font-semibold text-foreground tracking-tight">
|
||||
Project Commands
|
||||
</h2>
|
||||
</div>
|
||||
<p className="text-sm text-muted-foreground/80 ml-12">
|
||||
Configure custom commands for development and testing.
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<div className="p-6 space-y-8">
|
||||
{isLoading ? (
|
||||
<div className="flex items-center justify-center py-8">
|
||||
<Spinner size="md" />
|
||||
</div>
|
||||
) : isError ? (
|
||||
<div className="flex items-center justify-center py-8 text-sm text-destructive">
|
||||
Failed to load project settings. Please try again.
|
||||
</div>
|
||||
) : (
|
||||
<>
|
||||
{/* Dev Server Command Section */}
|
||||
<div className="space-y-4">
|
||||
<div className="flex items-center gap-2">
|
||||
<Play className="w-4 h-4 text-brand-500" />
|
||||
<h3 className="text-base font-medium text-foreground">Dev Server</h3>
|
||||
{hasDevChanges && (
|
||||
<span className="text-xs text-amber-500 font-medium">(unsaved)</span>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<div className="space-y-3 pl-6">
|
||||
<div className="relative">
|
||||
<Input
|
||||
id="dev-command"
|
||||
value={devCommand}
|
||||
onChange={(e) => setDevCommand(e.target.value)}
|
||||
onKeyDown={handleKeyDown}
|
||||
placeholder="e.g., npm run dev, yarn dev, cargo watch"
|
||||
className="font-mono text-sm pr-8"
|
||||
data-testid="dev-command-input"
|
||||
/>
|
||||
{devCommand && (
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
onClick={handleClearDev}
|
||||
className="absolute right-1 top-1/2 -translate-y-1/2 h-6 w-6 p-0 text-muted-foreground hover:text-foreground"
|
||||
aria-label="Clear dev command"
|
||||
>
|
||||
<X className="w-3.5 h-3.5" />
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
<p className="text-xs text-muted-foreground/80">
|
||||
Leave empty to auto-detect based on your package manager.
|
||||
</p>
|
||||
|
||||
{/* Dev Presets */}
|
||||
<div className="flex flex-wrap gap-1.5">
|
||||
{DEV_SERVER_PRESETS.map((preset) => (
|
||||
<Button
|
||||
key={preset.command}
|
||||
variant="outline"
|
||||
size="sm"
|
||||
onClick={() => handleUseDevPreset(preset.command)}
|
||||
className="text-xs font-mono h-7 px-2"
|
||||
>
|
||||
{preset.label}
|
||||
</Button>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Divider */}
|
||||
<div className="border-t border-border/30" />
|
||||
|
||||
{/* Test Command Section */}
|
||||
<div className="space-y-4">
|
||||
<div className="flex items-center gap-2">
|
||||
<FlaskConical className="w-4 h-4 text-brand-500" />
|
||||
<h3 className="text-base font-medium text-foreground">Test Runner</h3>
|
||||
{hasTestChanges && (
|
||||
<span className="text-xs text-amber-500 font-medium">(unsaved)</span>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<div className="space-y-3 pl-6">
|
||||
<div className="relative">
|
||||
<Input
|
||||
id="test-command"
|
||||
value={testCommand}
|
||||
onChange={(e) => setTestCommand(e.target.value)}
|
||||
onKeyDown={handleKeyDown}
|
||||
placeholder="e.g., npm test, pytest, cargo test"
|
||||
className="font-mono text-sm pr-8"
|
||||
data-testid="test-command-input"
|
||||
/>
|
||||
{testCommand && (
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
onClick={handleClearTest}
|
||||
className="absolute right-1 top-1/2 -translate-y-1/2 h-6 w-6 p-0 text-muted-foreground hover:text-foreground"
|
||||
aria-label="Clear test command"
|
||||
>
|
||||
<X className="w-3.5 h-3.5" />
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
<p className="text-xs text-muted-foreground/80">
|
||||
Leave empty to auto-detect based on your project structure.
|
||||
</p>
|
||||
|
||||
{/* Test Presets */}
|
||||
<div className="flex flex-wrap gap-1.5">
|
||||
{TEST_PRESETS.map((preset) => (
|
||||
<Button
|
||||
key={preset.command}
|
||||
variant="outline"
|
||||
size="sm"
|
||||
onClick={() => handleUseTestPreset(preset.command)}
|
||||
className="text-xs font-mono h-7 px-2"
|
||||
>
|
||||
{preset.label}
|
||||
</Button>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Auto-detection Info */}
|
||||
<div className="flex items-start gap-3 p-3 rounded-lg bg-accent/20 border border-border/30">
|
||||
<Info className="w-4 h-4 text-brand-500 mt-0.5 shrink-0" />
|
||||
<div className="text-xs text-muted-foreground">
|
||||
<p className="font-medium text-foreground mb-1">Auto-detection</p>
|
||||
<p>
|
||||
When no custom command is set, the system automatically detects your package
|
||||
manager and test framework based on project files (package.json, Cargo.toml,
|
||||
go.mod, etc.).
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* ── Terminal Quick Scripts Card ── */}
|
||||
<div
|
||||
className={cn(
|
||||
'rounded-2xl overflow-hidden',
|
||||
'border border-border/50',
|
||||
'bg-gradient-to-br from-card/90 via-card/70 to-card/80 backdrop-blur-xl',
|
||||
'shadow-sm shadow-black/5'
|
||||
)}
|
||||
data-testid="scripts-section"
|
||||
>
|
||||
{/* Header */}
|
||||
<div className="p-6 border-b border-border/50 bg-gradient-to-r from-transparent via-accent/5 to-transparent">
|
||||
<div className="flex items-center gap-3 mb-2">
|
||||
<div className="w-9 h-9 rounded-xl bg-gradient-to-br from-brand-500/20 to-brand-600/10 flex items-center justify-center border border-brand-500/20">
|
||||
<ScrollText className="w-5 h-5 text-brand-500" />
|
||||
</div>
|
||||
<h2 className="text-lg font-semibold text-foreground tracking-tight">
|
||||
Terminal Quick Scripts
|
||||
</h2>
|
||||
</div>
|
||||
<p className="text-sm text-muted-foreground/80 ml-12">
|
||||
Configure quick-access scripts that appear in the terminal header dropdown. Click any
|
||||
script to run it instantly.
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<div className="p-6 space-y-6">
|
||||
{isLoading ? (
|
||||
<div className="flex items-center justify-center py-8">
|
||||
<Spinner size="md" />
|
||||
</div>
|
||||
) : isError ? (
|
||||
<div className="flex items-center justify-center py-8 text-sm text-destructive">
|
||||
Failed to load project settings. Please try again.
|
||||
</div>
|
||||
) : (
|
||||
<>
|
||||
{/* Scripts List */}
|
||||
<div className="space-y-2">
|
||||
{scripts.map((script, index) => (
|
||||
<div
|
||||
key={script.id}
|
||||
className={cn(
|
||||
'flex items-center gap-2 p-2 rounded-lg border border-border/30 bg-accent/10 transition-all',
|
||||
draggedIndex === index && 'opacity-50',
|
||||
dragOverIndex === index && 'border-brand-500/50 bg-brand-500/5'
|
||||
)}
|
||||
draggable
|
||||
onDragStart={() => handleDragStart(index)}
|
||||
onDragOver={(e) => handleDragOver(e, index)}
|
||||
onDrop={(e) => handleDrop(e)}
|
||||
onDragEnd={(e) => handleDragEnd(e)}
|
||||
>
|
||||
{/* Drag handle - keyboard accessible */}
|
||||
<div
|
||||
className="cursor-grab active:cursor-grabbing text-muted-foreground hover:text-foreground focus:text-foreground focus:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-1 rounded shrink-0 p-0.5"
|
||||
title="Drag to reorder (or use Arrow keys)"
|
||||
tabIndex={0}
|
||||
role="button"
|
||||
aria-label={`Reorder ${script.name || 'script'}. Use arrow keys to move.`}
|
||||
onKeyDown={(e) => handleDragHandleKeyDown(e, index)}
|
||||
>
|
||||
<GripVertical className="w-4 h-4" />
|
||||
</div>
|
||||
|
||||
{/* Script name */}
|
||||
<Input
|
||||
value={script.name}
|
||||
onChange={(e) => handleUpdateScript(index, 'name', e.target.value)}
|
||||
onKeyDown={handleKeyDown}
|
||||
placeholder="Script name"
|
||||
className="h-8 text-sm flex-[0.4] min-w-0"
|
||||
/>
|
||||
|
||||
{/* Script command */}
|
||||
<Input
|
||||
value={script.command}
|
||||
onChange={(e) => handleUpdateScript(index, 'command', e.target.value)}
|
||||
onKeyDown={handleKeyDown}
|
||||
placeholder="Command to run"
|
||||
className="h-8 text-sm font-mono flex-[0.6] min-w-0"
|
||||
/>
|
||||
|
||||
{/* Remove button */}
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
onClick={() => handleRemoveScript(index)}
|
||||
className="h-8 w-8 p-0 text-muted-foreground hover:text-destructive shrink-0"
|
||||
aria-label={`Remove ${script.name || 'script'}`}
|
||||
>
|
||||
<Trash2 className="w-3.5 h-3.5" />
|
||||
</Button>
|
||||
</div>
|
||||
))}
|
||||
|
||||
{scripts.length === 0 && (
|
||||
<div className="text-center py-6 text-sm text-muted-foreground">
|
||||
No scripts configured. Add some below or use a preset.
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* Add Script Button */}
|
||||
<Button variant="outline" size="sm" onClick={handleAddScript} className="gap-1.5">
|
||||
<Plus className="w-3.5 h-3.5" />
|
||||
Add Script
|
||||
</Button>
|
||||
|
||||
{/* Divider */}
|
||||
<div className="border-t border-border/30" />
|
||||
|
||||
{/* Presets */}
|
||||
<div className="space-y-3">
|
||||
<h3 className="text-sm font-medium text-foreground">Quick Add Presets</h3>
|
||||
<div className="flex flex-wrap gap-1.5">
|
||||
{SCRIPT_PRESETS.map((preset) => (
|
||||
<Button
|
||||
key={preset.command}
|
||||
variant="outline"
|
||||
size="sm"
|
||||
onClick={() => handleAddPreset(preset)}
|
||||
className="text-xs font-mono h-7 px-2"
|
||||
>
|
||||
{preset.command}
|
||||
</Button>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Info Box */}
|
||||
<div className="flex items-start gap-3 p-3 rounded-lg bg-accent/20 border border-border/30">
|
||||
<Info className="w-4 h-4 text-brand-500 mt-0.5 shrink-0" />
|
||||
<div className="text-xs text-muted-foreground">
|
||||
<p className="font-medium text-foreground mb-1">Terminal Quick Scripts</p>
|
||||
<p>
|
||||
These scripts appear in the terminal header as a dropdown menu (the{' '}
|
||||
<ScrollText className="inline-block w-3 h-3 mx-0.5 align-middle" /> icon).
|
||||
Clicking a script will type the command into the active terminal and press
|
||||
Enter. Drag to reorder scripts.
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* ── Shared Action Buttons ── */}
|
||||
<div className="flex items-center justify-end gap-2">
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
onClick={handleReset}
|
||||
disabled={!hasChanges || isSaving}
|
||||
className="gap-1.5"
|
||||
>
|
||||
<RotateCcw className="w-3.5 h-3.5" />
|
||||
Reset
|
||||
</Button>
|
||||
<Button
|
||||
size="sm"
|
||||
onClick={handleSave}
|
||||
disabled={!hasChanges || isSaving}
|
||||
className="gap-1.5"
|
||||
>
|
||||
{isSaving ? <Spinner size="xs" /> : <Save className="w-3.5 h-3.5" />}
|
||||
Save
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -7,7 +7,6 @@ import {
|
||||
Workflow,
|
||||
Database,
|
||||
Terminal,
|
||||
ScrollText,
|
||||
} from 'lucide-react';
|
||||
import type { ProjectSettingsViewId } from '../hooks/use-project-settings-view';
|
||||
|
||||
@@ -20,8 +19,7 @@ export interface ProjectNavigationItem {
|
||||
export const PROJECT_SETTINGS_NAV_ITEMS: ProjectNavigationItem[] = [
|
||||
{ id: 'identity', label: 'Identity', icon: User },
|
||||
{ id: 'worktrees', label: 'Worktrees', icon: GitBranch },
|
||||
{ id: 'commands', label: 'Commands', icon: Terminal },
|
||||
{ id: 'scripts', label: 'Terminal Scripts', icon: ScrollText },
|
||||
{ id: 'commands-scripts', label: 'Commands & Scripts', icon: Terminal },
|
||||
{ id: 'theme', label: 'Theme', icon: Palette },
|
||||
{ id: 'claude', label: 'Models', icon: Workflow },
|
||||
{ id: 'data', label: 'Data', icon: Database },
|
||||
|
||||
@@ -6,6 +6,7 @@ export type ProjectSettingsViewId =
|
||||
| 'worktrees'
|
||||
| 'commands'
|
||||
| 'scripts'
|
||||
| 'commands-scripts'
|
||||
| 'claude'
|
||||
| 'data'
|
||||
| 'danger';
|
||||
|
||||
@@ -2,6 +2,8 @@ export { ProjectSettingsView } from './project-settings-view';
|
||||
export { ProjectIdentitySection } from './project-identity-section';
|
||||
export { ProjectThemeSection } from './project-theme-section';
|
||||
export { WorktreePreferencesSection } from './worktree-preferences-section';
|
||||
export { CommandsAndScriptsSection } from './commands-and-scripts-section';
|
||||
// Legacy exports kept for backward compatibility
|
||||
export { CommandsSection } from './commands-section';
|
||||
export { TerminalScriptsSection } from './terminal-scripts-section';
|
||||
export { useProjectSettingsView, type ProjectSettingsViewId } from './hooks';
|
||||
|
||||
@@ -5,8 +5,7 @@ import { Button } from '@/components/ui/button';
|
||||
import { ProjectIdentitySection } from './project-identity-section';
|
||||
import { ProjectThemeSection } from './project-theme-section';
|
||||
import { WorktreePreferencesSection } from './worktree-preferences-section';
|
||||
import { CommandsSection } from './commands-section';
|
||||
import { TerminalScriptsSection } from './terminal-scripts-section';
|
||||
import { CommandsAndScriptsSection } from './commands-and-scripts-section';
|
||||
import { ProjectModelsSection } from './project-models-section';
|
||||
import { DataManagementSection } from './data-management-section';
|
||||
import { DangerZoneSection } from '../settings-view/danger-zone/danger-zone-section';
|
||||
@@ -15,6 +14,8 @@ import { RemoveFromAutomakerDialog } from '../settings-view/components/remove-fr
|
||||
import { ProjectSettingsNavigation } from './components/project-settings-navigation';
|
||||
import { useProjectSettingsView } from './hooks/use-project-settings-view';
|
||||
import type { Project as ElectronProject } from '@/lib/electron';
|
||||
import { useSearch } from '@tanstack/react-router';
|
||||
import type { ProjectSettingsViewId } from './hooks/use-project-settings-view';
|
||||
|
||||
// Breakpoint constant for mobile (matches Tailwind lg breakpoint)
|
||||
const LG_BREAKPOINT = 1024;
|
||||
@@ -34,8 +35,18 @@ export function ProjectSettingsView() {
|
||||
const [showDeleteDialog, setShowDeleteDialog] = useState(false);
|
||||
const [showRemoveFromAutomakerDialog, setShowRemoveFromAutomakerDialog] = useState(false);
|
||||
|
||||
// Read the optional section search param to support deep-linking to a specific section
|
||||
const search = useSearch({ strict: false }) as { section?: ProjectSettingsViewId };
|
||||
// Map legacy 'commands' and 'scripts' IDs to the combined 'commands-scripts' section
|
||||
const resolvedSection: ProjectSettingsViewId | undefined =
|
||||
search.section === 'commands' || search.section === 'scripts'
|
||||
? 'commands-scripts'
|
||||
: search.section;
|
||||
|
||||
// Use project settings view navigation hook
|
||||
const { activeView, navigateTo } = useProjectSettingsView();
|
||||
const { activeView, navigateTo } = useProjectSettingsView({
|
||||
initialView: resolvedSection ?? 'identity',
|
||||
});
|
||||
|
||||
// Mobile navigation state - default to showing on desktop, hidden on mobile
|
||||
const [showNavigation, setShowNavigation] = useState(() => {
|
||||
@@ -91,9 +102,9 @@ export function ProjectSettingsView() {
|
||||
case 'worktrees':
|
||||
return <WorktreePreferencesSection project={currentProject} />;
|
||||
case 'commands':
|
||||
return <CommandsSection project={currentProject} />;
|
||||
case 'scripts':
|
||||
return <TerminalScriptsSection project={currentProject} />;
|
||||
case 'commands-scripts':
|
||||
return <CommandsAndScriptsSection project={currentProject} />;
|
||||
case 'claude':
|
||||
return <ProjectModelsSection project={currentProject} />;
|
||||
case 'data':
|
||||
|
||||
@@ -63,6 +63,8 @@ export function SettingsView() {
|
||||
setPromptCustomization,
|
||||
skipSandboxWarning,
|
||||
setSkipSandboxWarning,
|
||||
defaultMaxTurns,
|
||||
setDefaultMaxTurns,
|
||||
} = useAppStore();
|
||||
|
||||
// Global theme (project-specific themes are managed in Project Settings)
|
||||
@@ -173,6 +175,7 @@ export function SettingsView() {
|
||||
defaultRequirePlanApproval={defaultRequirePlanApproval}
|
||||
enableAiCommitMessages={enableAiCommitMessages}
|
||||
defaultFeatureModel={defaultFeatureModel}
|
||||
defaultMaxTurns={defaultMaxTurns}
|
||||
onDefaultSkipTestsChange={setDefaultSkipTests}
|
||||
onEnableDependencyBlockingChange={setEnableDependencyBlocking}
|
||||
onSkipVerificationInAutoModeChange={setSkipVerificationInAutoMode}
|
||||
@@ -180,6 +183,7 @@ export function SettingsView() {
|
||||
onDefaultRequirePlanApprovalChange={setDefaultRequirePlanApproval}
|
||||
onEnableAiCommitMessagesChange={setEnableAiCommitMessages}
|
||||
onDefaultFeatureModelChange={setDefaultFeatureModel}
|
||||
onDefaultMaxTurnsChange={setDefaultMaxTurns}
|
||||
/>
|
||||
);
|
||||
case 'worktrees':
|
||||
|
||||
@@ -9,6 +9,10 @@ import type { EventHook, EventHookTrigger } from '@automaker/types';
|
||||
import { EVENT_HOOK_TRIGGER_LABELS } from '@automaker/types';
|
||||
import { EventHookDialog } from './event-hook-dialog';
|
||||
import { EventHistoryView } from './event-history-view';
|
||||
import { toast } from 'sonner';
|
||||
import { createLogger } from '@automaker/utils/logger';
|
||||
|
||||
const logger = createLogger('EventHooks');
|
||||
|
||||
export function EventHooksSection() {
|
||||
const { eventHooks, setEventHooks } = useAppStore();
|
||||
@@ -26,24 +30,39 @@ export function EventHooksSection() {
|
||||
setDialogOpen(true);
|
||||
};
|
||||
|
||||
const handleDeleteHook = (hookId: string) => {
|
||||
setEventHooks(eventHooks.filter((h) => h.id !== hookId));
|
||||
};
|
||||
|
||||
const handleToggleHook = (hookId: string, enabled: boolean) => {
|
||||
setEventHooks(eventHooks.map((h) => (h.id === hookId ? { ...h, enabled } : h)));
|
||||
};
|
||||
|
||||
const handleSaveHook = (hook: EventHook) => {
|
||||
if (editingHook) {
|
||||
// Update existing
|
||||
setEventHooks(eventHooks.map((h) => (h.id === hook.id ? hook : h)));
|
||||
} else {
|
||||
// Add new
|
||||
setEventHooks([...eventHooks, hook]);
|
||||
const handleDeleteHook = async (hookId: string) => {
|
||||
try {
|
||||
await setEventHooks(eventHooks.filter((h) => h.id !== hookId));
|
||||
} catch (error) {
|
||||
logger.error('Failed to delete event hook:', error);
|
||||
toast.error('Failed to delete event hook');
|
||||
}
|
||||
};
|
||||
|
||||
const handleToggleHook = async (hookId: string, enabled: boolean) => {
|
||||
try {
|
||||
await setEventHooks(eventHooks.map((h) => (h.id === hookId ? { ...h, enabled } : h)));
|
||||
} catch (error) {
|
||||
logger.error('Failed to toggle event hook:', error);
|
||||
toast.error('Failed to update event hook');
|
||||
}
|
||||
};
|
||||
|
||||
const handleSaveHook = async (hook: EventHook) => {
|
||||
try {
|
||||
if (editingHook) {
|
||||
// Update existing
|
||||
await setEventHooks(eventHooks.map((h) => (h.id === hook.id ? hook : h)));
|
||||
} else {
|
||||
// Add new
|
||||
await setEventHooks([...eventHooks, hook]);
|
||||
}
|
||||
setDialogOpen(false);
|
||||
setEditingHook(null);
|
||||
} catch (error) {
|
||||
logger.error('Failed to save event hook:', error);
|
||||
toast.error('Failed to save event hook');
|
||||
}
|
||||
setDialogOpen(false);
|
||||
setEditingHook(null);
|
||||
};
|
||||
|
||||
// Group hooks by trigger type for better organization
|
||||
|
||||
@@ -1,5 +1,7 @@
|
||||
import { useState, useEffect } from 'react';
|
||||
import { Label } from '@/components/ui/label';
|
||||
import { Checkbox } from '@/components/ui/checkbox';
|
||||
import { Input } from '@/components/ui/input';
|
||||
import {
|
||||
FlaskConical,
|
||||
TestTube,
|
||||
@@ -12,6 +14,7 @@ import {
|
||||
FastForward,
|
||||
Sparkles,
|
||||
Cpu,
|
||||
RotateCcw,
|
||||
} from 'lucide-react';
|
||||
import { cn } from '@/lib/utils';
|
||||
import {
|
||||
@@ -34,6 +37,7 @@ interface FeatureDefaultsSectionProps {
|
||||
defaultRequirePlanApproval: boolean;
|
||||
enableAiCommitMessages: boolean;
|
||||
defaultFeatureModel: PhaseModelEntry;
|
||||
defaultMaxTurns: number;
|
||||
onDefaultSkipTestsChange: (value: boolean) => void;
|
||||
onEnableDependencyBlockingChange: (value: boolean) => void;
|
||||
onSkipVerificationInAutoModeChange: (value: boolean) => void;
|
||||
@@ -41,6 +45,7 @@ interface FeatureDefaultsSectionProps {
|
||||
onDefaultRequirePlanApprovalChange: (value: boolean) => void;
|
||||
onEnableAiCommitMessagesChange: (value: boolean) => void;
|
||||
onDefaultFeatureModelChange: (value: PhaseModelEntry) => void;
|
||||
onDefaultMaxTurnsChange: (value: number) => void;
|
||||
}
|
||||
|
||||
export function FeatureDefaultsSection({
|
||||
@@ -51,6 +56,7 @@ export function FeatureDefaultsSection({
|
||||
defaultRequirePlanApproval,
|
||||
enableAiCommitMessages,
|
||||
defaultFeatureModel,
|
||||
defaultMaxTurns,
|
||||
onDefaultSkipTestsChange,
|
||||
onEnableDependencyBlockingChange,
|
||||
onSkipVerificationInAutoModeChange,
|
||||
@@ -58,7 +64,16 @@ export function FeatureDefaultsSection({
|
||||
onDefaultRequirePlanApprovalChange,
|
||||
onEnableAiCommitMessagesChange,
|
||||
onDefaultFeatureModelChange,
|
||||
onDefaultMaxTurnsChange,
|
||||
}: FeatureDefaultsSectionProps) {
|
||||
const [maxTurnsInput, setMaxTurnsInput] = useState(String(defaultMaxTurns));
|
||||
|
||||
// Keep the displayed input in sync if the prop changes after mount
|
||||
// (e.g. when settings are loaded asynchronously or reset from parent)
|
||||
useEffect(() => {
|
||||
setMaxTurnsInput(String(defaultMaxTurns));
|
||||
}, [defaultMaxTurns]);
|
||||
|
||||
return (
|
||||
<div
|
||||
className={cn(
|
||||
@@ -104,6 +119,55 @@ export function FeatureDefaultsSection({
|
||||
{/* Separator */}
|
||||
<div className="border-t border-border/30" />
|
||||
|
||||
{/* Max Turns Setting */}
|
||||
<div className="group flex items-start space-x-3 p-3 rounded-xl hover:bg-accent/30 transition-colors duration-200 -mx-3">
|
||||
<div className="w-10 h-10 mt-0.5 rounded-xl flex items-center justify-center shrink-0 bg-orange-500/10">
|
||||
<RotateCcw className="w-5 h-5 text-orange-500" />
|
||||
</div>
|
||||
<div className="flex-1 space-y-2">
|
||||
<div className="flex items-center justify-between">
|
||||
<Label htmlFor="default-max-turns" className="text-foreground font-medium">
|
||||
Max Agent Turns
|
||||
</Label>
|
||||
<Input
|
||||
id="default-max-turns"
|
||||
type="number"
|
||||
min={1}
|
||||
max={2000}
|
||||
step={1}
|
||||
value={maxTurnsInput}
|
||||
onChange={(e) => {
|
||||
setMaxTurnsInput(e.target.value);
|
||||
}}
|
||||
onBlur={() => {
|
||||
const value = Number(maxTurnsInput);
|
||||
if (Number.isInteger(value) && value >= 1 && value <= 2000) {
|
||||
onDefaultMaxTurnsChange(value);
|
||||
} else {
|
||||
// Reset to current valid value if invalid (including decimals like "1.5")
|
||||
setMaxTurnsInput(String(defaultMaxTurns));
|
||||
}
|
||||
}}
|
||||
onKeyDown={(e) => {
|
||||
if (e.key === 'Enter') {
|
||||
(e.target as HTMLInputElement).blur();
|
||||
}
|
||||
}}
|
||||
className="w-[100px] h-8 text-right"
|
||||
data-testid="default-max-turns-input"
|
||||
/>
|
||||
</div>
|
||||
<p className="text-xs text-muted-foreground/80 leading-relaxed">
|
||||
Maximum number of tool-call round-trips the AI agent can perform per feature. Higher
|
||||
values allow more complex tasks but use more API credits. Default: 1000, Range:
|
||||
1-2000. Supported by Claude and Codex providers.
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Separator */}
|
||||
<div className="border-t border-border/30" />
|
||||
|
||||
{/* Planning Mode Default */}
|
||||
<div className="group flex items-start space-x-3 p-3 rounded-xl hover:bg-accent/30 transition-colors duration-200 -mx-3">
|
||||
<div
|
||||
|
||||
@@ -16,6 +16,9 @@ import {
|
||||
Terminal,
|
||||
SquarePlus,
|
||||
SplitSquareHorizontal,
|
||||
Palette,
|
||||
Type,
|
||||
X,
|
||||
} from 'lucide-react';
|
||||
import { cn } from '@/lib/utils';
|
||||
import { useAppStore } from '@/store/app-store';
|
||||
@@ -38,6 +41,8 @@ export function TerminalSection() {
|
||||
defaultTerminalId,
|
||||
setDefaultTerminalId,
|
||||
setOpenTerminalMode,
|
||||
setTerminalBackgroundColor,
|
||||
setTerminalForegroundColor,
|
||||
} = useAppStore();
|
||||
|
||||
const {
|
||||
@@ -48,6 +53,8 @@ export function TerminalSection() {
|
||||
lineHeight,
|
||||
defaultFontSize,
|
||||
openTerminalMode,
|
||||
customBackgroundColor,
|
||||
customForegroundColor,
|
||||
} = terminalState;
|
||||
|
||||
// Get available external terminals
|
||||
@@ -205,6 +212,138 @@ export function TerminalSection() {
|
||||
</Select>
|
||||
</div>
|
||||
|
||||
{/* Background Color */}
|
||||
<div className="space-y-3">
|
||||
<div className="flex items-center justify-between">
|
||||
<Label className="text-foreground font-medium">Background Color</Label>
|
||||
{customBackgroundColor && (
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
className="h-7 px-2 text-xs text-muted-foreground hover:text-foreground"
|
||||
onClick={() => {
|
||||
setTerminalBackgroundColor(null);
|
||||
toast.success('Background color reset to theme default');
|
||||
}}
|
||||
>
|
||||
<X className="w-3 h-3 mr-1" />
|
||||
Reset
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
<p className="text-xs text-muted-foreground">
|
||||
Override the terminal background color. Leave empty to use the theme default.
|
||||
</p>
|
||||
<div className="flex items-center gap-3">
|
||||
<div className="flex items-center gap-2 flex-1">
|
||||
<div
|
||||
className="w-10 h-10 rounded-lg border border-border/50 shadow-sm flex items-center justify-center"
|
||||
style={{
|
||||
backgroundColor: customBackgroundColor || 'var(--card)',
|
||||
}}
|
||||
>
|
||||
<Palette
|
||||
className={cn(
|
||||
'w-5 h-5',
|
||||
customBackgroundColor ? 'text-white/80' : 'text-muted-foreground'
|
||||
)}
|
||||
/>
|
||||
</div>
|
||||
<Input
|
||||
type="color"
|
||||
value={customBackgroundColor || '#000000'}
|
||||
onChange={(e) => {
|
||||
const color = e.target.value;
|
||||
setTerminalBackgroundColor(color);
|
||||
}}
|
||||
className="w-14 h-10 p-1 cursor-pointer bg-transparent border-border/50"
|
||||
title="Pick a color"
|
||||
/>
|
||||
<Input
|
||||
type="text"
|
||||
value={customBackgroundColor || ''}
|
||||
onChange={(e) => {
|
||||
const value = e.target.value;
|
||||
// Validate hex color format
|
||||
if (value === '' || /^#[0-9A-Fa-f]{0,6}$/.test(value)) {
|
||||
if (value === '' || /^#[0-9A-Fa-f]{6}$/.test(value)) {
|
||||
setTerminalBackgroundColor(value || null);
|
||||
}
|
||||
}
|
||||
}}
|
||||
placeholder="e.g., #1a1a1a"
|
||||
className="flex-1 bg-accent/30 border-border/50 font-mono text-sm"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Foreground Color */}
|
||||
<div className="space-y-3">
|
||||
<div className="flex items-center justify-between">
|
||||
<Label className="text-foreground font-medium">Foreground Color</Label>
|
||||
{customForegroundColor && (
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
className="h-7 px-2 text-xs text-muted-foreground hover:text-foreground"
|
||||
onClick={() => {
|
||||
setTerminalForegroundColor(null);
|
||||
toast.success('Foreground color reset to theme default');
|
||||
}}
|
||||
>
|
||||
<X className="w-3 h-3 mr-1" />
|
||||
Reset
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
<p className="text-xs text-muted-foreground">
|
||||
Override the terminal text/foreground color. Leave empty to use the theme default.
|
||||
</p>
|
||||
<div className="flex items-center gap-3">
|
||||
<div className="flex items-center gap-2 flex-1">
|
||||
<div
|
||||
className="w-10 h-10 rounded-lg border border-border/50 shadow-sm flex items-center justify-center"
|
||||
style={{
|
||||
backgroundColor: customForegroundColor || 'var(--foreground)',
|
||||
}}
|
||||
>
|
||||
<Type
|
||||
className={cn(
|
||||
'w-5 h-5',
|
||||
customForegroundColor ? 'text-black/80' : 'text-background'
|
||||
)}
|
||||
/>
|
||||
</div>
|
||||
<Input
|
||||
type="color"
|
||||
value={customForegroundColor || '#ffffff'}
|
||||
onChange={(e) => {
|
||||
const color = e.target.value;
|
||||
setTerminalForegroundColor(color);
|
||||
}}
|
||||
className="w-14 h-10 p-1 cursor-pointer bg-transparent border-border/50"
|
||||
title="Pick a color"
|
||||
/>
|
||||
<Input
|
||||
type="text"
|
||||
value={customForegroundColor || ''}
|
||||
onChange={(e) => {
|
||||
const value = e.target.value;
|
||||
// Validate hex color format
|
||||
if (value === '' || /^#[0-9A-Fa-f]{0,6}$/.test(value)) {
|
||||
if (value === '' || /^#[0-9A-Fa-f]{6}$/.test(value)) {
|
||||
setTerminalForegroundColor(value || null);
|
||||
}
|
||||
}
|
||||
}}
|
||||
placeholder="e.g., #ffffff"
|
||||
className="flex-1 bg-accent/30 border-border/50 font-mono text-sm"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Default Font Size */}
|
||||
<div className="space-y-3">
|
||||
<div className="flex items-center justify-between">
|
||||
|
||||
@@ -16,6 +16,9 @@ import {
|
||||
GitBranch,
|
||||
ChevronDown,
|
||||
FolderGit,
|
||||
Palette,
|
||||
RotateCcw,
|
||||
Type,
|
||||
} from 'lucide-react';
|
||||
import { Spinner } from '@/components/ui/spinner';
|
||||
import { getServerUrlSync } from '@/lib/http-api-client';
|
||||
@@ -240,9 +243,17 @@ interface TerminalViewProps {
|
||||
initialMode?: 'tab' | 'split';
|
||||
/** Unique nonce to allow opening the same worktree multiple times */
|
||||
nonce?: number;
|
||||
/** Command to run automatically when the terminal is created (e.g., from scripts submenu) */
|
||||
initialCommand?: string;
|
||||
}
|
||||
|
||||
export function TerminalView({ initialCwd, initialBranch, initialMode, nonce }: TerminalViewProps) {
|
||||
export function TerminalView({
|
||||
initialCwd,
|
||||
initialBranch,
|
||||
initialMode,
|
||||
nonce,
|
||||
initialCommand,
|
||||
}: TerminalViewProps) {
|
||||
const {
|
||||
terminalState,
|
||||
setTerminalUnlocked,
|
||||
@@ -268,6 +279,8 @@ export function TerminalView({ initialCwd, initialBranch, initialMode, nonce }:
|
||||
setTerminalLineHeight,
|
||||
setTerminalScrollbackLines,
|
||||
setTerminalScreenReaderMode,
|
||||
setTerminalBackgroundColor,
|
||||
setTerminalForegroundColor,
|
||||
updateTerminalPanelSizes,
|
||||
currentWorktreeByProject,
|
||||
worktreesByProject,
|
||||
@@ -288,6 +301,10 @@ export function TerminalView({ initialCwd, initialBranch, initialMode, nonce }:
|
||||
const isCreatingRef = useRef<boolean>(false);
|
||||
const restoringProjectPathRef = useRef<string | null>(null);
|
||||
const [newSessionIds, setNewSessionIds] = useState<Set<string>>(new Set());
|
||||
// Per-session command overrides (e.g., from scripts submenu), takes priority over defaultRunScript
|
||||
const [sessionCommandOverrides, setSessionCommandOverrides] = useState<Map<string, string>>(
|
||||
new Map()
|
||||
);
|
||||
const [serverSessionInfo, setServerSessionInfo] = useState<{
|
||||
current: number;
|
||||
max: number;
|
||||
@@ -576,7 +593,7 @@ export function TerminalView({ initialCwd, initialBranch, initialMode, nonce }:
|
||||
|
||||
// Skip if we've already handled this exact request (prevents duplicate terminals)
|
||||
// Include mode and nonce in the key to allow opening same cwd multiple times
|
||||
const cwdKey = `${initialCwd}:${initialMode || 'default'}:${nonce || 0}`;
|
||||
const cwdKey = `${initialCwd}:${initialMode || 'default'}:${nonce || 0}:${initialCommand || ''}`;
|
||||
if (initialCwdHandledRef.current === cwdKey) return;
|
||||
|
||||
// Skip if terminal is not enabled or not unlocked
|
||||
@@ -618,8 +635,12 @@ export function TerminalView({ initialCwd, initialBranch, initialMode, nonce }:
|
||||
}
|
||||
|
||||
// Mark this session as new for running initial command
|
||||
if (defaultRunScript) {
|
||||
if (initialCommand || defaultRunScript) {
|
||||
setNewSessionIds((prev) => new Set(prev).add(data.data.id));
|
||||
// Store per-session command override if an explicit command was provided
|
||||
if (initialCommand) {
|
||||
setSessionCommandOverrides((prev) => new Map(prev).set(data.data.id, initialCommand));
|
||||
}
|
||||
}
|
||||
|
||||
// Show success toast with branch name if provided
|
||||
@@ -654,6 +675,7 @@ export function TerminalView({ initialCwd, initialBranch, initialMode, nonce }:
|
||||
initialCwd,
|
||||
initialBranch,
|
||||
initialMode,
|
||||
initialCommand,
|
||||
nonce,
|
||||
status?.enabled,
|
||||
status?.passwordRequired,
|
||||
@@ -1059,7 +1081,12 @@ export function TerminalView({ initialCwd, initialBranch, initialMode, nonce }:
|
||||
// Create terminal in new tab
|
||||
// customCwd: optional working directory (e.g., a specific worktree path)
|
||||
// branchName: optional branch name to display in the terminal panel header
|
||||
const createTerminalInNewTab = async (customCwd?: string, branchName?: string) => {
|
||||
// command: optional command to run when the terminal connects (e.g., from scripts menu)
|
||||
const createTerminalInNewTab = async (
|
||||
customCwd?: string,
|
||||
branchName?: string,
|
||||
command?: string
|
||||
) => {
|
||||
if (!canCreateTerminal('[Terminal] Debounced terminal tab creation')) {
|
||||
return;
|
||||
}
|
||||
@@ -1087,8 +1114,12 @@ export function TerminalView({ initialCwd, initialBranch, initialMode, nonce }:
|
||||
const { addTerminalToTab } = useAppStore.getState();
|
||||
addTerminalToTab(data.data.id, tabId, undefined, worktreeBranch);
|
||||
// Mark this session as new for running initial command
|
||||
if (defaultRunScript) {
|
||||
if (command || defaultRunScript) {
|
||||
setNewSessionIds((prev) => new Set(prev).add(data.data.id));
|
||||
// Store per-session command override if an explicit command was provided
|
||||
if (command) {
|
||||
setSessionCommandOverrides((prev) => new Map(prev).set(data.data.id, command));
|
||||
}
|
||||
}
|
||||
// Refresh session count
|
||||
fetchServerSettings();
|
||||
@@ -1136,6 +1167,18 @@ export function TerminalView({ initialCwd, initialBranch, initialMode, nonce }:
|
||||
// Always remove from UI - even if server says 404 (session may have already exited)
|
||||
removeTerminalFromLayout(sessionId);
|
||||
|
||||
// Clean up stale entries for killed sessions
|
||||
setSessionCommandOverrides((prev) => {
|
||||
const next = new Map(prev);
|
||||
next.delete(sessionId);
|
||||
return next;
|
||||
});
|
||||
setNewSessionIds((prev) => {
|
||||
const next = new Set(prev);
|
||||
next.delete(sessionId);
|
||||
return next;
|
||||
});
|
||||
|
||||
if (!response.ok && response.status !== 404) {
|
||||
// Log non-404 errors but still proceed with UI cleanup
|
||||
const data = await response.json().catch(() => ({}));
|
||||
@@ -1148,6 +1191,17 @@ export function TerminalView({ initialCwd, initialBranch, initialMode, nonce }:
|
||||
logger.error('Kill session error:', err);
|
||||
// Still remove from UI on network error - better UX than leaving broken terminal
|
||||
removeTerminalFromLayout(sessionId);
|
||||
// Clean up stale entries for killed sessions (same cleanup as try block)
|
||||
setSessionCommandOverrides((prev) => {
|
||||
const next = new Map(prev);
|
||||
next.delete(sessionId);
|
||||
return next;
|
||||
});
|
||||
setNewSessionIds((prev) => {
|
||||
const next = new Set(prev);
|
||||
next.delete(sessionId);
|
||||
return next;
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
@@ -1182,6 +1236,22 @@ export function TerminalView({ initialCwd, initialBranch, initialMode, nonce }:
|
||||
})
|
||||
);
|
||||
|
||||
// Clean up stale entries for all killed sessions in this tab
|
||||
setSessionCommandOverrides((prev) => {
|
||||
const next = new Map(prev);
|
||||
for (const sessionId of sessionIds) {
|
||||
next.delete(sessionId);
|
||||
}
|
||||
return next;
|
||||
});
|
||||
setNewSessionIds((prev) => {
|
||||
const next = new Set(prev);
|
||||
for (const sessionId of sessionIds) {
|
||||
next.delete(sessionId);
|
||||
}
|
||||
return next;
|
||||
});
|
||||
|
||||
// Now remove the tab from state
|
||||
removeTerminalTab(tabId);
|
||||
// Refresh session count
|
||||
@@ -1255,6 +1325,12 @@ export function TerminalView({ initialCwd, initialBranch, initialMode, nonce }:
|
||||
next.delete(sessionId);
|
||||
return next;
|
||||
});
|
||||
// Clean up any per-session command override
|
||||
setSessionCommandOverrides((prev) => {
|
||||
const next = new Map(prev);
|
||||
next.delete(sessionId);
|
||||
return next;
|
||||
});
|
||||
}, []);
|
||||
|
||||
// Navigate between terminal panes with directional awareness
|
||||
@@ -1387,6 +1463,9 @@ export function TerminalView({ initialCwd, initialBranch, initialMode, nonce }:
|
||||
const terminalFontSize = content.fontSize ?? terminalState.defaultFontSize;
|
||||
// Only run command on new sessions (not restored ones)
|
||||
const isNewSession = newSessionIds.has(content.sessionId);
|
||||
// Per-session command override takes priority over defaultRunScript
|
||||
const sessionCommand = sessionCommandOverrides.get(content.sessionId);
|
||||
const runCommand = isNewSession ? sessionCommand || defaultRunScript : undefined;
|
||||
return (
|
||||
<TerminalErrorBoundary
|
||||
key={`boundary-${content.sessionId}`}
|
||||
@@ -1413,6 +1492,10 @@ export function TerminalView({ initialCwd, initialBranch, initialMode, nonce }:
|
||||
createTerminal('vertical', content.sessionId, cwd, branchName);
|
||||
}}
|
||||
onNewTab={createTerminalInNewTab}
|
||||
onRunCommandInNewTab={(command: string) => {
|
||||
const { cwd, branchName: branch } = getActiveSessionWorktreeInfo();
|
||||
createTerminalInNewTab(cwd, branch, command);
|
||||
}}
|
||||
onNavigateUp={() => navigateToTerminal('up')}
|
||||
onNavigateDown={() => navigateToTerminal('down')}
|
||||
onNavigateLeft={() => navigateToTerminal('left')}
|
||||
@@ -1427,7 +1510,7 @@ export function TerminalView({ initialCwd, initialBranch, initialMode, nonce }:
|
||||
isDropTarget={activeDragId !== null && activeDragId !== content.sessionId}
|
||||
fontSize={terminalFontSize}
|
||||
onFontSizeChange={(size) => setTerminalPanelFontSize(content.sessionId, size)}
|
||||
runCommandOnConnect={isNewSession ? defaultRunScript : undefined}
|
||||
runCommandOnConnect={runCommand}
|
||||
onCommandRan={() => handleCommandRan(content.sessionId)}
|
||||
isMaximized={terminalState.maximizedSessionId === content.sessionId}
|
||||
onToggleMaximize={() => toggleTerminalMaximized(content.sessionId)}
|
||||
@@ -1919,6 +2002,119 @@ export function TerminalView({ initialCwd, initialBranch, initialMode, nonce }:
|
||||
/>
|
||||
</div>
|
||||
|
||||
{/* Background Color */}
|
||||
<div className="space-y-2">
|
||||
<div className="flex items-center justify-between">
|
||||
<Label className="text-xs font-medium">Background Color</Label>
|
||||
{terminalState.customBackgroundColor && (
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="icon"
|
||||
className="h-5 w-5"
|
||||
onClick={() => setTerminalBackgroundColor(null)}
|
||||
title="Reset to theme default"
|
||||
>
|
||||
<RotateCcw className="h-3 w-3" />
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
<div className="flex items-center gap-2">
|
||||
<div
|
||||
className="w-7 h-7 rounded border border-border/50 shrink-0 flex items-center justify-center"
|
||||
style={{
|
||||
backgroundColor: terminalState.customBackgroundColor || 'var(--card)',
|
||||
}}
|
||||
>
|
||||
<Palette
|
||||
className={cn(
|
||||
'h-3 w-3',
|
||||
terminalState.customBackgroundColor
|
||||
? 'text-white/80'
|
||||
: 'text-muted-foreground'
|
||||
)}
|
||||
/>
|
||||
</div>
|
||||
<Input
|
||||
type="color"
|
||||
value={terminalState.customBackgroundColor || '#000000'}
|
||||
onChange={(e) => setTerminalBackgroundColor(e.target.value)}
|
||||
className="w-10 h-7 p-0.5 cursor-pointer bg-transparent border-border/50 shrink-0"
|
||||
title="Pick a background color"
|
||||
/>
|
||||
<Input
|
||||
type="text"
|
||||
value={terminalState.customBackgroundColor || ''}
|
||||
onChange={(e) => {
|
||||
const value = e.target.value;
|
||||
if (value === '' || /^#[0-9A-Fa-f]{0,6}$/.test(value)) {
|
||||
if (value === '' || /^#[0-9A-Fa-f]{6}$/.test(value)) {
|
||||
setTerminalBackgroundColor(value || null);
|
||||
}
|
||||
}
|
||||
}}
|
||||
placeholder="#1a1a1a"
|
||||
className="flex-1 h-7 text-xs font-mono"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Foreground Color */}
|
||||
<div className="space-y-2">
|
||||
<div className="flex items-center justify-between">
|
||||
<Label className="text-xs font-medium">Foreground Color</Label>
|
||||
{terminalState.customForegroundColor && (
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="icon"
|
||||
className="h-5 w-5"
|
||||
onClick={() => setTerminalForegroundColor(null)}
|
||||
title="Reset to theme default"
|
||||
>
|
||||
<RotateCcw className="h-3 w-3" />
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
<div className="flex items-center gap-2">
|
||||
<div
|
||||
className="w-7 h-7 rounded border border-border/50 shrink-0 flex items-center justify-center"
|
||||
style={{
|
||||
backgroundColor:
|
||||
terminalState.customForegroundColor || 'var(--foreground)',
|
||||
}}
|
||||
>
|
||||
<Type
|
||||
className={cn(
|
||||
'h-3 w-3',
|
||||
terminalState.customForegroundColor
|
||||
? 'text-black/80'
|
||||
: 'text-background'
|
||||
)}
|
||||
/>
|
||||
</div>
|
||||
<Input
|
||||
type="color"
|
||||
value={terminalState.customForegroundColor || '#ffffff'}
|
||||
onChange={(e) => setTerminalForegroundColor(e.target.value)}
|
||||
className="w-10 h-7 p-0.5 cursor-pointer bg-transparent border-border/50 shrink-0"
|
||||
title="Pick a foreground color"
|
||||
/>
|
||||
<Input
|
||||
type="text"
|
||||
value={terminalState.customForegroundColor || ''}
|
||||
onChange={(e) => {
|
||||
const value = e.target.value;
|
||||
if (value === '' || /^#[0-9A-Fa-f]{0,6}$/.test(value)) {
|
||||
if (value === '' || /^#[0-9A-Fa-f]{6}$/.test(value)) {
|
||||
setTerminalForegroundColor(value || null);
|
||||
}
|
||||
}
|
||||
}}
|
||||
placeholder="#ffffff"
|
||||
className="flex-1 h-7 text-xs font-mono"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Screen Reader */}
|
||||
<div className="flex items-center justify-between">
|
||||
<div className="space-y-0.5">
|
||||
@@ -1971,6 +2167,10 @@ export function TerminalView({ initialCwd, initialBranch, initialMode, nonce }:
|
||||
createTerminal('vertical', terminalState.maximizedSessionId!, cwd, branchName);
|
||||
}}
|
||||
onNewTab={createTerminalInNewTab}
|
||||
onRunCommandInNewTab={(command: string) => {
|
||||
const { cwd, branchName: branch } = getActiveSessionWorktreeInfo();
|
||||
createTerminalInNewTab(cwd, branch, command);
|
||||
}}
|
||||
onSessionInvalid={() => {
|
||||
const sessionId = terminalState.maximizedSessionId!;
|
||||
logger.info(`Maximized session ${sessionId} is invalid, removing from layout`);
|
||||
@@ -1982,6 +2182,13 @@ export function TerminalView({ initialCwd, initialBranch, initialMode, nonce }:
|
||||
onFontSizeChange={(size) =>
|
||||
setTerminalPanelFontSize(terminalState.maximizedSessionId!, size)
|
||||
}
|
||||
runCommandOnConnect={
|
||||
newSessionIds.has(terminalState.maximizedSessionId)
|
||||
? sessionCommandOverrides.get(terminalState.maximizedSessionId) ||
|
||||
defaultRunScript
|
||||
: undefined
|
||||
}
|
||||
onCommandRan={() => handleCommandRan(terminalState.maximizedSessionId!)}
|
||||
isMaximized={true}
|
||||
onToggleMaximize={() => toggleTerminalMaximized(terminalState.maximizedSessionId!)}
|
||||
/>
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import { useEffect, useRef, useCallback, useState } from 'react';
|
||||
import { useNavigate } from '@tanstack/react-router';
|
||||
import { createLogger } from '@automaker/utils/logger';
|
||||
import {
|
||||
X,
|
||||
@@ -90,6 +91,7 @@ interface TerminalPanelProps {
|
||||
onSplitHorizontal: () => void;
|
||||
onSplitVertical: () => void;
|
||||
onNewTab?: () => void;
|
||||
onRunCommandInNewTab?: (command: string) => void; // Run a script command in a new terminal tab
|
||||
onNavigateUp?: () => void; // Navigate to terminal pane above
|
||||
onNavigateDown?: () => void; // Navigate to terminal pane below
|
||||
onNavigateLeft?: () => void; // Navigate to terminal pane on the left
|
||||
@@ -120,6 +122,7 @@ export function TerminalPanel({
|
||||
onSplitHorizontal,
|
||||
onSplitVertical,
|
||||
onNewTab,
|
||||
onRunCommandInNewTab,
|
||||
onNavigateUp,
|
||||
onNavigateDown,
|
||||
onNavigateLeft,
|
||||
@@ -135,6 +138,7 @@ export function TerminalPanel({
|
||||
onToggleMaximize,
|
||||
branchName,
|
||||
}: TerminalPanelProps) {
|
||||
const navigate = useNavigate();
|
||||
const terminalRef = useRef<HTMLDivElement>(null);
|
||||
const containerRef = useRef<HTMLDivElement>(null);
|
||||
const xtermRef = useRef<XTerminal | null>(null);
|
||||
@@ -198,16 +202,25 @@ export function TerminalPanel({
|
||||
const currentProject = useAppStore((state) => state.currentProject);
|
||||
|
||||
// Get terminal settings from store - grouped with shallow comparison to reduce re-renders
|
||||
const { defaultRunScript, screenReaderMode, fontFamily, scrollbackLines, lineHeight } =
|
||||
useAppStore(
|
||||
useShallow((state) => ({
|
||||
defaultRunScript: state.terminalState.defaultRunScript,
|
||||
screenReaderMode: state.terminalState.screenReaderMode,
|
||||
fontFamily: state.terminalState.fontFamily,
|
||||
scrollbackLines: state.terminalState.scrollbackLines,
|
||||
lineHeight: state.terminalState.lineHeight,
|
||||
}))
|
||||
);
|
||||
const {
|
||||
defaultRunScript,
|
||||
screenReaderMode,
|
||||
fontFamily,
|
||||
scrollbackLines,
|
||||
lineHeight,
|
||||
customBackgroundColor,
|
||||
customForegroundColor,
|
||||
} = useAppStore(
|
||||
useShallow((state) => ({
|
||||
defaultRunScript: state.terminalState.defaultRunScript,
|
||||
screenReaderMode: state.terminalState.screenReaderMode,
|
||||
fontFamily: state.terminalState.fontFamily,
|
||||
scrollbackLines: state.terminalState.scrollbackLines,
|
||||
lineHeight: state.terminalState.lineHeight,
|
||||
customBackgroundColor: state.terminalState.customBackgroundColor,
|
||||
customForegroundColor: state.terminalState.customForegroundColor,
|
||||
}))
|
||||
);
|
||||
|
||||
// Action setters are stable references, can use individual selectors
|
||||
const setTerminalDefaultRunScript = useAppStore((state) => state.setTerminalDefaultRunScript);
|
||||
@@ -675,7 +688,7 @@ export function TerminalPanel({
|
||||
if (!mounted || !terminalRef.current) return;
|
||||
|
||||
// Get terminal theme matching the app theme
|
||||
const terminalTheme = getTerminalTheme(themeRef.current);
|
||||
const baseTheme = getTerminalTheme(themeRef.current);
|
||||
|
||||
// Get settings from store (read at initialization time)
|
||||
const terminalSettings = useAppStore.getState().terminalState;
|
||||
@@ -683,6 +696,18 @@ export function TerminalPanel({
|
||||
const terminalFontFamily = getTerminalFontFamily(terminalSettings.fontFamily);
|
||||
const terminalScrollback = terminalSettings.scrollbackLines || 5000;
|
||||
const terminalLineHeight = terminalSettings.lineHeight || 1.0;
|
||||
const customBgColor = terminalSettings.customBackgroundColor;
|
||||
const customFgColor = terminalSettings.customForegroundColor;
|
||||
|
||||
// Apply custom colors if set
|
||||
const terminalTheme =
|
||||
customBgColor || customFgColor
|
||||
? {
|
||||
...baseTheme,
|
||||
...(customBgColor && { background: customBgColor }),
|
||||
...(customFgColor && { foreground: customFgColor }),
|
||||
}
|
||||
: baseTheme;
|
||||
|
||||
// Create terminal instance with the current global font size and theme
|
||||
const terminal = new Terminal({
|
||||
@@ -1480,15 +1505,23 @@ export function TerminalPanel({
|
||||
}
|
||||
}, [fontSize, isTerminalReady]);
|
||||
|
||||
// Update terminal theme when app theme changes (including system preference)
|
||||
// Update terminal theme when app theme or custom colors change (including system preference)
|
||||
useEffect(() => {
|
||||
if (xtermRef.current && isTerminalReady) {
|
||||
// Clear any search decorations first to prevent stale color artifacts
|
||||
searchAddonRef.current?.clearDecorations();
|
||||
const terminalTheme = getTerminalTheme(resolvedTheme);
|
||||
const baseTheme = getTerminalTheme(resolvedTheme);
|
||||
const terminalTheme =
|
||||
customBackgroundColor || customForegroundColor
|
||||
? {
|
||||
...baseTheme,
|
||||
...(customBackgroundColor && { background: customBackgroundColor }),
|
||||
...(customForegroundColor && { foreground: customForegroundColor }),
|
||||
}
|
||||
: baseTheme;
|
||||
xtermRef.current.options.theme = terminalTheme;
|
||||
}
|
||||
}, [resolvedTheme, isTerminalReady]);
|
||||
}, [resolvedTheme, customBackgroundColor, customForegroundColor, isTerminalReady]);
|
||||
|
||||
// Handle keyboard shortcuts for zoom (Ctrl+Plus, Ctrl+Minus, Ctrl+0)
|
||||
useEffect(() => {
|
||||
@@ -1921,6 +1954,10 @@ export function TerminalPanel({
|
||||
// Get current terminal theme for xterm styling (resolved for system preference)
|
||||
const currentTerminalTheme = getTerminalTheme(resolvedTheme);
|
||||
|
||||
// Apply custom background/foreground colors if set, otherwise use theme defaults
|
||||
const terminalBackgroundColor = customBackgroundColor ?? currentTerminalTheme.background;
|
||||
const terminalForegroundColor = customForegroundColor ?? currentTerminalTheme.foreground;
|
||||
|
||||
return (
|
||||
<div
|
||||
ref={setRefs}
|
||||
@@ -2071,7 +2108,11 @@ export function TerminalPanel({
|
||||
{/* Quick scripts dropdown */}
|
||||
<TerminalScriptsDropdown
|
||||
onRunCommand={sendCommand}
|
||||
onRunCommandInNewTab={onRunCommandInNewTab}
|
||||
isConnected={connectionStatus === 'connected'}
|
||||
onOpenSettings={() =>
|
||||
navigate({ to: '/project-settings', search: { section: 'commands-scripts' } })
|
||||
}
|
||||
/>
|
||||
|
||||
{/* Settings popover */}
|
||||
@@ -2387,7 +2428,7 @@ export function TerminalPanel({
|
||||
<div
|
||||
ref={terminalRef}
|
||||
className="absolute inset-0"
|
||||
style={{ backgroundColor: currentTerminalTheme.background }}
|
||||
style={{ backgroundColor: terminalBackgroundColor }}
|
||||
onContextMenu={handleContextMenu}
|
||||
onTouchStart={handleTouchStart}
|
||||
onTouchMove={handleTouchMove}
|
||||
@@ -2448,8 +2489,8 @@ export function TerminalPanel({
|
||||
className="flex-1 overflow-auto"
|
||||
style={
|
||||
{
|
||||
backgroundColor: currentTerminalTheme.background,
|
||||
color: currentTerminalTheme.foreground,
|
||||
backgroundColor: terminalBackgroundColor,
|
||||
color: terminalForegroundColor,
|
||||
fontFamily: getTerminalFontFamily(fontFamily),
|
||||
fontSize: `${fontSize}px`,
|
||||
lineHeight: `${lineHeight || 1.0}`,
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { useCallback, useMemo } from 'react';
|
||||
import { ScrollText, Play, Settings2 } from 'lucide-react';
|
||||
import { ScrollText, Play, Settings2, SquareArrowOutUpRight } from 'lucide-react';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import {
|
||||
DropdownMenu,
|
||||
@@ -17,6 +17,8 @@ import { DEFAULT_TERMINAL_SCRIPTS } from '../project-settings-view/terminal-scri
|
||||
interface TerminalScriptsDropdownProps {
|
||||
/** Callback to send a command + newline to the terminal */
|
||||
onRunCommand: (command: string) => void;
|
||||
/** Callback to run a command in a new terminal tab */
|
||||
onRunCommandInNewTab?: (command: string) => void;
|
||||
/** Whether the terminal is connected and ready */
|
||||
isConnected: boolean;
|
||||
/** Optional callback to navigate to project settings scripts section */
|
||||
@@ -25,11 +27,13 @@ interface TerminalScriptsDropdownProps {
|
||||
|
||||
/**
|
||||
* Dropdown menu in the terminal header bar that provides quick-access
|
||||
* to user-configured project scripts. Clicking a script inserts the
|
||||
* command into the terminal and presses Enter.
|
||||
* to user-configured project scripts. Each script is a split button:
|
||||
* clicking the left side runs the command in the current terminal,
|
||||
* clicking the "new tab" icon on the right runs it in a new tab.
|
||||
*/
|
||||
export function TerminalScriptsDropdown({
|
||||
onRunCommand,
|
||||
onRunCommandInNewTab,
|
||||
isConnected,
|
||||
onOpenSettings,
|
||||
}: TerminalScriptsDropdownProps) {
|
||||
@@ -53,6 +57,14 @@ export function TerminalScriptsDropdown({
|
||||
[isConnected, onRunCommand]
|
||||
);
|
||||
|
||||
const handleRunScriptInNewTab = useCallback(
|
||||
(command: string) => {
|
||||
if (!isConnected || !onRunCommandInNewTab) return;
|
||||
onRunCommandInNewTab(command);
|
||||
},
|
||||
[isConnected, onRunCommandInNewTab]
|
||||
);
|
||||
|
||||
return (
|
||||
<DropdownMenu>
|
||||
<DropdownMenuTrigger asChild>
|
||||
@@ -82,7 +94,7 @@ export function TerminalScriptsDropdown({
|
||||
key={script.id}
|
||||
onClick={() => handleRunScript(script.command)}
|
||||
disabled={!isConnected}
|
||||
className="gap-2"
|
||||
className="gap-2 pr-1"
|
||||
>
|
||||
<Play className={cn('h-3.5 w-3.5 shrink-0 text-brand-500')} />
|
||||
<div className="flex flex-col min-w-0 flex-1">
|
||||
@@ -91,17 +103,43 @@ export function TerminalScriptsDropdown({
|
||||
{script.command}
|
||||
</span>
|
||||
</div>
|
||||
{onRunCommandInNewTab && (
|
||||
<button
|
||||
type="button"
|
||||
className={cn(
|
||||
'shrink-0 ml-1 p-1 rounded-sm border-l border-border',
|
||||
'text-muted-foreground hover:text-foreground hover:bg-accent/80',
|
||||
'transition-colors',
|
||||
!isConnected && 'pointer-events-none opacity-50'
|
||||
)}
|
||||
title="Run in new tab"
|
||||
onClick={(e) => {
|
||||
e.stopPropagation();
|
||||
e.preventDefault();
|
||||
handleRunScriptInNewTab(script.command);
|
||||
}}
|
||||
onPointerDown={(e) => {
|
||||
// Prevent the DropdownMenuItem from handling this pointer event
|
||||
e.stopPropagation();
|
||||
}}
|
||||
onPointerUp={(e) => {
|
||||
e.stopPropagation();
|
||||
}}
|
||||
>
|
||||
<SquareArrowOutUpRight className="h-3 w-3" />
|
||||
</button>
|
||||
)}
|
||||
</DropdownMenuItem>
|
||||
))}
|
||||
{onOpenSettings && (
|
||||
<>
|
||||
<DropdownMenuSeparator />
|
||||
<DropdownMenuItem onClick={onOpenSettings} className="gap-2 text-muted-foreground">
|
||||
<Settings2 className="h-3.5 w-3.5 shrink-0" />
|
||||
<span className="text-sm">Configure Scripts...</span>
|
||||
</DropdownMenuItem>
|
||||
</>
|
||||
)}
|
||||
<DropdownMenuSeparator />
|
||||
<DropdownMenuItem
|
||||
onClick={onOpenSettings}
|
||||
className="gap-2 text-muted-foreground"
|
||||
disabled={!onOpenSettings}
|
||||
>
|
||||
<Settings2 className="h-3.5 w-3.5 shrink-0" />
|
||||
<span className="text-sm">Edit Commands & Scripts</span>
|
||||
</DropdownMenuItem>
|
||||
</DropdownMenuContent>
|
||||
</DropdownMenu>
|
||||
);
|
||||
|
||||
@@ -81,12 +81,12 @@ export function getTerminalFontFamily(fontValue: string | undefined): string {
|
||||
return fontValue;
|
||||
}
|
||||
|
||||
// Dark theme (default)
|
||||
// Dark theme (default) - true black background with white foreground
|
||||
const darkTheme: TerminalTheme = {
|
||||
background: '#0a0a0a',
|
||||
foreground: '#d4d4d4',
|
||||
cursor: '#d4d4d4',
|
||||
cursorAccent: '#0a0a0a',
|
||||
background: '#000000',
|
||||
foreground: '#ffffff',
|
||||
cursor: '#ffffff',
|
||||
cursorAccent: '#000000',
|
||||
selectionBackground: '#264f78',
|
||||
black: '#1e1e1e',
|
||||
red: '#f44747',
|
||||
@@ -626,4 +626,29 @@ export function getTerminalTheme(theme: ThemeMode): TerminalTheme {
|
||||
return terminalThemes[theme] || darkTheme;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get terminal theme with optional custom color overrides
|
||||
* @param theme - The app theme mode
|
||||
* @param customBackgroundColor - Optional custom background color (hex string) to override theme default
|
||||
* @param customForegroundColor - Optional custom foreground/text color (hex string) to override theme default
|
||||
* @returns Terminal theme with custom colors if provided
|
||||
*/
|
||||
export function getTerminalThemeWithOverride(
|
||||
theme: ThemeMode,
|
||||
customBackgroundColor: string | null,
|
||||
customForegroundColor?: string | null
|
||||
): TerminalTheme {
|
||||
const baseTheme = getTerminalTheme(theme);
|
||||
|
||||
if (customBackgroundColor || customForegroundColor) {
|
||||
return {
|
||||
...baseTheme,
|
||||
...(customBackgroundColor && { background: customBackgroundColor }),
|
||||
...(customForegroundColor && { foreground: customForegroundColor }),
|
||||
};
|
||||
}
|
||||
|
||||
return baseTheme;
|
||||
}
|
||||
|
||||
export default terminalThemes;
|
||||
|
||||
@@ -46,6 +46,8 @@ export {
|
||||
useCommitWorktree,
|
||||
usePushWorktree,
|
||||
usePullWorktree,
|
||||
useSyncWorktree,
|
||||
useSetTracking,
|
||||
useCreatePullRequest,
|
||||
useMergeWorktree,
|
||||
useSwitchBranch,
|
||||
@@ -62,6 +64,7 @@ export {
|
||||
useValidateIssue,
|
||||
useMarkValidationViewed,
|
||||
useGetValidationStatus,
|
||||
useResolveReviewThread,
|
||||
} from './use-github-mutations';
|
||||
|
||||
// Ideation mutations
|
||||
|
||||
@@ -135,6 +135,55 @@ export function useMarkValidationViewed(projectPath: string) {
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Resolve or unresolve a PR review thread
|
||||
*
|
||||
* @param projectPath - Path to the project
|
||||
* @param prNumber - PR number (for cache invalidation)
|
||||
* @returns Mutation for resolving/unresolving a review thread
|
||||
*
|
||||
* @example
|
||||
* ```tsx
|
||||
* const resolveThread = useResolveReviewThread(projectPath, prNumber);
|
||||
* resolveThread.mutate({ threadId: comment.threadId, resolve: true });
|
||||
* ```
|
||||
*/
|
||||
export function useResolveReviewThread(projectPath: string, prNumber: number) {
|
||||
const queryClient = useQueryClient();
|
||||
|
||||
return useMutation({
|
||||
mutationFn: async ({ threadId, resolve }: { threadId: string; resolve: boolean }) => {
|
||||
const api = getElectronAPI();
|
||||
if (!api.github?.resolveReviewThread) {
|
||||
throw new Error('Resolve review thread API not available');
|
||||
}
|
||||
|
||||
const result = await api.github.resolveReviewThread(projectPath, threadId, resolve);
|
||||
|
||||
if (!result.success) {
|
||||
throw new Error(result.error || 'Failed to resolve review thread');
|
||||
}
|
||||
|
||||
return { isResolved: result.isResolved ?? resolve };
|
||||
},
|
||||
onSuccess: (_, variables) => {
|
||||
const action = variables.resolve ? 'resolved' : 'unresolved';
|
||||
toast.success(`Comment ${action}`, {
|
||||
description: `The review thread has been ${action} on GitHub`,
|
||||
});
|
||||
// Invalidate the PR review comments cache to reflect updated resolved status
|
||||
queryClient.invalidateQueries({
|
||||
queryKey: queryKeys.github.prReviewComments(projectPath, prNumber),
|
||||
});
|
||||
},
|
||||
onError: (error) => {
|
||||
toast.error('Failed to update comment', {
|
||||
description: error instanceof Error ? error.message : 'Unknown error',
|
||||
});
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Get running validation status
|
||||
*
|
||||
|
||||
@@ -197,6 +197,76 @@ export function usePullWorktree() {
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Sync worktree branch (pull then push)
|
||||
*
|
||||
* @returns Mutation for syncing changes
|
||||
*/
|
||||
export function useSyncWorktree() {
|
||||
const queryClient = useQueryClient();
|
||||
|
||||
return useMutation({
|
||||
mutationFn: async ({ worktreePath, remote }: { worktreePath: string; remote?: string }) => {
|
||||
const api = getElectronAPI();
|
||||
if (!api.worktree) throw new Error('Worktree API not available');
|
||||
const result = await api.worktree.sync(worktreePath, remote);
|
||||
if (!result.success) {
|
||||
throw new Error(result.error || 'Failed to sync');
|
||||
}
|
||||
return result.result;
|
||||
},
|
||||
onSuccess: () => {
|
||||
queryClient.invalidateQueries({ queryKey: ['worktrees'] });
|
||||
toast.success('Branch synced with remote');
|
||||
},
|
||||
onError: (error: Error) => {
|
||||
toast.error('Failed to sync', {
|
||||
description: error.message,
|
||||
});
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Set upstream tracking branch
|
||||
*
|
||||
* @returns Mutation for setting tracking branch
|
||||
*/
|
||||
export function useSetTracking() {
|
||||
const queryClient = useQueryClient();
|
||||
|
||||
return useMutation({
|
||||
mutationFn: async ({
|
||||
worktreePath,
|
||||
remote,
|
||||
branch,
|
||||
}: {
|
||||
worktreePath: string;
|
||||
remote: string;
|
||||
branch?: string;
|
||||
}) => {
|
||||
const api = getElectronAPI();
|
||||
if (!api.worktree) throw new Error('Worktree API not available');
|
||||
const result = await api.worktree.setTracking(worktreePath, remote, branch);
|
||||
if (!result.success) {
|
||||
throw new Error(result.error || 'Failed to set tracking branch');
|
||||
}
|
||||
return result.result;
|
||||
},
|
||||
onSuccess: (result) => {
|
||||
queryClient.invalidateQueries({ queryKey: ['worktrees'] });
|
||||
toast.success('Tracking branch set', {
|
||||
description: result?.message,
|
||||
});
|
||||
},
|
||||
onError: (error: Error) => {
|
||||
toast.error('Failed to set tracking branch', {
|
||||
description: error.message,
|
||||
});
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Create a pull request from a worktree
|
||||
*
|
||||
|
||||
@@ -20,6 +20,7 @@ export {
|
||||
useGitHubValidations,
|
||||
useGitHubRemote,
|
||||
useGitHubIssueComments,
|
||||
useGitHubPRReviewComments,
|
||||
} from './use-github';
|
||||
|
||||
// Usage
|
||||
|
||||
@@ -6,8 +6,8 @@
|
||||
* automatic caching, deduplication, and background refetching.
|
||||
*/
|
||||
|
||||
import { useMemo } from 'react';
|
||||
import { useQuery } from '@tanstack/react-query';
|
||||
import { useMemo, useEffect, useRef } from 'react';
|
||||
import { useQuery, useQueryClient } from '@tanstack/react-query';
|
||||
import { getElectronAPI } from '@/lib/electron';
|
||||
import { queryKeys } from '@/lib/query-keys';
|
||||
import { STALE_TIMES } from '@/lib/query-client';
|
||||
@@ -151,6 +151,34 @@ export function useFeatures(projectPath: string | undefined) {
|
||||
[projectPath]
|
||||
);
|
||||
|
||||
const queryClient = useQueryClient();
|
||||
|
||||
// Subscribe to React Query cache changes for features and sync to localStorage.
|
||||
// This ensures optimistic updates (e.g., status changes to 'verified') are
|
||||
// persisted to localStorage immediately, not just when queryFn runs.
|
||||
// Without this, a page refresh after an optimistic update could show stale
|
||||
// localStorage data where features appear in the wrong column (e.g., verified
|
||||
// features showing up in backlog).
|
||||
const projectPathRef = useRef(projectPath);
|
||||
projectPathRef.current = projectPath;
|
||||
useEffect(() => {
|
||||
if (!projectPath) return;
|
||||
const targetQueryHash = JSON.stringify(queryKeys.features.all(projectPath));
|
||||
const unsubscribe = queryClient.getQueryCache().subscribe((event) => {
|
||||
if (
|
||||
event.type === 'updated' &&
|
||||
event.action.type === 'success' &&
|
||||
event.query.queryHash === targetQueryHash
|
||||
) {
|
||||
const features = event.query.state.data as Feature[] | undefined;
|
||||
if (features && projectPathRef.current) {
|
||||
writePersistedFeatures(projectPathRef.current, features);
|
||||
}
|
||||
}
|
||||
});
|
||||
return unsubscribe;
|
||||
}, [projectPath, queryClient]);
|
||||
|
||||
return useQuery({
|
||||
queryKey: queryKeys.features.all(projectPath ?? ''),
|
||||
queryFn: async (): Promise<Feature[]> => {
|
||||
@@ -166,7 +194,11 @@ export function useFeatures(projectPath: string | undefined) {
|
||||
},
|
||||
enabled: !!projectPath,
|
||||
initialData: () => persisted?.features,
|
||||
initialDataUpdatedAt: () => persisted?.timestamp,
|
||||
// Always treat localStorage cache as stale so React Query immediately
|
||||
// fetches fresh data from the server on page load. This prevents stale
|
||||
// feature statuses (e.g., 'verified' features appearing in backlog)
|
||||
// while still showing cached data instantly for a fast initial render.
|
||||
initialDataUpdatedAt: 0,
|
||||
staleTime: STALE_TIMES.FEATURES,
|
||||
refetchInterval: createSmartPollingInterval(FEATURES_POLLING_INTERVAL),
|
||||
refetchOnWindowFocus: FEATURES_REFETCH_ON_FOCUS,
|
||||
|
||||
@@ -8,7 +8,13 @@ import { useQuery, useInfiniteQuery } from '@tanstack/react-query';
|
||||
import { getElectronAPI } from '@/lib/electron';
|
||||
import { queryKeys } from '@/lib/query-keys';
|
||||
import { STALE_TIMES } from '@/lib/query-client';
|
||||
import type { GitHubIssue, GitHubPR, GitHubComment, StoredValidation } from '@/lib/electron';
|
||||
import type {
|
||||
GitHubIssue,
|
||||
GitHubPR,
|
||||
GitHubComment,
|
||||
PRReviewComment,
|
||||
StoredValidation,
|
||||
} from '@/lib/electron';
|
||||
|
||||
interface GitHubIssuesResult {
|
||||
openIssues: GitHubIssue[];
|
||||
@@ -197,3 +203,45 @@ export function useGitHubIssueComments(
|
||||
staleTime: STALE_TIMES.GITHUB,
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Fetch review comments for a GitHub PR
|
||||
*
|
||||
* Fetches both regular PR comments and inline code review comments
|
||||
* with file path and line context for each.
|
||||
*
|
||||
* @param projectPath - Path to the project
|
||||
* @param prNumber - PR number
|
||||
* @returns Query result with review comments
|
||||
*
|
||||
* @example
|
||||
* ```tsx
|
||||
* const { data, isLoading } = useGitHubPRReviewComments(projectPath, prNumber);
|
||||
* const comments = data?.comments ?? [];
|
||||
* ```
|
||||
*/
|
||||
export function useGitHubPRReviewComments(
|
||||
projectPath: string | undefined,
|
||||
prNumber: number | undefined
|
||||
) {
|
||||
return useQuery({
|
||||
queryKey: queryKeys.github.prReviewComments(projectPath ?? '', prNumber ?? 0),
|
||||
queryFn: async (): Promise<{ comments: PRReviewComment[]; totalCount: number }> => {
|
||||
if (!projectPath || !prNumber) throw new Error('Missing project path or PR number');
|
||||
const api = getElectronAPI();
|
||||
if (!api.github) {
|
||||
throw new Error('GitHub API not available');
|
||||
}
|
||||
const result = await api.github.getPRReviewComments(projectPath, prNumber);
|
||||
if (!result.success) {
|
||||
throw new Error(result.error || 'Failed to fetch PR review comments');
|
||||
}
|
||||
return {
|
||||
comments: (result.comments ?? []) as PRReviewComment[],
|
||||
totalCount: result.totalCount ?? 0,
|
||||
};
|
||||
},
|
||||
enabled: !!projectPath && !!prNumber,
|
||||
staleTime: STALE_TIMES.GITHUB,
|
||||
});
|
||||
}
|
||||
|
||||
@@ -108,10 +108,17 @@ export function useAutoMode(worktree?: WorktreeInfo) {
|
||||
// Derive branchName from worktree:
|
||||
// If worktree is provided, use its branch name (even for main worktree, as it might be on a feature branch)
|
||||
// If not provided, default to null (main worktree default)
|
||||
// IMPORTANT: Depend on primitive values (isMain, branch) instead of the worktree object
|
||||
// reference to avoid re-computing when the parent passes a new object with the same values.
|
||||
// This prevents a cascading re-render loop: new worktree ref → new branchName useMemo →
|
||||
// new refreshStatus callback → effect re-fires → store update → re-render → React error #185.
|
||||
const worktreeIsMain = worktree?.isMain;
|
||||
const worktreeBranch = worktree?.branch;
|
||||
const hasWorktree = worktree !== undefined;
|
||||
const branchName = useMemo(() => {
|
||||
if (!worktree) return null;
|
||||
return worktree.isMain ? null : worktree.branch || null;
|
||||
}, [worktree]);
|
||||
if (!hasWorktree) return null;
|
||||
return worktreeIsMain ? null : worktreeBranch || null;
|
||||
}, [hasWorktree, worktreeIsMain, worktreeBranch]);
|
||||
|
||||
// Helper to look up project ID from path
|
||||
const getProjectIdFromPath = useCallback(
|
||||
@@ -245,10 +252,19 @@ export function useAutoMode(worktree?: WorktreeInfo) {
|
||||
}
|
||||
}, [branchName, currentProject, setAutoModeRunning]);
|
||||
|
||||
// On mount, query backend for current auto loop status and sync UI state.
|
||||
// On mount (and when refreshStatus identity changes, e.g. project switch),
|
||||
// query backend for current auto loop status and sync UI state.
|
||||
// This handles cases where the backend is still running after a page refresh.
|
||||
//
|
||||
// IMPORTANT: Debounce with a short delay to prevent a synchronous cascade
|
||||
// during project switches. Without this, the sequence is:
|
||||
// refreshStatus() → setAutoModeRunning() → store update → re-render →
|
||||
// other effects fire → more store updates → React error #185.
|
||||
// The 150ms delay lets React settle the initial mount renders before we
|
||||
// trigger additional store mutations from the API response.
|
||||
useEffect(() => {
|
||||
void refreshStatus();
|
||||
const timer = setTimeout(() => void refreshStatus(), 150);
|
||||
return () => clearTimeout(timer);
|
||||
}, [refreshStatus]);
|
||||
|
||||
// Periodic polling fallback when WebSocket events are stale.
|
||||
|
||||
@@ -8,12 +8,21 @@ import { getHttpApiClient } from '@/lib/http-api-client';
|
||||
* before the user opens feature dialogs.
|
||||
*/
|
||||
export function useCursorStatusInit() {
|
||||
const { setCursorCliStatus, cursorCliStatus } = useSetupStore();
|
||||
// Use individual selectors instead of bare useSetupStore() to prevent
|
||||
// re-rendering on every setup store mutation during initialization.
|
||||
const setCursorCliStatus = useSetupStore((s) => s.setCursorCliStatus);
|
||||
const initialized = useRef(false);
|
||||
|
||||
useEffect(() => {
|
||||
// Only initialize once per session
|
||||
if (initialized.current || cursorCliStatus !== null) {
|
||||
if (initialized.current) {
|
||||
return;
|
||||
}
|
||||
// Check current status at call time rather than via dependency to avoid
|
||||
// re-renders when other setup store fields change during initialization.
|
||||
const currentStatus = useSetupStore.getState().cursorCliStatus;
|
||||
if (currentStatus !== null) {
|
||||
initialized.current = true;
|
||||
return;
|
||||
}
|
||||
initialized.current = true;
|
||||
@@ -42,5 +51,5 @@ export function useCursorStatusInit() {
|
||||
};
|
||||
|
||||
initCursorStatus();
|
||||
}, [setCursorCliStatus, cursorCliStatus]);
|
||||
}, [setCursorCliStatus]);
|
||||
}
|
||||
|
||||
@@ -26,7 +26,6 @@ export function useProjectSettingsLoader() {
|
||||
(state) => state.setAutoDismissInitScriptIndicator
|
||||
);
|
||||
const setWorktreeCopyFiles = useAppStore((state) => state.setWorktreeCopyFiles);
|
||||
const setCurrentProject = useAppStore((state) => state.setCurrentProject);
|
||||
|
||||
const appliedProjectRef = useRef<{ path: string; dataUpdatedAt: number } | null>(null);
|
||||
|
||||
@@ -116,30 +115,39 @@ export function useProjectSettingsLoader() {
|
||||
|
||||
// Check if we need to update the project
|
||||
const storeState = useAppStore.getState();
|
||||
const updatedProject = storeState.currentProject;
|
||||
if (updatedProject && updatedProject.path === projectPath) {
|
||||
// snapshotProject is the store's current value at this point in time;
|
||||
// it is distinct from updatedProjectData which is the new value we build below.
|
||||
const snapshotProject = storeState.currentProject;
|
||||
if (snapshotProject && snapshotProject.path === projectPath) {
|
||||
const needsUpdate =
|
||||
(activeClaudeApiProfileId !== undefined &&
|
||||
updatedProject.activeClaudeApiProfileId !== activeClaudeApiProfileId) ||
|
||||
snapshotProject.activeClaudeApiProfileId !== activeClaudeApiProfileId) ||
|
||||
(phaseModelOverrides !== undefined &&
|
||||
JSON.stringify(updatedProject.phaseModelOverrides) !==
|
||||
JSON.stringify(snapshotProject.phaseModelOverrides) !==
|
||||
JSON.stringify(phaseModelOverrides));
|
||||
|
||||
if (needsUpdate) {
|
||||
const updatedProjectData = {
|
||||
...updatedProject,
|
||||
...snapshotProject,
|
||||
...(activeClaudeApiProfileId !== undefined && { activeClaudeApiProfileId }),
|
||||
...(phaseModelOverrides !== undefined && { phaseModelOverrides }),
|
||||
};
|
||||
|
||||
// Update currentProject
|
||||
setCurrentProject(updatedProjectData);
|
||||
|
||||
// Also update the project in the projects array to keep them in sync
|
||||
// Update both currentProject and projects array in a single setState call
|
||||
// to avoid two separate re-renders that can cascade during initialization
|
||||
// and contribute to React error #185 (maximum update depth exceeded).
|
||||
const updatedProjects = storeState.projects.map((p) =>
|
||||
p.id === updatedProject.id ? updatedProjectData : p
|
||||
p.id === snapshotProject.id ? updatedProjectData : p
|
||||
);
|
||||
useAppStore.setState({ projects: updatedProjects });
|
||||
// NOTE: Intentionally bypasses setCurrentProject() to avoid a second
|
||||
// render cycle that can trigger React error #185 (maximum update depth
|
||||
// exceeded). This means persistEffectiveThemeForProject() is skipped,
|
||||
// which is safe because only activeClaudeApiProfileId and
|
||||
// phaseModelOverrides are mutated here — not the project theme.
|
||||
useAppStore.setState({
|
||||
currentProject: updatedProjectData,
|
||||
projects: updatedProjects,
|
||||
});
|
||||
}
|
||||
}
|
||||
}, [
|
||||
@@ -159,6 +167,5 @@ export function useProjectSettingsLoader() {
|
||||
setDefaultDeleteBranch,
|
||||
setAutoDismissInitScriptIndicator,
|
||||
setWorktreeCopyFiles,
|
||||
setCurrentProject,
|
||||
]);
|
||||
}
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user