Fix: Dev server detection bug fixes. Settings sync bug fixes. Cli provider fixes. Terminal background/foreground colors (#791)

* Changes from fix/dev-server-state-bug

* feat: Add configurable max turns setting with user overrides. Address pr comments

* fix: Update default behaviors and improve state management across server and UI

* feat: Extract branch sync logic to separate service. Fix settings sync bug. Address pr comments

* refactor: Extract magic numbers to named constants and improve branch tracking logic

- Add DEFAULT_MAX_TURNS (1000) and MAX_ALLOWED_TURNS (2000) constants to settings-helpers
- Replace hardcoded 1000 values with DEFAULT_MAX_TURNS constant throughout codebase
- Improve max turns validation with explicit Number.isFinite check
- Update getTrackingBranch to split on first slash instead of last for better remote parsing
- Change isBranchCheckedOut return type from boolean to string|null to return worktree path
- Add comments explaining skipFetch parameter in worktree creation
- Fix cleanup order in AgentExecutor finally block to run before logging
```

* feat: Add comment refresh and improve model sync in PR dialog
This commit is contained in:
gsxdsm
2026-02-21 08:57:04 -08:00
committed by GitHub
parent c81ea768a7
commit 3ddf26f666
41 changed files with 2705 additions and 274 deletions

View File

@@ -459,13 +459,21 @@ export function BoardView() {
prevWorktreePathRef.current = currentWorktreePath;
}, [currentWorktreePath, currentProject?.path, queryClient]);
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

View File

@@ -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...'}
</>
) : (
<>

View File

@@ -7,6 +7,11 @@ 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;
}
@@ -30,6 +35,26 @@ function buildDevServerBrowserUrl(serverUrl: string): string | 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());
@@ -37,6 +62,120 @@ export function useDevServers({ projectPath }: UseDevServersOptions) {
// 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();
@@ -56,19 +195,132 @@ export function useDevServers({ projectPath }: UseDevServersOptions) {
// 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]);
// 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();
@@ -78,10 +330,24 @@ 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);
@@ -99,25 +365,15 @@ export function useDevServers({ projectPath }: UseDevServersOptions) {
// Only show toast on the transition from undetected → detected (not on re-renders/polls)
if (!toastShownForRef.current.has(key)) {
toastShownForRef.current.add(key);
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,
});
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);
@@ -143,10 +399,22 @@ export function useDevServers({ projectPath }: UseDevServersOptions) {
});
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(
@@ -186,6 +454,8 @@ export function useDevServers({ projectPath }: UseDevServersOptions) {
});
return next;
});
// Start port detection timeout
startPortDetectionTimer(key);
toast.success('Dev server started, detecting port...');
} else {
toast.error(result.error || 'Failed to start dev server');
@@ -197,7 +467,7 @@ export function useDevServers({ projectPath }: UseDevServersOptions) {
setIsStartingDevServer(false);
}
},
[isStartingDevServer, projectPath]
[isStartingDevServer, projectPath, startPortDetectionTimer]
);
const handleStopDevServer = useCallback(
@@ -214,6 +484,8 @@ export function useDevServers({ projectPath }: UseDevServersOptions) {
if (result.success) {
const key = normalizePath(targetPath);
// Clear port detection timeout
clearPortDetectionTimer(key);
setRunningDevServers((prev) => {
const next = new Map(prev);
next.delete(key);
@@ -230,7 +502,7 @@ export function useDevServers({ projectPath }: UseDevServersOptions) {
toast.error('Failed to stop dev server');
}
},
[projectPath]
[projectPath, clearPortDetectionTimer]
);
const handleOpenDevServerUrl = useCallback(

View File

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

View File

@@ -92,9 +92,9 @@ export function GitHubPRsView() {
// Start the feature immediately after creation
const api = getElectronAPI();
if (api.features?.run) {
if (api.autoMode?.runFeature) {
try {
await api.features.run(currentProject.path, featureId);
await api.autoMode.runFeature(currentProject.path, featureId);
toast.success('Feature created and started', {
description: `Addressing review comments on PR #${pr.number}`,
});

View File

@@ -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':

View File

@@ -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

View File

@@ -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">

View File

@@ -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';
@@ -276,6 +279,8 @@ export function TerminalView({
setTerminalLineHeight,
setTerminalScrollbackLines,
setTerminalScreenReaderMode,
setTerminalBackgroundColor,
setTerminalForegroundColor,
updateTerminalPanelSizes,
currentWorktreeByProject,
worktreesByProject,
@@ -1997,6 +2002,119 @@ export function TerminalView({
/>
</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">

View File

@@ -202,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);
@@ -679,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;
@@ -687,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({
@@ -1484,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(() => {
@@ -1925,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}
@@ -2395,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}
@@ -2456,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}`,