fix: resolve source control and chat UX bugs

- make staging real in the git panel: new /stage and /unstage endpoints,
  /status now reports the actual index via porcelain -z (handles renames,
  conflicts, and paths with spaces), and Stage/Unstage All run real git
  commands instead of toggling client-side state
- add branch search to the header dropdown and Branches tab
- persist the chosen permission mode per provider so a brand-new chat
  keeps it once the session id arrives, instead of reverting to default
- replace cmdk's fuzzy model search with strict token matching so
  "chatgpt" no longer surfaces unrelated models
- unit tests for the git status parser
This commit is contained in:
Haileyesus
2026-07-06 15:33:57 +03:00
parent 5dedf873e6
commit 09a21b3754
10 changed files with 437 additions and 78 deletions

View File

@@ -293,6 +293,76 @@ async function resolveRepositoryFilePath(projectPath, filePath) {
}
// Get git status for a project
/**
* Parses `git status --porcelain=v1 -z` output into the response shape the
* git panel consumes. NUL-separated entries carry no path quoting, so names
* with spaces/unicode survive intact (the plain porcelain output quotes and
* escapes them, which broke the old line-based parser).
*
* `staged` lists paths with index-side changes. The UI renders its "Staged"
* section from this list so it always mirrors the real git index (including
* files staged outside the app, e.g. via VSCode or the terminal).
*
* Exported for tests.
*/
export function parseGitStatusOutput(statusOutput) {
const modified = [];
const added = [];
const deleted = [];
const untracked = [];
const staged = [];
const statusEntries = statusOutput.split('\0');
for (let entryIndex = 0; entryIndex < statusEntries.length; entryIndex++) {
const entry = statusEntries[entryIndex];
if (!entry || entry.length < 4) continue;
// Porcelain v1: X = index (staged) status, Y = worktree (unstaged) status.
const indexStatus = entry[0];
const worktreeStatus = entry[1];
const file = entry.slice(3);
// Renames/copies carry the original path as the following NUL entry;
// the UI tracks the post-rename path only.
if (indexStatus === 'R' || indexStatus === 'C') {
entryIndex += 1;
}
if (indexStatus === '?') {
untracked.push(file);
continue;
}
if (indexStatus === '!') {
continue; // ignored files are never reported
}
const isConflict =
indexStatus === 'U' || worktreeStatus === 'U' ||
(indexStatus === 'A' && worktreeStatus === 'A') ||
(indexStatus === 'D' && worktreeStatus === 'D');
if (isConflict) {
// Merge conflicts must be resolved in the worktree first; surface them
// as modified and never as staged.
modified.push(file);
continue;
}
if (indexStatus !== ' ') {
staged.push(file);
}
if (indexStatus === 'D' || worktreeStatus === 'D') {
deleted.push(file);
} else if (indexStatus === 'A' || worktreeStatus === 'A') {
added.push(file);
} else {
modified.push(file);
}
}
return { modified, added, deleted, untracked, staged };
}
router.get('/status', async (req, res) => {
const { project } = req.query;
@@ -309,30 +379,8 @@ router.get('/status', async (req, res) => {
const branch = await getCurrentBranchName(projectPath);
const hasCommits = await repositoryHasCommits(projectPath);
// Get git status
const { stdout: statusOutput } = await spawnAsync('git', ['status', '--porcelain'], { cwd: projectPath });
const modified = [];
const added = [];
const deleted = [];
const untracked = [];
statusOutput.split('\n').forEach(line => {
if (!line.trim()) return;
const status = line.substring(0, 2);
const file = line.substring(3);
if (status === 'M ' || status === ' M' || status === 'MM') {
modified.push(file);
} else if (status === 'A ' || status === 'AM') {
added.push(file);
} else if (status === 'D ' || status === ' D') {
deleted.push(file);
} else if (status === '??') {
untracked.push(file);
}
});
const { stdout: statusOutput } = await spawnAsync('git', ['status', '--porcelain=v1', '-z'], { cwd: projectPath });
const { modified, added, deleted, untracked, staged } = parseGitStatusOutput(statusOutput);
res.json({
branch,
@@ -340,7 +388,8 @@ router.get('/status', async (req, res) => {
modified,
added,
deleted,
untracked
untracked,
staged
});
} catch (error) {
console.error('Git status error:', error);
@@ -593,6 +642,64 @@ router.post('/commit', async (req, res) => {
}
});
// Stage files (git add). Mirrors what the UI shows as the "Staged" section,
// so the app's staging state and the real git index never drift apart.
router.post('/stage', async (req, res) => {
const { project, files } = req.body;
if (!project || !Array.isArray(files) || files.length === 0) {
return res.status(400).json({ error: 'Project id and files are required' });
}
try {
const projectPath = await getActualProjectPath(project);
await validateGitRepository(projectPath);
const repositoryRootPath = await getRepositoryRootPath(projectPath);
for (const file of files) {
const { repositoryRelativeFilePath } = await resolveRepositoryFilePath(projectPath, file);
await spawnAsync('git', ['add', '--', repositoryRelativeFilePath], { cwd: repositoryRootPath });
}
res.json({ success: true });
} catch (error) {
console.error('Git stage error:', error);
res.status(500).json({ error: error.message });
}
});
// Unstage files (remove from the index, keep the worktree changes)
router.post('/unstage', async (req, res) => {
const { project, files } = req.body;
if (!project || !Array.isArray(files) || files.length === 0) {
return res.status(400).json({ error: 'Project id and files are required' });
}
try {
const projectPath = await getActualProjectPath(project);
await validateGitRepository(projectPath);
const repositoryRootPath = await getRepositoryRootPath(projectPath);
const hasCommits = await repositoryHasCommits(projectPath);
for (const file of files) {
const { repositoryRelativeFilePath } = await resolveRepositoryFilePath(projectPath, file);
if (hasCommits) {
await spawnAsync('git', ['reset', 'HEAD', '--', repositoryRelativeFilePath], { cwd: repositoryRootPath });
} else {
// No HEAD to reset against before the first commit; dropping the
// index entry is the only way to unstage while keeping the file.
await spawnAsync('git', ['rm', '--cached', '-r', '--force', '--', repositoryRelativeFilePath], { cwd: repositoryRootPath });
}
}
res.json({ success: true });
} catch (error) {
console.error('Git unstage error:', error);
res.status(500).json({ error: error.message });
}
});
// Revert latest local commit (keeps changes staged)
router.post('/revert-local-commit', async (req, res) => {
const { project } = req.body;

68
server/routes/git.test.js Normal file
View File

@@ -0,0 +1,68 @@
import assert from 'node:assert/strict';
import test from 'node:test';
import { parseGitStatusOutput } from './git.js';
// Builds `git status --porcelain=v1 -z` output: NUL-separated entries with a
// trailing NUL, exactly as git emits it.
const porcelain = (...entries) => entries.join('\0') + '\0';
test('parseGitStatusOutput buckets files and reports index-side staging', () => {
const output = porcelain(
'M staged-modified.ts',
' M unstaged-modified.ts',
'MM staged-and-unstaged.ts',
'A staged-new.ts',
'D staged-deleted.ts',
' D unstaged-deleted.ts',
'?? untracked.ts',
);
const result = parseGitStatusOutput(output);
assert.deepEqual(result.modified, ['staged-modified.ts', 'unstaged-modified.ts', 'staged-and-unstaged.ts']);
assert.deepEqual(result.added, ['staged-new.ts']);
assert.deepEqual(result.deleted, ['staged-deleted.ts', 'unstaged-deleted.ts']);
assert.deepEqual(result.untracked, ['untracked.ts']);
// Only index-side (X) changes count as staged.
assert.deepEqual(result.staged, [
'staged-modified.ts',
'staged-and-unstaged.ts',
'staged-new.ts',
'staged-deleted.ts',
]);
});
test('parseGitStatusOutput keeps paths with spaces intact (-z output has no quoting)', () => {
const result = parseGitStatusOutput(porcelain('M src/my folder/some file.ts'));
assert.deepEqual(result.modified, ['src/my folder/some file.ts']);
assert.deepEqual(result.staged, ['src/my folder/some file.ts']);
});
test('parseGitStatusOutput tracks the post-rename path and skips the original', () => {
const output = porcelain('R renamed-to.ts', 'renamed-from.ts', ' M other.ts');
const result = parseGitStatusOutput(output);
assert.deepEqual(result.modified, ['renamed-to.ts', 'other.ts']);
assert.deepEqual(result.staged, ['renamed-to.ts']);
// The pre-rename path is metadata, not a change entry.
assert.equal(JSON.stringify(result).includes('renamed-from.ts'), false);
});
test('parseGitStatusOutput never reports merge conflicts as staged', () => {
const output = porcelain('UU conflicted.ts', 'AA both-added.ts', 'DD both-deleted.ts');
const result = parseGitStatusOutput(output);
assert.deepEqual(result.modified, ['conflicted.ts', 'both-added.ts', 'both-deleted.ts']);
assert.deepEqual(result.staged, []);
});
test('parseGitStatusOutput handles empty output', () => {
assert.deepEqual(parseGitStatusOutput(''), {
modified: [],
added: [],
deleted: [],
untracked: [],
staged: [],
});
});

View File

@@ -451,17 +451,19 @@ export function useChatProviderState({ selectedSession, selectedProject: _select
}, [providerEfforts, providerModels, reconcileStoredEffort]);
useEffect(() => {
if (!selectedSession?.id) {
return;
}
const savedMode = localStorage.getItem(`permissionMode-${selectedSession.id}`) as PermissionMode | null;
const validModes = getPermissionModesForProvider(provider);
setPermissionMode(
savedMode && validModes.includes(savedMode)
? savedMode
: getDefaultPermissionModeForProvider(provider),
const sessionSavedMode = selectedSession?.id
? (localStorage.getItem(`permissionMode-${selectedSession.id}`) as PermissionMode | null)
: null;
// Fall back to the last mode picked for this provider: a brand-new chat
// only receives its session id after the first send, so without this the
// mode chosen beforehand would snap back to the default as soon as the
// session id appears.
const providerSavedMode = localStorage.getItem(`permissionMode-last-${provider}`) as PermissionMode | null;
const savedMode = [sessionSavedMode, providerSavedMode].find(
(mode): mode is PermissionMode => Boolean(mode && validModes.includes(mode)),
);
setPermissionMode(savedMode ?? getDefaultPermissionModeForProvider(provider));
}, [selectedSession?.id, provider, getDefaultPermissionModeForProvider, getPermissionModesForProvider]);
useEffect(() => {
@@ -511,6 +513,10 @@ export function useChatProviderState({ selectedSession, selectedProject: _select
const nextMode = modes[nextIndex];
setPermissionMode(nextMode);
// Persist per provider as well as per session: a brand-new chat has no
// session id yet, and the per-provider key keeps the choice sticky when
// the real id arrives (and for future sessions of this provider).
localStorage.setItem(`permissionMode-last-${provider}`, nextMode);
if (selectedSession?.id) {
localStorage.setItem(`permissionMode-${selectedSession.id}`, nextMode);
}

View File

@@ -34,6 +34,17 @@ const PROVIDER_META: { id: LLMProvider; name: string }[] = [
const MOD_KEY =
typeof navigator !== "undefined" && /Mac|iPhone|iPad/.test(navigator.platform) ? "⌘" : "Ctrl";
// cmdk's default filter is fuzzy (loose character-subsequence scoring), which
// surfaces unrelated models — e.g. searching "chatgpt" also matched "Fable".
// Require every whitespace-separated search token to appear as a literal
// substring instead, so "claude 4.5" still matches "Anthropic Claude Haiku 4.5"
// but "chatgpt" only matches models that actually contain it.
function modelSearchFilter(value: string, search: string): number {
const haystack = value.toLowerCase();
const tokens = search.toLowerCase().split(/\s+/).filter(Boolean);
return tokens.every((token) => haystack.includes(token)) ? 1 : 0;
}
type ProviderSelectionEmptyStateProps = {
selectedSession: ProjectSession | null;
currentSessionId: string | null;
@@ -234,7 +245,7 @@ export default function ProviderSelectionEmptyState({
<div className="border-b border-border/60 bg-muted/20 px-4 py-3">
<p className="text-sm font-semibold text-foreground">Choose a model</p>
</div>
<Command>
<Command filter={modelSearchFilter}>
<CommandInput
placeholder={t("providerSelection.searchModels", {
defaultValue: "Search models...",

View File

@@ -495,6 +495,71 @@ export function useGitPanelController({
[fetchGitStatus, selectedProject],
);
const stageFiles = useCallback(
async (files: string[]) => {
if (!selectedProject || files.length === 0) {
return false;
}
try {
const response = await fetchWithAuth('/api/git/stage', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
project: selectedProject.projectId,
files,
}),
});
const data = await readJson<GitOperationResponse>(response);
if (!data.success) {
setOperationError(data.error ?? 'Stage failed');
return false;
}
// Refresh so the Staged section re-syncs from the real index.
await fetchGitStatus();
return true;
} catch (error) {
setOperationError(error instanceof Error ? error.message : 'Stage failed');
return false;
}
},
[fetchGitStatus, selectedProject],
);
const unstageFiles = useCallback(
async (files: string[]) => {
if (!selectedProject || files.length === 0) {
return false;
}
try {
const response = await fetchWithAuth('/api/git/unstage', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
project: selectedProject.projectId,
files,
}),
});
const data = await readJson<GitOperationResponse>(response);
if (!data.success) {
setOperationError(data.error ?? 'Unstage failed');
return false;
}
await fetchGitStatus();
return true;
} catch (error) {
setOperationError(error instanceof Error ? error.message : 'Unstage failed');
return false;
}
},
[fetchGitStatus, selectedProject],
);
const fetchRecentCommits = useCallback(async () => {
if (!selectedProject) {
return;
@@ -744,6 +809,8 @@ export function useGitPanelController({
handlePublish,
discardChanges,
deleteUntrackedFile,
stageFiles,
unstageFiles,
fetchCommitDiff,
generateCommitMessage,
commitChanges,

View File

@@ -25,6 +25,8 @@ export type GitStatusResponse = {
added?: string[];
deleted?: string[];
untracked?: string[];
/** Paths with index-side changes — mirrors the real git index. */
staged?: string[];
error?: string;
details?: string;
};
@@ -99,6 +101,8 @@ export type GitPanelController = {
handlePublish: () => Promise<void>;
discardChanges: (filePath: string) => Promise<void>;
deleteUntrackedFile: (filePath: string) => Promise<void>;
stageFiles: (files: string[]) => Promise<boolean>;
unstageFiles: (files: string[]) => Promise<boolean>;
fetchCommitDiff: (commitHash: string) => Promise<void>;
generateCommitMessage: (files: string[]) => Promise<string | null>;
commitChanges: (message: string, files: string[]) => Promise<boolean>;

View File

@@ -46,6 +46,8 @@ export default function GitPanel({ selectedProject, isMobile = false, onFileOpen
handlePublish,
discardChanges,
deleteUntrackedFile,
stageFiles,
unstageFiles,
fetchCommitDiff,
generateCommitMessage,
commitChanges,
@@ -138,6 +140,8 @@ export default function GitPanel({ selectedProject, isMobile = false, onFileOpen
onOpenFile={openFile}
onDiscardFile={discardChanges}
onDeleteFile={deleteUntrackedFile}
onStageFiles={stageFiles}
onUnstageFiles={unstageFiles}
onCommitChanges={commitChanges}
onGenerateCommitMessage={generateCommitMessage}
onRequestConfirmation={setConfirmAction}

View File

@@ -1,5 +1,5 @@
import { AlertCircle, Check, ChevronDown, Download, GitBranch, Plus, RefreshCw, RotateCcw, Upload, X } from 'lucide-react';
import { useEffect, useRef, useState } from 'react';
import { AlertCircle, Check, ChevronDown, Download, GitBranch, Plus, RefreshCw, RotateCcw, Search, Upload, X } from 'lucide-react';
import { useEffect, useMemo, useRef, useState } from 'react';
import type { ConfirmationRequest, GitRemoteStatus } from '../types/types';
import NewBranchModal from './modals/NewBranchModal';
@@ -54,7 +54,26 @@ export default function GitPanelHeader({
}: GitPanelHeaderProps) {
const [showBranchDropdown, setShowBranchDropdown] = useState(false);
const [showNewBranchModal, setShowNewBranchModal] = useState(false);
const [branchSearchQuery, setBranchSearchQuery] = useState('');
const dropdownRef = useRef<HTMLDivElement | null>(null);
const branchSearchInputRef = useRef<HTMLInputElement | null>(null);
// Focus the search box on open; drop any stale query on close.
useEffect(() => {
if (showBranchDropdown) {
branchSearchInputRef.current?.focus();
} else {
setBranchSearchQuery('');
}
}, [showBranchDropdown]);
const filteredBranches = useMemo(() => {
const query = branchSearchQuery.trim().toLowerCase();
if (!query) {
return branches;
}
return branches.filter((branch) => branch.toLowerCase().includes(query));
}, [branches, branchSearchQuery]);
useEffect(() => {
const handleClickOutside = (event: MouseEvent) => {
@@ -149,21 +168,45 @@ export default function GitPanelHeader({
{showBranchDropdown && (
<div className="absolute left-0 top-full z-50 mt-1 w-64 overflow-hidden rounded-xl border border-border bg-card shadow-lg">
<div className="max-h-64 overflow-y-auto py-1">
{branches.map((branch) => (
<div className="flex items-center gap-2 border-b border-border px-3 py-2">
<Search className="h-3.5 w-3.5 shrink-0 text-muted-foreground" />
<input
ref={branchSearchInputRef}
type="text"
value={branchSearchQuery}
onChange={(event) => setBranchSearchQuery(event.target.value)}
placeholder="Search branches..."
className="w-full bg-transparent text-sm text-foreground placeholder:text-muted-foreground focus:outline-none"
/>
{branchSearchQuery && (
<button
key={branch}
onClick={() => void handleSwitchBranch(branch)}
className={`w-full px-4 py-2 text-left text-sm transition-colors hover:bg-accent ${
branch === currentBranch ? 'bg-accent/50 text-foreground' : 'text-muted-foreground'
}`}
onClick={() => setBranchSearchQuery('')}
className="shrink-0 text-muted-foreground transition-colors hover:text-foreground"
title="Clear search"
>
<span className="flex items-center space-x-2">
{branch === currentBranch && <Check className="h-3 w-3 text-primary" />}
<span className={branch === currentBranch ? 'font-medium' : ''}>{branch}</span>
</span>
<X className="h-3.5 w-3.5" />
</button>
))}
)}
</div>
<div className="max-h-64 overflow-y-auto py-1">
{filteredBranches.length === 0 ? (
<div className="px-4 py-3 text-center text-sm text-muted-foreground">No matching branches</div>
) : (
filteredBranches.map((branch) => (
<button
key={branch}
onClick={() => void handleSwitchBranch(branch)}
className={`w-full px-4 py-2 text-left text-sm transition-colors hover:bg-accent ${
branch === currentBranch ? 'bg-accent/50 text-foreground' : 'text-muted-foreground'
}`}
>
<span className="flex items-center space-x-2">
{branch === currentBranch && <Check className="h-3 w-3 text-primary" />}
<span className={branch === currentBranch ? 'font-medium' : ''}>{branch}</span>
</span>
</button>
))
)}
</div>
<div className="border-t border-border py-1">
<button

View File

@@ -1,5 +1,5 @@
import { Check, GitBranch, Globe, Plus, RefreshCw, Trash2 } from 'lucide-react';
import { useState } from 'react';
import { Check, GitBranch, Globe, Plus, RefreshCw, Search, Trash2, X } from 'lucide-react';
import { useMemo, useState } from 'react';
import type { ConfirmationRequest, GitRemoteStatus } from '../../types/types';
import NewBranchModal from '../modals/NewBranchModal';
@@ -138,10 +138,21 @@ export default function BranchesView({
onRequestConfirmation,
}: BranchesViewProps) {
const [showNewBranchModal, setShowNewBranchModal] = useState(false);
const [branchSearchQuery, setBranchSearchQuery] = useState('');
const aheadCount = remoteStatus?.ahead ?? 0;
const behindCount = remoteStatus?.behind ?? 0;
const normalizedQuery = branchSearchQuery.trim().toLowerCase();
const filteredLocalBranches = useMemo(
() => (normalizedQuery ? localBranches.filter((branch) => branch.toLowerCase().includes(normalizedQuery)) : localBranches),
[localBranches, normalizedQuery],
);
const filteredRemoteBranches = useMemo(
() => (normalizedQuery ? remoteBranches.filter((branch) => branch.toLowerCase().includes(normalizedQuery)) : remoteBranches),
[normalizedQuery, remoteBranches],
);
const requestSwitch = (branch: string) => {
onRequestConfirmation({
type: 'commit', // reuse neutral type for switch
@@ -182,12 +193,33 @@ export default function BranchesView({
</button>
</div>
{/* Branch search */}
<div className="flex items-center gap-2 border-b border-border/40 px-4 py-2">
<Search className="h-3.5 w-3.5 shrink-0 text-muted-foreground" />
<input
type="text"
value={branchSearchQuery}
onChange={(event) => setBranchSearchQuery(event.target.value)}
placeholder="Search branches..."
className="w-full bg-transparent text-sm text-foreground placeholder:text-muted-foreground focus:outline-none"
/>
{branchSearchQuery && (
<button
onClick={() => setBranchSearchQuery('')}
className="shrink-0 text-muted-foreground transition-colors hover:text-foreground"
title="Clear search"
>
<X className="h-3.5 w-3.5" />
</button>
)}
</div>
{/* Branch list */}
<div className="flex-1 overflow-y-auto">
{localBranches.length > 0 && (
{filteredLocalBranches.length > 0 && (
<>
<SectionHeader label="Local" count={localBranches.length} />
{localBranches.map((branch) => (
<SectionHeader label="Local" count={filteredLocalBranches.length} />
{filteredLocalBranches.map((branch) => (
<BranchRow
key={`local:${branch}`}
name={branch}
@@ -203,10 +235,10 @@ export default function BranchesView({
</>
)}
{remoteBranches.length > 0 && (
{filteredRemoteBranches.length > 0 && (
<>
<SectionHeader label="Remote" count={remoteBranches.length} />
{remoteBranches.map((branch) => (
<SectionHeader label="Remote" count={filteredRemoteBranches.length} />
{filteredRemoteBranches.map((branch) => (
<BranchRow
key={`remote:${branch}`}
name={branch}
@@ -222,10 +254,10 @@ export default function BranchesView({
</>
)}
{localBranches.length === 0 && remoteBranches.length === 0 && (
{filteredLocalBranches.length === 0 && filteredRemoteBranches.length === 0 && (
<div className="flex h-32 flex-col items-center justify-center gap-2 text-muted-foreground">
<GitBranch className="h-10 w-10 opacity-30" />
<p className="text-sm">No branches found</p>
<p className="text-sm">{normalizedQuery ? 'No branches match your search' : 'No branches found'}</p>
</div>
)}
</div>

View File

@@ -19,6 +19,8 @@ type ChangesViewProps = {
onOpenFile: (filePath: string) => Promise<void>;
onDiscardFile: (filePath: string) => Promise<void>;
onDeleteFile: (filePath: string) => Promise<void>;
onStageFiles: (files: string[]) => Promise<boolean>;
onUnstageFiles: (files: string[]) => Promise<boolean>;
onCommitChanges: (message: string, files: string[]) => Promise<boolean>;
onGenerateCommitMessage: (files: string[]) => Promise<string | null>;
onRequestConfirmation: (request: ConfirmationRequest) => void;
@@ -38,6 +40,8 @@ export default function ChangesView({
onOpenFile,
onDiscardFile,
onDeleteFile,
onStageFiles,
onUnstageFiles,
onCommitChanges,
onGenerateCommitMessage,
onRequestConfirmation,
@@ -55,12 +59,9 @@ export default function ChangesView({
return;
}
// Remove any selected files that no longer exist in the status
setSelectedFiles((prev) => {
const allFiles = new Set(getAllChangedFiles(gitStatus));
const next = new Set([...prev].filter((f) => allFiles.has(f)));
return next;
});
// The Staged section mirrors the real git index reported by /status, so
// files staged outside the app (VSCode, terminal) show up here too.
setSelectedFiles(new Set(gitStatus.staged ?? []));
}, [gitStatus]);
useEffect(() => {
@@ -85,17 +86,25 @@ export default function ChangesView({
});
}, []);
const toggleFileSelected = useCallback((filePath: string) => {
setSelectedFiles((previous) => {
const next = new Set(previous);
if (next.has(filePath)) {
next.delete(filePath);
} else {
next.add(filePath);
}
return next;
});
}, []);
// Staging is real: every toggle runs git add / git reset through the API.
// The set is flipped optimistically; the status refresh triggered by the
// API call re-syncs it from the actual index afterwards.
const toggleFileSelected = useCallback(
(filePath: string) => {
const isStaged = selectedFiles.has(filePath);
setSelectedFiles((previous) => {
const next = new Set(previous);
if (isStaged) {
next.delete(filePath);
} else {
next.add(filePath);
}
return next;
});
void (isStaged ? onUnstageFiles([filePath]) : onStageFiles([filePath]));
},
[onStageFiles, onUnstageFiles, selectedFiles],
);
const requestFileAction = useCallback(
(filePath: string, status: FileStatusCode) => {
@@ -197,7 +206,11 @@ export default function ChangesView({
</span>
{selectedFiles.size > 0 && (
<button
onClick={() => setSelectedFiles(new Set())}
onClick={() => {
const filesToUnstage = Array.from(selectedFiles);
setSelectedFiles(new Set());
void onUnstageFiles(filesToUnstage);
}}
className="text-xs text-primary transition-colors hover:text-primary/80"
>
Unstage All
@@ -230,7 +243,11 @@ export default function ChangesView({
</span>
{unstagedFiles.size > 0 && (
<button
onClick={() => setSelectedFiles(new Set(changedFiles))}
onClick={() => {
const filesToStage = Array.from(unstagedFiles);
setSelectedFiles(new Set(changedFiles));
void onStageFiles(filesToStage);
}}
className="text-xs text-primary transition-colors hover:text-primary/80"
>
Stage All