3 Commits

Author SHA1 Message Date
gsxdsm
736e12d397 feat: Batch dev server logs and fix React module resolution order 2026-03-02 23:19:17 -08:00
gsxdsm
90be17fd79 fix: Address PR #828 review feedback
- Reset RAF buffer on context changes (worktree switch, dev-server restart)
  to prevent stale output from flushing into new sessions
- Fix high-frequency WebSocket filter to catch auto-mode:event wrapping
  (auto_mode_progress is wrapped in auto-mode:event) and add feature:progress
- Reorder Vite aliases so explicit jsx-runtime entries aren't shadowed by
  the broad /^react(\/|$)/ regex (Vite uses first-match-wins)

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-02 23:17:28 -08:00
gsxdsm
fc6c69f03d Changes from fix/dev-server-hang 2026-03-02 23:03:36 -08:00
12 changed files with 157 additions and 266 deletions

View File

@@ -1,5 +1,6 @@
// @ts-nocheck - feature update logic with partial updates and image/file handling // @ts-nocheck - feature update logic with partial updates and image/file handling
import { useCallback } from 'react'; import { useCallback } from 'react';
import { useQueryClient } from '@tanstack/react-query';
import { import {
Feature, Feature,
FeatureImage, FeatureImage,
@@ -17,10 +18,7 @@ import { useVerifyFeature, useResumeFeature } from '@/hooks/mutations';
import { truncateDescription } from '@/lib/utils'; import { truncateDescription } from '@/lib/utils';
import { getBlockingDependencies } from '@automaker/dependency-resolver'; import { getBlockingDependencies } from '@automaker/dependency-resolver';
import { createLogger } from '@automaker/utils/logger'; import { createLogger } from '@automaker/utils/logger';
import { import { queryKeys } from '@/lib/query-keys';
markFeatureTransitioning,
unmarkFeatureTransitioning,
} from '@/lib/feature-transition-state';
const logger = createLogger('BoardActions'); const logger = createLogger('BoardActions');
@@ -118,6 +116,8 @@ export function useBoardActions({
currentWorktreeBranch, currentWorktreeBranch,
stopFeature, stopFeature,
}: UseBoardActionsProps) { }: UseBoardActionsProps) {
const queryClient = useQueryClient();
// IMPORTANT: Use individual selectors instead of bare useAppStore() to prevent // IMPORTANT: Use individual selectors instead of bare useAppStore() to prevent
// subscribing to the entire store. Bare useAppStore() causes the host component // subscribing to the entire store. Bare useAppStore() causes the host component
// (BoardView) to re-render on EVERY store change, which cascades through effects // (BoardView) to re-render on EVERY store change, which cascades through effects
@@ -125,6 +125,7 @@ export function useBoardActions({
const addFeature = useAppStore((s) => s.addFeature); const addFeature = useAppStore((s) => s.addFeature);
const updateFeature = useAppStore((s) => s.updateFeature); const updateFeature = useAppStore((s) => s.updateFeature);
const removeFeature = useAppStore((s) => s.removeFeature); const removeFeature = useAppStore((s) => s.removeFeature);
const moveFeature = useAppStore((s) => s.moveFeature);
const worktreesEnabled = useAppStore((s) => s.useWorktrees); const worktreesEnabled = useAppStore((s) => s.useWorktrees);
const enableDependencyBlocking = useAppStore((s) => s.enableDependencyBlocking); const enableDependencyBlocking = useAppStore((s) => s.enableDependencyBlocking);
const skipVerificationInAutoMode = useAppStore((s) => s.skipVerificationInAutoMode); const skipVerificationInAutoMode = useAppStore((s) => s.skipVerificationInAutoMode);
@@ -706,7 +707,8 @@ export function useBoardActions({
try { try {
const result = await verifyFeatureMutation.mutateAsync(feature.id); const result = await verifyFeatureMutation.mutateAsync(feature.id);
if (result.passes) { if (result.passes) {
// persistFeatureUpdate handles the optimistic RQ cache update internally // Immediately move card to verified column (optimistic update)
moveFeature(feature.id, 'verified');
persistFeatureUpdate(feature.id, { persistFeatureUpdate(feature.id, {
status: 'verified', status: 'verified',
justFinishedAt: undefined, justFinishedAt: undefined,
@@ -723,7 +725,7 @@ export function useBoardActions({
// Error toast is already shown by the mutation's onError handler // Error toast is already shown by the mutation's onError handler
} }
}, },
[currentProject, verifyFeatureMutation, persistFeatureUpdate] [currentProject, verifyFeatureMutation, moveFeature, persistFeatureUpdate]
); );
const handleResumeFeature = useCallback( const handleResumeFeature = useCallback(
@@ -740,6 +742,7 @@ export function useBoardActions({
const handleManualVerify = useCallback( const handleManualVerify = useCallback(
(feature: Feature) => { (feature: Feature) => {
moveFeature(feature.id, 'verified');
persistFeatureUpdate(feature.id, { persistFeatureUpdate(feature.id, {
status: 'verified', status: 'verified',
justFinishedAt: undefined, justFinishedAt: undefined,
@@ -748,7 +751,7 @@ export function useBoardActions({
description: `Marked as verified: ${truncateDescription(feature.description)}`, description: `Marked as verified: ${truncateDescription(feature.description)}`,
}); });
}, },
[persistFeatureUpdate] [moveFeature, persistFeatureUpdate]
); );
const handleMoveBackToInProgress = useCallback( const handleMoveBackToInProgress = useCallback(
@@ -757,12 +760,13 @@ export function useBoardActions({
status: 'in_progress' as const, status: 'in_progress' as const,
startedAt: new Date().toISOString(), startedAt: new Date().toISOString(),
}; };
updateFeature(feature.id, updates);
persistFeatureUpdate(feature.id, updates); persistFeatureUpdate(feature.id, updates);
toast.info('Feature moved back', { toast.info('Feature moved back', {
description: `Moved back to In Progress: ${truncateDescription(feature.description)}`, description: `Moved back to In Progress: ${truncateDescription(feature.description)}`,
}); });
}, },
[persistFeatureUpdate] [updateFeature, persistFeatureUpdate]
); );
const handleOpenFollowUp = useCallback( const handleOpenFollowUp = useCallback(
@@ -881,6 +885,7 @@ export function useBoardActions({
); );
if (result.success) { if (result.success) {
moveFeature(feature.id, 'verified');
persistFeatureUpdate(feature.id, { status: 'verified' }); persistFeatureUpdate(feature.id, { status: 'verified' });
toast.success('Feature committed', { toast.success('Feature committed', {
description: `Committed and verified: ${truncateDescription(feature.description)}`, description: `Committed and verified: ${truncateDescription(feature.description)}`,
@@ -902,7 +907,7 @@ export function useBoardActions({
await loadFeatures(); await loadFeatures();
} }
}, },
[currentProject, persistFeatureUpdate, loadFeatures, onWorktreeCreated] [currentProject, moveFeature, persistFeatureUpdate, loadFeatures, onWorktreeCreated]
); );
const handleMergeFeature = useCallback( const handleMergeFeature = useCallback(
@@ -946,12 +951,17 @@ export function useBoardActions({
const handleCompleteFeature = useCallback( const handleCompleteFeature = useCallback(
(feature: Feature) => { (feature: Feature) => {
persistFeatureUpdate(feature.id, { status: 'completed' as const }); const updates = {
status: 'completed' as const,
};
updateFeature(feature.id, updates);
persistFeatureUpdate(feature.id, updates);
toast.success('Feature completed', { toast.success('Feature completed', {
description: `Archived: ${truncateDescription(feature.description)}`, description: `Archived: ${truncateDescription(feature.description)}`,
}); });
}, },
[persistFeatureUpdate] [updateFeature, persistFeatureUpdate]
); );
const handleUnarchiveFeature = useCallback( const handleUnarchiveFeature = useCallback(
@@ -968,7 +978,11 @@ export function useBoardActions({
(projectPath ? isPrimaryWorktreeBranch(projectPath, currentWorktreeBranch) : true) (projectPath ? isPrimaryWorktreeBranch(projectPath, currentWorktreeBranch) : true)
: featureBranch === currentWorktreeBranch; : featureBranch === currentWorktreeBranch;
persistFeatureUpdate(feature.id, { status: 'verified' as const }); const updates: Partial<Feature> = {
status: 'verified' as const,
};
updateFeature(feature.id, updates);
persistFeatureUpdate(feature.id, updates);
if (willBeVisibleOnCurrentView) { if (willBeVisibleOnCurrentView) {
toast.success('Feature restored', { toast.success('Feature restored', {
@@ -980,7 +994,13 @@ export function useBoardActions({
}); });
} }
}, },
[persistFeatureUpdate, currentWorktreeBranch, projectPath, isPrimaryWorktreeBranch] [
updateFeature,
persistFeatureUpdate,
currentWorktreeBranch,
projectPath,
isPrimaryWorktreeBranch,
]
); );
const handleViewOutput = useCallback( const handleViewOutput = useCallback(
@@ -1011,13 +1031,6 @@ export function useBoardActions({
const handleForceStopFeature = useCallback( const handleForceStopFeature = useCallback(
async (feature: Feature) => { async (feature: Feature) => {
// Mark this feature as transitioning so WebSocket-driven query invalidation
// (useAutoModeQueryInvalidation) skips redundant cache invalidations while
// persistFeatureUpdate is handling the optimistic update. Without this guard,
// auto_mode_error / auto_mode_stopped WS events race with the optimistic
// update and cause cache flip-flops that cascade through useBoardColumnFeatures,
// triggering React error #185 on mobile.
markFeatureTransitioning(feature.id);
try { try {
await stopFeature(feature.id); await stopFeature(feature.id);
@@ -1035,11 +1048,25 @@ export function useBoardActions({
removeRunningTaskFromAllWorktrees(currentProject.id, feature.id); removeRunningTaskFromAllWorktrees(currentProject.id, feature.id);
} }
// Optimistically update the React Query features cache so the board
// moves the card immediately. Without this, the card stays in
// "in_progress" until the next poll cycle (30s) because the async
// refetch races with the persistFeatureUpdate write.
if (currentProject) {
queryClient.setQueryData(
queryKeys.features.all(currentProject.path),
(oldFeatures: Feature[] | undefined) => {
if (!oldFeatures) return oldFeatures;
return oldFeatures.map((f) =>
f.id === feature.id ? { ...f, status: targetStatus } : f
);
}
);
}
if (targetStatus !== feature.status) { if (targetStatus !== feature.status) {
// persistFeatureUpdate handles the optimistic RQ cache update, the moveFeature(feature.id, targetStatus);
// Zustand store update (on server response), and the final cache // Must await to ensure file is written before user can restart
// invalidation internally — no need for separate queryClient.setQueryData
// or moveFeature calls which would cause redundant re-renders.
await persistFeatureUpdate(feature.id, { status: targetStatus }); await persistFeatureUpdate(feature.id, { status: targetStatus });
} }
@@ -1056,15 +1083,9 @@ export function useBoardActions({
toast.error('Failed to stop agent', { toast.error('Failed to stop agent', {
description: error instanceof Error ? error.message : 'An error occurred', description: error instanceof Error ? error.message : 'An error occurred',
}); });
} finally {
// Delay unmarking so the refetch triggered by persistFeatureUpdate's
// invalidateQueries() has time to settle before WS-driven invalidations
// are allowed through again. Without this, a WS event arriving during
// the refetch window would trigger a conflicting invalidation.
setTimeout(() => unmarkFeatureTransitioning(feature.id), 500);
} }
}, },
[stopFeature, persistFeatureUpdate, currentProject] [stopFeature, moveFeature, persistFeatureUpdate, currentProject, queryClient]
); );
const handleStartNextFeatures = useCallback(async () => { const handleStartNextFeatures = useCallback(async () => {

View File

@@ -1,5 +1,5 @@
// @ts-nocheck - column filtering logic with dependency resolution and status mapping // @ts-nocheck - column filtering logic with dependency resolution and status mapping
import { useMemo, useCallback, useEffect } from 'react'; import { useMemo, useCallback, useEffect, useRef } from 'react';
import { Feature, useAppStore } from '@/store/app-store'; import { Feature, useAppStore } from '@/store/app-store';
import { import {
createFeatureMap, createFeatureMap,
@@ -177,6 +177,9 @@ export function useBoardColumnFeatures({
(state) => state.clearRecentlyCompletedFeatures (state) => state.clearRecentlyCompletedFeatures
); );
// Track previous feature IDs to detect when features list has been refreshed
const prevFeatureIdsRef = useRef<Set<string>>(new Set());
// Clear recently completed features when the cache refreshes with updated statuses. // Clear recently completed features when the cache refreshes with updated statuses.
// //
// RACE CONDITION SCENARIO THIS PREVENTS: // RACE CONDITION SCENARIO THIS PREVENTS:
@@ -190,16 +193,12 @@ export function useBoardColumnFeatures({
// //
// When the refetch completes with fresh data (status='verified'/'completed'), // When the refetch completes with fresh data (status='verified'/'completed'),
// this effect clears the recentlyCompletedFeatures set since it's no longer needed. // this effect clears the recentlyCompletedFeatures set since it's no longer needed.
// Clear recently completed features when the cache refreshes with updated statuses.
// IMPORTANT: Only depend on `features` (not `recentlyCompletedFeatures`) to avoid a
// re-trigger loop where clearing the set creates a new reference that re-fires this effect.
// Read recentlyCompletedFeatures from the store directly to get the latest value without
// subscribing to it as a dependency.
useEffect(() => { useEffect(() => {
const currentRecentlyCompleted = useAppStore.getState().recentlyCompletedFeatures; const currentIds = new Set(features.map((f) => f.id));
if (currentRecentlyCompleted.size === 0) return;
const hasUpdatedStatus = Array.from(currentRecentlyCompleted).some((featureId) => { // Check if any recently completed features now have terminal statuses in the new data
// If so, we can clear the tracking since the cache is now fresh
const hasUpdatedStatus = Array.from(recentlyCompletedFeatures).some((featureId) => {
const feature = features.find((f) => f.id === featureId); const feature = features.find((f) => f.id === featureId);
return feature && (feature.status === 'verified' || feature.status === 'completed'); return feature && (feature.status === 'verified' || feature.status === 'completed');
}); });
@@ -207,7 +206,9 @@ export function useBoardColumnFeatures({
if (hasUpdatedStatus) { if (hasUpdatedStatus) {
clearRecentlyCompletedFeatures(); clearRecentlyCompletedFeatures();
} }
}, [features, clearRecentlyCompletedFeatures]);
prevFeatureIdsRef.current = currentIds;
}, [features, recentlyCompletedFeatures, clearRecentlyCompletedFeatures]);
// Memoize column features to prevent unnecessary re-renders // Memoize column features to prevent unnecessary re-renders
const columnFeaturesMap = useMemo(() => { const columnFeaturesMap = useMemo(() => {

View File

@@ -38,6 +38,7 @@ export function useBoardDragDrop({
// subscribing to the entire store. Bare useAppStore() causes the host component // subscribing to the entire store. Bare useAppStore() causes the host component
// (BoardView) to re-render on EVERY store change, which cascades through effects // (BoardView) to re-render on EVERY store change, which cascades through effects
// and triggers React error #185 (maximum update depth exceeded). // and triggers React error #185 (maximum update depth exceeded).
const moveFeature = useAppStore((s) => s.moveFeature);
const updateFeature = useAppStore((s) => s.updateFeature); const updateFeature = useAppStore((s) => s.updateFeature);
// Note: getOrCreateWorktreeForFeature removed - worktrees are now created server-side // Note: getOrCreateWorktreeForFeature removed - worktrees are now created server-side
@@ -206,8 +207,7 @@ export function useBoardDragDrop({
if (targetStatus === draggedFeature.status) return; if (targetStatus === draggedFeature.status) return;
// Handle different drag scenarios // Handle different drag scenarios
// Note: persistFeatureUpdate handles optimistic RQ cache update internally, // Note: Worktrees are created server-side at execution time based on feature.branchName
// so no separate moveFeature() call is needed.
if (draggedFeature.status === 'backlog' || draggedFeature.status === 'merge_conflict') { if (draggedFeature.status === 'backlog' || draggedFeature.status === 'merge_conflict') {
// From backlog // From backlog
if (targetStatus === 'in_progress') { if (targetStatus === 'in_progress') {
@@ -215,6 +215,7 @@ export function useBoardDragDrop({
// Server will derive workDir from feature.branchName // Server will derive workDir from feature.branchName
await handleStartImplementation(draggedFeature); await handleStartImplementation(draggedFeature);
} else { } else {
moveFeature(featureId, targetStatus);
persistFeatureUpdate(featureId, { status: targetStatus }); persistFeatureUpdate(featureId, { status: targetStatus });
} }
} else if (draggedFeature.status === 'waiting_approval') { } else if (draggedFeature.status === 'waiting_approval') {
@@ -222,6 +223,7 @@ export function useBoardDragDrop({
// NOTE: This check must come BEFORE skipTests check because waiting_approval // NOTE: This check must come BEFORE skipTests check because waiting_approval
// features often have skipTests=true, and we want status-based handling first // features often have skipTests=true, and we want status-based handling first
if (targetStatus === 'verified') { if (targetStatus === 'verified') {
moveFeature(featureId, 'verified');
// Clear justFinishedAt timestamp when manually verifying via drag // Clear justFinishedAt timestamp when manually verifying via drag
persistFeatureUpdate(featureId, { persistFeatureUpdate(featureId, {
status: 'verified', status: 'verified',
@@ -235,6 +237,7 @@ export function useBoardDragDrop({
}); });
} else if (targetStatus === 'backlog') { } else if (targetStatus === 'backlog') {
// Allow moving waiting_approval cards back to backlog // Allow moving waiting_approval cards back to backlog
moveFeature(featureId, 'backlog');
// Clear justFinishedAt timestamp when moving back to backlog // Clear justFinishedAt timestamp when moving back to backlog
persistFeatureUpdate(featureId, { persistFeatureUpdate(featureId, {
status: 'backlog', status: 'backlog',
@@ -266,6 +269,7 @@ export function useBoardDragDrop({
}); });
} }
} }
moveFeature(featureId, 'backlog');
persistFeatureUpdate(featureId, { status: 'backlog' }); persistFeatureUpdate(featureId, { status: 'backlog' });
toast.info( toast.info(
isRunningTask isRunningTask
@@ -287,6 +291,7 @@ export function useBoardDragDrop({
return; return;
} else if (targetStatus === 'verified' && draggedFeature.skipTests) { } else if (targetStatus === 'verified' && draggedFeature.skipTests) {
// Manual verify via drag (only for skipTests features) // Manual verify via drag (only for skipTests features)
moveFeature(featureId, 'verified');
persistFeatureUpdate(featureId, { status: 'verified' }); persistFeatureUpdate(featureId, { status: 'verified' });
toast.success('Feature verified', { toast.success('Feature verified', {
description: `Marked as verified: ${draggedFeature.description.slice( description: `Marked as verified: ${draggedFeature.description.slice(
@@ -299,6 +304,7 @@ export function useBoardDragDrop({
// skipTests feature being moved between verified and waiting_approval // skipTests feature being moved between verified and waiting_approval
if (targetStatus === 'waiting_approval' && draggedFeature.status === 'verified') { if (targetStatus === 'waiting_approval' && draggedFeature.status === 'verified') {
// Move verified feature back to waiting_approval // Move verified feature back to waiting_approval
moveFeature(featureId, 'waiting_approval');
persistFeatureUpdate(featureId, { status: 'waiting_approval' }); persistFeatureUpdate(featureId, { status: 'waiting_approval' });
toast.info('Feature moved back', { toast.info('Feature moved back', {
description: `Moved back to Waiting Approval: ${draggedFeature.description.slice( description: `Moved back to Waiting Approval: ${draggedFeature.description.slice(
@@ -308,6 +314,7 @@ export function useBoardDragDrop({
}); });
} else if (targetStatus === 'backlog') { } else if (targetStatus === 'backlog') {
// Allow moving skipTests cards back to backlog (from verified) // Allow moving skipTests cards back to backlog (from verified)
moveFeature(featureId, 'backlog');
persistFeatureUpdate(featureId, { status: 'backlog' }); persistFeatureUpdate(featureId, { status: 'backlog' });
toast.info('Feature moved to backlog', { toast.info('Feature moved to backlog', {
description: `Moved to Backlog: ${draggedFeature.description.slice( description: `Moved to Backlog: ${draggedFeature.description.slice(
@@ -320,6 +327,7 @@ export function useBoardDragDrop({
// Handle verified TDD (non-skipTests) features being moved back // Handle verified TDD (non-skipTests) features being moved back
if (targetStatus === 'waiting_approval') { if (targetStatus === 'waiting_approval') {
// Move verified feature back to waiting_approval // Move verified feature back to waiting_approval
moveFeature(featureId, 'waiting_approval');
persistFeatureUpdate(featureId, { status: 'waiting_approval' }); persistFeatureUpdate(featureId, { status: 'waiting_approval' });
toast.info('Feature moved back', { toast.info('Feature moved back', {
description: `Moved back to Waiting Approval: ${draggedFeature.description.slice( description: `Moved back to Waiting Approval: ${draggedFeature.description.slice(
@@ -329,6 +337,7 @@ export function useBoardDragDrop({
}); });
} else if (targetStatus === 'backlog') { } else if (targetStatus === 'backlog') {
// Allow moving verified cards back to backlog // Allow moving verified cards back to backlog
moveFeature(featureId, 'backlog');
persistFeatureUpdate(featureId, { status: 'backlog' }); persistFeatureUpdate(featureId, { status: 'backlog' });
toast.info('Feature moved to backlog', { toast.info('Feature moved to backlog', {
description: `Moved to Backlog: ${draggedFeature.description.slice( description: `Moved to Backlog: ${draggedFeature.description.slice(
@@ -342,6 +351,7 @@ export function useBoardDragDrop({
[ [
features, features,
runningAutoTasks, runningAutoTasks,
moveFeature,
updateFeature, updateFeature,
persistFeatureUpdate, persistFeatureUpdate,
handleStartImplementation, handleStartImplementation,

View File

@@ -87,22 +87,37 @@ export function useBoardFeatures({ currentProject }: UseBoardFeaturesProps) {
); );
// Subscribe to auto mode events for notifications (ding sound, toasts) // Subscribe to auto mode events for notifications (ding sound, toasts)
// Note: Query invalidation is handled by useAutoModeQueryInvalidation in the root. // Note: Query invalidation is handled by useAutoModeQueryInvalidation in the root
// Note: removeRunningTask is handled by useAutoMode — do NOT duplicate it here,
// as duplicate Zustand mutations cause re-render cascades (React error #185).
useEffect(() => { useEffect(() => {
const api = getElectronAPI(); const api = getElectronAPI();
if (!api?.autoMode || !currentProject) return; if (!api?.autoMode || !currentProject) return;
const { removeRunningTask } = useAppStore.getState();
const projectId = currentProject.id;
const projectPath = currentProject.path; const projectPath = currentProject.path;
const unsubscribe = api.autoMode.onEvent((event) => { const unsubscribe = api.autoMode.onEvent((event) => {
// Check if event is for the current project by matching projectPath // Check if event is for the current project by matching projectPath
const eventProjectPath = ('projectPath' in event && event.projectPath) as string | undefined; const eventProjectPath = ('projectPath' in event && event.projectPath) as string | undefined;
if (eventProjectPath && eventProjectPath !== projectPath) { if (eventProjectPath && eventProjectPath !== projectPath) {
// Event is for a different project, ignore it
logger.debug(
`Ignoring auto mode event for different project: ${eventProjectPath} (current: ${projectPath})`
);
return; return;
} }
// Use event's projectPath or projectId if available, otherwise use current project
// Board view only reacts to events for the currently selected project
const eventProjectId = ('projectId' in event && event.projectId) || projectId;
// NOTE: auto_mode_feature_start and auto_mode_feature_complete are NOT handled here
// for feature list reloading. That is handled by useAutoModeQueryInvalidation which
// invalidates the features.all query on those events. Duplicate invalidation here
// caused a re-render cascade through DndContext that triggered React error #185
// (maximum update depth exceeded), crashing the board view with an infinite spinner
// when a new feature was added and moved to in_progress.
if (event.type === 'auto_mode_feature_complete') { if (event.type === 'auto_mode_feature_complete') {
// Play ding sound when feature is done (unless muted) // Play ding sound when feature is done (unless muted)
const { muteDoneSound } = useAppStore.getState(); const { muteDoneSound } = useAppStore.getState();
@@ -111,7 +126,14 @@ export function useBoardFeatures({ currentProject }: UseBoardFeaturesProps) {
audio.play().catch((err) => logger.warn('Could not play ding sound:', err)); audio.play().catch((err) => logger.warn('Could not play ding sound:', err));
} }
} else if (event.type === 'auto_mode_error') { } else if (event.type === 'auto_mode_error') {
// Show error toast (removeRunningTask is handled by useAutoMode, not here) // Remove from running tasks
if (event.featureId) {
const eventBranchName =
'branchName' in event && event.branchName !== undefined ? event.branchName : null;
removeRunningTask(eventProjectId, eventBranchName, event.featureId);
}
// Show error toast
const isAuthError = const isAuthError =
event.errorType === 'authentication' || event.errorType === 'authentication' ||
(event.error && (event.error &&

View File

@@ -281,10 +281,6 @@ function VirtualizedList<Item extends VirtualListItem>({
); );
} }
// Stable empty Set to use as default prop value. Using `new Set()` inline in
// the destructuring creates a new reference on every render, defeating memo.
const EMPTY_FEATURE_IDS = new Set<string>();
export const KanbanBoard = memo(function KanbanBoard({ export const KanbanBoard = memo(function KanbanBoard({
activeFeature, activeFeature,
getColumnFeatures, getColumnFeatures,
@@ -321,7 +317,7 @@ export const KanbanBoard = memo(function KanbanBoard({
onOpenPipelineSettings, onOpenPipelineSettings,
isSelectionMode = false, isSelectionMode = false,
selectionTarget = null, selectionTarget = null,
selectedFeatureIds = EMPTY_FEATURE_IDS, selectedFeatureIds = new Set(),
onToggleFeatureSelection, onToggleFeatureSelection,
onToggleSelectionMode, onToggleSelectionMode,
onAiSuggest, onAiSuggest,

View File

@@ -77,21 +77,14 @@ export function useDevServerLogs({ worktreePath, autoSubscribe = true }: UseDevS
// Buffer for batching rapid output events into fewer setState calls. // Buffer for batching rapid output events into fewer setState calls.
// Content accumulates here and is flushed via requestAnimationFrame, // Content accumulates here and is flushed via requestAnimationFrame,
// ensuring at most one React re-render per animation frame (~60fps max). // ensuring at most one React re-render per animation frame (~60fps max).
// A fallback setTimeout ensures the buffer is flushed even when RAF is
// throttled (e.g., when the tab is in the background).
const pendingOutputRef = useRef(''); const pendingOutputRef = useRef('');
const rafIdRef = useRef<number | null>(null); const rafIdRef = useRef<number | null>(null);
const timerIdRef = useRef<ReturnType<typeof setTimeout> | null>(null);
const resetPendingOutput = useCallback(() => { const resetPendingOutput = useCallback(() => {
if (rafIdRef.current !== null) { if (rafIdRef.current !== null) {
cancelAnimationFrame(rafIdRef.current); cancelAnimationFrame(rafIdRef.current);
rafIdRef.current = null; rafIdRef.current = null;
} }
if (timerIdRef.current !== null) {
clearTimeout(timerIdRef.current);
timerIdRef.current = null;
}
pendingOutputRef.current = ''; pendingOutputRef.current = '';
}, []); }, []);
@@ -169,12 +162,7 @@ export function useDevServerLogs({ worktreePath, autoSubscribe = true }: UseDevS
}, [resetPendingOutput]); }, [resetPendingOutput]);
const flushPendingOutput = useCallback(() => { const flushPendingOutput = useCallback(() => {
// Clear both scheduling handles to prevent duplicate flushes
rafIdRef.current = null; rafIdRef.current = null;
if (timerIdRef.current !== null) {
clearTimeout(timerIdRef.current);
timerIdRef.current = null;
}
const content = pendingOutputRef.current; const content = pendingOutputRef.current;
if (!content) return; if (!content) return;
pendingOutputRef.current = ''; pendingOutputRef.current = '';
@@ -204,31 +192,13 @@ export function useDevServerLogs({ worktreePath, autoSubscribe = true }: UseDevS
* *
* Uses requestAnimationFrame to batch rapid output events into at most * Uses requestAnimationFrame to batch rapid output events into at most
* one React state update per frame, preventing excessive re-renders. * one React state update per frame, preventing excessive re-renders.
* A fallback setTimeout(250ms) ensures the buffer is flushed even when
* RAF is throttled (e.g., when the tab is in the background).
* If the pending buffer reaches MAX_LOG_BUFFER_SIZE, flushes immediately
* to prevent unbounded memory growth.
*/ */
const appendLogs = useCallback( const appendLogs = useCallback(
(content: string) => { (content: string) => {
pendingOutputRef.current += content; pendingOutputRef.current += content;
// Flush immediately if buffer has reached the size limit
if (pendingOutputRef.current.length >= MAX_LOG_BUFFER_SIZE) {
flushPendingOutput();
return;
}
// Schedule a RAF flush if not already scheduled
if (rafIdRef.current === null) { if (rafIdRef.current === null) {
rafIdRef.current = requestAnimationFrame(flushPendingOutput); rafIdRef.current = requestAnimationFrame(flushPendingOutput);
} }
// Schedule a fallback timer flush if not already scheduled,
// to handle cases where RAF is throttled (background tab)
if (timerIdRef.current === null) {
timerIdRef.current = setTimeout(flushPendingOutput, 250);
}
}, },
[flushPendingOutput] [flushPendingOutput]
); );

View File

@@ -22,8 +22,6 @@ function arraysEqual(a: string[], b: string[]): boolean {
return a.every((id) => set.has(id)); return a.every((id) => set.has(id));
} }
const AUTO_MODE_POLLING_INTERVAL = 30000; const AUTO_MODE_POLLING_INTERVAL = 30000;
// Stable empty array reference to avoid re-renders from `[] !== []`
const EMPTY_TASKS: string[] = [];
/** /**
* Generate a worktree key for session storage * Generate a worktree key for session storage
@@ -79,12 +77,8 @@ function isPlanApprovalEvent(
* @param worktree - Optional worktree info. If not provided, uses main worktree (branchName = null) * @param worktree - Optional worktree info. If not provided, uses main worktree (branchName = null)
*/ */
export function useAutoMode(worktree?: WorktreeInfo) { export function useAutoMode(worktree?: WorktreeInfo) {
// Subscribe to stable action functions and scalar state via useShallow.
// IMPORTANT: Do NOT subscribe to autoModeByWorktree here. That object gets a
// new reference on every Zustand mutation to ANY worktree, which would re-render
// every useAutoMode consumer on every store change. Instead, we subscribe to the
// specific worktree's state below using a targeted selector.
const { const {
autoModeByWorktree,
setAutoModeRunning, setAutoModeRunning,
addRunningTask, addRunningTask,
removeRunningTask, removeRunningTask,
@@ -99,6 +93,7 @@ export function useAutoMode(worktree?: WorktreeInfo) {
addRecentlyCompletedFeature, addRecentlyCompletedFeature,
} = useAppStore( } = useAppStore(
useShallow((state) => ({ useShallow((state) => ({
autoModeByWorktree: state.autoModeByWorktree,
setAutoModeRunning: state.setAutoModeRunning, setAutoModeRunning: state.setAutoModeRunning,
addRunningTask: state.addRunningTask, addRunningTask: state.addRunningTask,
removeRunningTask: state.removeRunningTask, removeRunningTask: state.removeRunningTask,
@@ -149,109 +144,41 @@ export function useAutoMode(worktree?: WorktreeInfo) {
[projects] [projects]
); );
// Get worktree-specific auto mode state using a TARGETED selector with // Get worktree-specific auto mode state
// VALUE-BASED equality. This is critical for preventing cascading re-renders
// in board view, where DndContext amplifies every parent re-render.
//
// Why value-based equality matters: Every Zustand `set()` call (including
// `addAutoModeActivity` which fires on every WS event) triggers all subscriber
// selectors to re-run. Even our targeted selector that reads a specific key
// would return a new object reference (from the spread in `removeRunningTask`
// etc.), causing a re-render even when the actual values haven't changed.
// By extracting primitives and comparing with a custom equality function,
// we only re-render when isRunning/runningTasks/maxConcurrency actually change.
const projectId = currentProject?.id; const projectId = currentProject?.id;
const worktreeKey = useMemo( const worktreeAutoModeState = useMemo(() => {
() => (projectId ? getWorktreeKey(projectId, branchName) : null), if (!projectId)
[projectId, branchName, getWorktreeKey]
);
// Subscribe to this specific worktree's state using useShallow.
// useShallow compares each property of the returned object with Object.is,
// so primitive properties (isRunning: boolean, maxConcurrency: number) are
// naturally stable. Only runningTasks (array) needs additional stabilization
// since filter()/spread creates new array references even for identical content.
const { worktreeIsRunning, worktreeRunningTasksRaw, worktreeMaxConcurrency } = useAppStore(
useShallow((state) => {
if (!worktreeKey) {
return {
worktreeIsRunning: false,
worktreeRunningTasksRaw: EMPTY_TASKS,
worktreeMaxConcurrency: undefined as number | undefined,
};
}
const wt = state.autoModeByWorktree[worktreeKey];
if (!wt) {
return {
worktreeIsRunning: false,
worktreeRunningTasksRaw: EMPTY_TASKS,
worktreeMaxConcurrency: undefined as number | undefined,
};
}
return { return {
worktreeIsRunning: wt.isRunning, isRunning: false,
worktreeRunningTasksRaw: wt.runningTasks, runningTasks: [],
worktreeMaxConcurrency: wt.maxConcurrency, branchName: null,
maxConcurrency: DEFAULT_MAX_CONCURRENCY,
}; };
}) const key = getWorktreeKey(projectId, branchName);
); return (
// Stabilize runningTasks: useShallow uses Object.is per property, but autoModeByWorktree[key] || {
// runningTasks gets a new array ref after removeRunningTask/addRunningTask. isRunning: false,
// Cache the previous value and only update when content actually changes. runningTasks: [],
const prevTasksRef = useRef<string[]>(EMPTY_TASKS); branchName,
const worktreeRunningTasks = useMemo(() => { maxConcurrency: DEFAULT_MAX_CONCURRENCY,
if (worktreeRunningTasksRaw === prevTasksRef.current) return prevTasksRef.current; }
if (arraysEqual(prevTasksRef.current, worktreeRunningTasksRaw)) return prevTasksRef.current; );
prevTasksRef.current = worktreeRunningTasksRaw; }, [autoModeByWorktree, projectId, branchName, getWorktreeKey]);
return worktreeRunningTasksRaw;
}, [worktreeRunningTasksRaw]);
const isAutoModeRunning = worktreeIsRunning; const isAutoModeRunning = worktreeAutoModeState.isRunning;
const runningAutoTasks = worktreeRunningTasks; const runningAutoTasks = worktreeAutoModeState.runningTasks;
// Use worktreeMaxConcurrency (from the reactive per-key selector) so // Use the subscribed worktreeAutoModeState.maxConcurrency (from the reactive
// canStartNewTask stays reactive when refreshStatus updates worktree state // autoModeByWorktree store slice) so canStartNewTask stays reactive when
// or when the global setting changes. // refreshStatus updates worktree state or when the global setting changes.
// Falls back to the subscribed globalMaxConcurrency (also reactive) when no
// per-worktree value is set, and to DEFAULT_MAX_CONCURRENCY when no project.
const maxConcurrency = projectId const maxConcurrency = projectId
? (worktreeMaxConcurrency ?? globalMaxConcurrency) ? (worktreeAutoModeState.maxConcurrency ?? globalMaxConcurrency)
: DEFAULT_MAX_CONCURRENCY; : DEFAULT_MAX_CONCURRENCY;
// Check if we can start a new task based on concurrency limit // Check if we can start a new task based on concurrency limit
const canStartNewTask = runningAutoTasks.length < maxConcurrency; const canStartNewTask = runningAutoTasks.length < maxConcurrency;
// Batch addAutoModeActivity calls to reduce Zustand set() frequency.
// Without batching, each WS event (especially auto_mode_progress which fires
// rapidly during streaming) triggers a separate set() → all subscriber selectors
// re-evaluate → on mobile this overwhelms React's batching → crash.
// This batches activities in a ref and flushes them in a single set() call.
const pendingActivitiesRef = useRef<Parameters<typeof addAutoModeActivity>[0][]>([]);
const flushTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null);
const batchedAddAutoModeActivity = useCallback(
(activity: Parameters<typeof addAutoModeActivity>[0]) => {
pendingActivitiesRef.current.push(activity);
if (!flushTimerRef.current) {
flushTimerRef.current = setTimeout(() => {
const batch = pendingActivitiesRef.current;
pendingActivitiesRef.current = [];
flushTimerRef.current = null;
// Flush all pending activities in a single store update
for (const act of batch) {
addAutoModeActivity(act);
}
}, 100);
}
},
[addAutoModeActivity]
);
// Cleanup flush timer on unmount
useEffect(() => {
return () => {
if (flushTimerRef.current) {
clearTimeout(flushTimerRef.current);
}
};
}, []);
// Ref to prevent refreshStatus and WebSocket handlers from overwriting optimistic state // Ref to prevent refreshStatus and WebSocket handlers from overwriting optimistic state
// during start/stop transitions. // during start/stop transitions.
const isTransitioningRef = useRef(false); const isTransitioningRef = useRef(false);
@@ -571,7 +498,7 @@ export function useAutoMode(worktree?: WorktreeInfo) {
case 'auto_mode_feature_start': case 'auto_mode_feature_start':
if (event.featureId) { if (event.featureId) {
addRunningTask(eventProjectId, eventBranchName, event.featureId); addRunningTask(eventProjectId, eventBranchName, event.featureId);
batchedAddAutoModeActivity({ addAutoModeActivity({
featureId: event.featureId, featureId: event.featureId,
type: 'start', type: 'start',
message: `Started working on feature`, message: `Started working on feature`,
@@ -587,7 +514,7 @@ export function useAutoMode(worktree?: WorktreeInfo) {
// briefly appear in backlog due to stale cache data // briefly appear in backlog due to stale cache data
addRecentlyCompletedFeature(event.featureId); addRecentlyCompletedFeature(event.featureId);
removeRunningTask(eventProjectId, eventBranchName, event.featureId); removeRunningTask(eventProjectId, eventBranchName, event.featureId);
batchedAddAutoModeActivity({ addAutoModeActivity({
featureId: event.featureId, featureId: event.featureId,
type: 'complete', type: 'complete',
message: event.passes message: event.passes
@@ -624,7 +551,7 @@ export function useAutoMode(worktree?: WorktreeInfo) {
? `Authentication failed: Please check your API key in Settings or run 'claude login' in terminal to re-authenticate.` ? `Authentication failed: Please check your API key in Settings or run 'claude login' in terminal to re-authenticate.`
: event.error; : event.error;
batchedAddAutoModeActivity({ addAutoModeActivity({
featureId: event.featureId, featureId: event.featureId,
type: 'error', type: 'error',
message: errorMessage, message: errorMessage,
@@ -641,7 +568,7 @@ export function useAutoMode(worktree?: WorktreeInfo) {
case 'auto_mode_progress': case 'auto_mode_progress':
// Log progress updates (throttle to avoid spam) // Log progress updates (throttle to avoid spam)
if (event.featureId && event.content && event.content.length > 10) { if (event.featureId && event.content && event.content.length > 10) {
batchedAddAutoModeActivity({ addAutoModeActivity({
featureId: event.featureId, featureId: event.featureId,
type: 'progress', type: 'progress',
message: event.content.substring(0, 200), // Limit message length message: event.content.substring(0, 200), // Limit message length
@@ -652,7 +579,7 @@ export function useAutoMode(worktree?: WorktreeInfo) {
case 'auto_mode_tool': case 'auto_mode_tool':
// Log tool usage // Log tool usage
if (event.featureId && event.tool) { if (event.featureId && event.tool) {
batchedAddAutoModeActivity({ addAutoModeActivity({
featureId: event.featureId, featureId: event.featureId,
type: 'tool', type: 'tool',
message: `Using tool: ${event.tool}`, message: `Using tool: ${event.tool}`,
@@ -665,7 +592,7 @@ export function useAutoMode(worktree?: WorktreeInfo) {
// Log phase transitions (Planning, Action, Verification) // Log phase transitions (Planning, Action, Verification)
if (event.featureId && event.phase && event.message) { if (event.featureId && event.phase && event.message) {
logger.debug(`[AutoMode] Phase: ${event.phase} for ${event.featureId}`); logger.debug(`[AutoMode] Phase: ${event.phase} for ${event.featureId}`);
batchedAddAutoModeActivity({ addAutoModeActivity({
featureId: event.featureId, featureId: event.featureId,
type: event.phase, type: event.phase,
message: event.message, message: event.message,
@@ -691,7 +618,7 @@ export function useAutoMode(worktree?: WorktreeInfo) {
// Log when planning phase begins // Log when planning phase begins
if (event.featureId && event.mode && event.message) { if (event.featureId && event.mode && event.message) {
logger.debug(`[AutoMode] Planning started (${event.mode}) for ${event.featureId}`); logger.debug(`[AutoMode] Planning started (${event.mode}) for ${event.featureId}`);
batchedAddAutoModeActivity({ addAutoModeActivity({
featureId: event.featureId, featureId: event.featureId,
type: 'planning', type: 'planning',
message: event.message, message: event.message,
@@ -704,7 +631,7 @@ export function useAutoMode(worktree?: WorktreeInfo) {
// Log when plan is approved by user // Log when plan is approved by user
if (event.featureId) { if (event.featureId) {
logger.debug(`[AutoMode] Plan approved for ${event.featureId}`); logger.debug(`[AutoMode] Plan approved for ${event.featureId}`);
batchedAddAutoModeActivity({ addAutoModeActivity({
featureId: event.featureId, featureId: event.featureId,
type: 'action', type: 'action',
message: event.hasEdits message: event.hasEdits
@@ -719,7 +646,7 @@ export function useAutoMode(worktree?: WorktreeInfo) {
// Log when plan is auto-approved (requirePlanApproval=false) // Log when plan is auto-approved (requirePlanApproval=false)
if (event.featureId) { if (event.featureId) {
logger.debug(`[AutoMode] Plan auto-approved for ${event.featureId}`); logger.debug(`[AutoMode] Plan auto-approved for ${event.featureId}`);
batchedAddAutoModeActivity({ addAutoModeActivity({
featureId: event.featureId, featureId: event.featureId,
type: 'action', type: 'action',
message: 'Plan auto-approved, starting implementation...', message: 'Plan auto-approved, starting implementation...',
@@ -738,7 +665,7 @@ export function useAutoMode(worktree?: WorktreeInfo) {
logger.debug( logger.debug(
`[AutoMode] Plan revision requested for ${event.featureId} (v${revisionEvent.planVersion})` `[AutoMode] Plan revision requested for ${event.featureId} (v${revisionEvent.planVersion})`
); );
batchedAddAutoModeActivity({ addAutoModeActivity({
featureId: event.featureId, featureId: event.featureId,
type: 'planning', type: 'planning',
message: `Revising plan based on feedback (v${revisionEvent.planVersion})...`, message: `Revising plan based on feedback (v${revisionEvent.planVersion})...`,
@@ -754,7 +681,7 @@ export function useAutoMode(worktree?: WorktreeInfo) {
logger.debug( logger.debug(
`[AutoMode] Task ${taskEvent.taskId} started for ${event.featureId}: ${taskEvent.taskDescription}` `[AutoMode] Task ${taskEvent.taskId} started for ${event.featureId}: ${taskEvent.taskDescription}`
); );
batchedAddAutoModeActivity({ addAutoModeActivity({
featureId: event.featureId, featureId: event.featureId,
type: 'progress', type: 'progress',
message: `▶ Starting ${taskEvent.taskId}: ${taskEvent.taskDescription}`, message: `▶ Starting ${taskEvent.taskId}: ${taskEvent.taskDescription}`,
@@ -769,7 +696,7 @@ export function useAutoMode(worktree?: WorktreeInfo) {
logger.debug( logger.debug(
`[AutoMode] Task ${taskEvent.taskId} completed for ${event.featureId} (${taskEvent.tasksCompleted}/${taskEvent.tasksTotal})` `[AutoMode] Task ${taskEvent.taskId} completed for ${event.featureId} (${taskEvent.tasksCompleted}/${taskEvent.tasksTotal})`
); );
batchedAddAutoModeActivity({ addAutoModeActivity({
featureId: event.featureId, featureId: event.featureId,
type: 'progress', type: 'progress',
message: `${taskEvent.taskId} done (${taskEvent.tasksCompleted}/${taskEvent.tasksTotal})`, message: `${taskEvent.taskId} done (${taskEvent.tasksCompleted}/${taskEvent.tasksTotal})`,
@@ -787,7 +714,7 @@ export function useAutoMode(worktree?: WorktreeInfo) {
logger.debug( logger.debug(
`[AutoMode] Phase ${phaseEvent.phaseNumber} completed for ${event.featureId}` `[AutoMode] Phase ${phaseEvent.phaseNumber} completed for ${event.featureId}`
); );
batchedAddAutoModeActivity({ addAutoModeActivity({
featureId: event.featureId, featureId: event.featureId,
type: 'action', type: 'action',
message: `Phase ${phaseEvent.phaseNumber} completed`, message: `Phase ${phaseEvent.phaseNumber} completed`,
@@ -815,7 +742,7 @@ export function useAutoMode(worktree?: WorktreeInfo) {
logger.debug( logger.debug(
`[AutoMode] Summary saved for ${event.featureId}: ${summaryEvent.summary.substring(0, 100)}...` `[AutoMode] Summary saved for ${event.featureId}: ${summaryEvent.summary.substring(0, 100)}...`
); );
batchedAddAutoModeActivity({ addAutoModeActivity({
featureId: event.featureId, featureId: event.featureId,
type: 'progress', type: 'progress',
message: `Summary: ${summaryEvent.summary.substring(0, 100)}...`, message: `Summary: ${summaryEvent.summary.substring(0, 100)}...`,
@@ -831,7 +758,7 @@ export function useAutoMode(worktree?: WorktreeInfo) {
branchName, branchName,
addRunningTask, addRunningTask,
removeRunningTask, removeRunningTask,
batchedAddAutoModeActivity, addAutoModeActivity,
getProjectIdFromPath, getProjectIdFromPath,
setPendingPlanApproval, setPendingPlanApproval,
setAutoModeRunning, setAutoModeRunning,
@@ -1050,7 +977,7 @@ export function useAutoMode(worktree?: WorktreeInfo) {
removeRunningTask(currentProject.id, branchName, featureId); removeRunningTask(currentProject.id, branchName, featureId);
logger.info('Feature stopped successfully:', featureId); logger.info('Feature stopped successfully:', featureId);
batchedAddAutoModeActivity({ addAutoModeActivity({
featureId, featureId,
type: 'complete', type: 'complete',
message: 'Feature stopped by user', message: 'Feature stopped by user',
@@ -1066,7 +993,7 @@ export function useAutoMode(worktree?: WorktreeInfo) {
throw error; throw error;
} }
}, },
[currentProject, branchName, removeRunningTask, batchedAddAutoModeActivity] [currentProject, branchName, removeRunningTask, addAutoModeActivity]
); );
return { return {

View File

@@ -13,7 +13,6 @@ import type { AutoModeEvent, SpecRegenerationEvent, StreamEvent } from '@/types/
import type { IssueValidationEvent } from '@automaker/types'; import type { IssueValidationEvent } from '@automaker/types';
import { debounce, type DebouncedFunction } from '@automaker/utils/debounce'; import { debounce, type DebouncedFunction } from '@automaker/utils/debounce';
import { useEventRecencyStore } from './use-event-recency'; import { useEventRecencyStore } from './use-event-recency';
import { isAnyFeatureTransitioning } from '@/lib/feature-transition-state';
/** /**
* Debounce configuration for auto_mode_progress invalidations * Debounce configuration for auto_mode_progress invalidations
@@ -32,10 +31,8 @@ const FEATURE_LIST_INVALIDATION_EVENTS: AutoModeEvent['type'][] = [
'auto_mode_feature_start', 'auto_mode_feature_start',
'auto_mode_feature_complete', 'auto_mode_feature_complete',
'auto_mode_error', 'auto_mode_error',
// NOTE: auto_mode_started and auto_mode_stopped are intentionally excluded. 'auto_mode_started',
// These events signal auto-loop state changes, NOT feature data changes. 'auto_mode_stopped',
// Including them caused unnecessary refetches that raced with optimistic
// updates during start/stop cycles, triggering React error #185 on mobile.
'plan_approval_required', 'plan_approval_required',
'plan_approved', 'plan_approved',
'plan_rejected', 'plan_rejected',
@@ -179,12 +176,8 @@ export function useAutoModeQueryInvalidation(projectPath: string | undefined) {
// This allows polling to be disabled when WebSocket events are flowing // This allows polling to be disabled when WebSocket events are flowing
recordGlobalEvent(); recordGlobalEvent();
// Invalidate feature list for lifecycle events. // Invalidate feature list for lifecycle events
// Skip invalidation when a feature is mid-transition (e.g., being cancelled) if (FEATURE_LIST_INVALIDATION_EVENTS.includes(event.type)) {
// because persistFeatureUpdate already handles the optimistic cache update.
// Without this guard, auto_mode_error / auto_mode_stopped WS events race
// with the optimistic update and cause re-render cascades on mobile (React #185).
if (FEATURE_LIST_INVALIDATION_EVENTS.includes(event.type) && !isAnyFeatureTransitioning()) {
queryClient.invalidateQueries({ queryClient.invalidateQueries({
queryKey: queryKeys.features.all(currentProjectPath), queryKey: queryKeys.features.all(currentProjectPath),
}); });

View File

@@ -1,19 +0,0 @@
/**
* Lightweight module-level state tracking which features are mid-transition
* (e.g., being cancelled). Used by useAutoModeQueryInvalidation to skip
* redundant cache invalidations while persistFeatureUpdate is in flight.
*/
const transitioningFeatures = new Set<string>();
export function markFeatureTransitioning(featureId: string): void {
transitioningFeatures.add(featureId);
}
export function unmarkFeatureTransitioning(featureId: string): void {
transitioningFeatures.delete(featureId);
}
export function isAnyFeatureTransitioning(): boolean {
return transitioningFeatures.size > 0;
}

View File

@@ -2763,21 +2763,6 @@ export class HttpApiClient implements ElectronAPI {
headers?: Record<string, string>; headers?: Record<string, string>;
enabled?: boolean; enabled?: boolean;
}>; }>;
eventHooks?: Array<{
id: string;
trigger: string;
enabled: boolean;
action: Record<string, unknown>;
name?: string;
}>;
ntfyEndpoints?: Array<{
id: string;
name: string;
serverUrl: string;
topic: string;
authType: string;
enabled: boolean;
}>;
}; };
error?: string; error?: string;
}> => this.get('/api/settings/global'), }> => this.get('/api/settings/global'),

View File

@@ -600,7 +600,10 @@ function RootLayoutContent() {
// so updating them won't cause a visible re-render flash. // so updating them won't cause a visible re-render flash.
const serverHooks = (finalSettings as GlobalSettings).eventHooks ?? []; const serverHooks = (finalSettings as GlobalSettings).eventHooks ?? [];
const currentHooks = useAppStore.getState().eventHooks; const currentHooks = useAppStore.getState().eventHooks;
if (JSON.stringify(serverHooks) !== JSON.stringify(currentHooks)) { if (
JSON.stringify(serverHooks) !== JSON.stringify(currentHooks) &&
serverHooks.length > 0
) {
logger.info( logger.info(
`[FAST_HYDRATE] Reconciling eventHooks from server (server=${serverHooks.length}, store=${currentHooks.length})` `[FAST_HYDRATE] Reconciling eventHooks from server (server=${serverHooks.length}, store=${currentHooks.length})`
); );

View File

@@ -1044,9 +1044,6 @@ export const useAppStore = create<AppState & AppActions>()((set, get) => ({
set((state) => { set((state) => {
const current = state.autoModeByWorktree[key]; const current = state.autoModeByWorktree[key];
if (!current) return state; if (!current) return state;
// Idempotent: skip if task is not in the list to avoid creating new
// object references that trigger unnecessary re-renders.
if (!current.runningTasks.includes(taskId)) return state;
return { return {
autoModeByWorktree: { autoModeByWorktree: {
...state.autoModeByWorktree, ...state.autoModeByWorktree,
@@ -1100,20 +1097,13 @@ export const useAppStore = create<AppState & AppActions>()((set, get) => ({
addRecentlyCompletedFeature: (featureId: string) => { addRecentlyCompletedFeature: (featureId: string) => {
set((state) => { set((state) => {
// Idempotent: skip if already tracked to avoid creating a new Set reference
// that triggers unnecessary re-renders in useBoardColumnFeatures.
if (state.recentlyCompletedFeatures.has(featureId)) return state;
const newSet = new Set(state.recentlyCompletedFeatures); const newSet = new Set(state.recentlyCompletedFeatures);
newSet.add(featureId); newSet.add(featureId);
return { recentlyCompletedFeatures: newSet }; return { recentlyCompletedFeatures: newSet };
}); });
}, },
clearRecentlyCompletedFeatures: () => { clearRecentlyCompletedFeatures: () => set({ recentlyCompletedFeatures: new Set() }),
// Idempotent: skip if already empty to avoid creating a new Set reference.
if (get().recentlyCompletedFeatures.size === 0) return;
set({ recentlyCompletedFeatures: new Set() });
},
setMaxConcurrency: (max) => set({ maxConcurrency: max }), setMaxConcurrency: (max) => set({ maxConcurrency: max }),
@@ -1506,11 +1496,7 @@ export const useAppStore = create<AppState & AppActions>()((set, get) => ({
set({ eventHooks: hooks }); set({ eventHooks: hooks });
try { try {
const httpApi = getHttpApiClient(); const httpApi = getHttpApiClient();
await httpApi.settings.updateGlobal({ await httpApi.settings.updateGlobal({ eventHooks: hooks });
eventHooks: hooks,
// Signal the server that an empty array is intentional (not a wipe from stale state)
...(hooks.length === 0 ? { __allowEmptyEventHooks: true } : {}),
});
} catch (error) { } catch (error) {
logger.error('Failed to sync event hooks:', error); logger.error('Failed to sync event hooks:', error);
} }
@@ -1521,11 +1507,7 @@ export const useAppStore = create<AppState & AppActions>()((set, get) => ({
set({ ntfyEndpoints: endpoints }); set({ ntfyEndpoints: endpoints });
try { try {
const httpApi = getHttpApiClient(); const httpApi = getHttpApiClient();
await httpApi.settings.updateGlobal({ await httpApi.settings.updateGlobal({ ntfyEndpoints: endpoints });
ntfyEndpoints: endpoints,
// Signal the server that an empty array is intentional (not a wipe from stale state)
...(endpoints.length === 0 ? { __allowEmptyNtfyEndpoints: true } : {}),
});
} catch (error) { } catch (error) {
logger.error('Failed to sync ntfy endpoints:', error); logger.error('Failed to sync ntfy endpoints:', error);
} }