mirror of
https://github.com/siteboon/claudecodeui.git
synced 2026-07-07 14:12:40 +08:00
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:
@@ -293,6 +293,76 @@ async function resolveRepositoryFilePath(projectPath, filePath) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Get git status for a project
|
// 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) => {
|
router.get('/status', async (req, res) => {
|
||||||
const { project } = req.query;
|
const { project } = req.query;
|
||||||
|
|
||||||
@@ -309,30 +379,8 @@ router.get('/status', async (req, res) => {
|
|||||||
const branch = await getCurrentBranchName(projectPath);
|
const branch = await getCurrentBranchName(projectPath);
|
||||||
const hasCommits = await repositoryHasCommits(projectPath);
|
const hasCommits = await repositoryHasCommits(projectPath);
|
||||||
|
|
||||||
// Get git status
|
const { stdout: statusOutput } = await spawnAsync('git', ['status', '--porcelain=v1', '-z'], { cwd: projectPath });
|
||||||
const { stdout: statusOutput } = await spawnAsync('git', ['status', '--porcelain'], { cwd: projectPath });
|
const { modified, added, deleted, untracked, staged } = parseGitStatusOutput(statusOutput);
|
||||||
|
|
||||||
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);
|
|
||||||
}
|
|
||||||
});
|
|
||||||
|
|
||||||
res.json({
|
res.json({
|
||||||
branch,
|
branch,
|
||||||
@@ -340,7 +388,8 @@ router.get('/status', async (req, res) => {
|
|||||||
modified,
|
modified,
|
||||||
added,
|
added,
|
||||||
deleted,
|
deleted,
|
||||||
untracked
|
untracked,
|
||||||
|
staged
|
||||||
});
|
});
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
console.error('Git status error:', 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)
|
// Revert latest local commit (keeps changes staged)
|
||||||
router.post('/revert-local-commit', async (req, res) => {
|
router.post('/revert-local-commit', async (req, res) => {
|
||||||
const { project } = req.body;
|
const { project } = req.body;
|
||||||
|
|||||||
68
server/routes/git.test.js
Normal file
68
server/routes/git.test.js
Normal 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: [],
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -451,17 +451,19 @@ export function useChatProviderState({ selectedSession, selectedProject: _select
|
|||||||
}, [providerEfforts, providerModels, reconcileStoredEffort]);
|
}, [providerEfforts, providerModels, reconcileStoredEffort]);
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
if (!selectedSession?.id) {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
const savedMode = localStorage.getItem(`permissionMode-${selectedSession.id}`) as PermissionMode | null;
|
|
||||||
const validModes = getPermissionModesForProvider(provider);
|
const validModes = getPermissionModesForProvider(provider);
|
||||||
setPermissionMode(
|
const sessionSavedMode = selectedSession?.id
|
||||||
savedMode && validModes.includes(savedMode)
|
? (localStorage.getItem(`permissionMode-${selectedSession.id}`) as PermissionMode | null)
|
||||||
? savedMode
|
: null;
|
||||||
: getDefaultPermissionModeForProvider(provider),
|
// 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]);
|
}, [selectedSession?.id, provider, getDefaultPermissionModeForProvider, getPermissionModesForProvider]);
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
@@ -511,6 +513,10 @@ export function useChatProviderState({ selectedSession, selectedProject: _select
|
|||||||
const nextMode = modes[nextIndex];
|
const nextMode = modes[nextIndex];
|
||||||
setPermissionMode(nextMode);
|
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) {
|
if (selectedSession?.id) {
|
||||||
localStorage.setItem(`permissionMode-${selectedSession.id}`, nextMode);
|
localStorage.setItem(`permissionMode-${selectedSession.id}`, nextMode);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -34,6 +34,17 @@ const PROVIDER_META: { id: LLMProvider; name: string }[] = [
|
|||||||
const MOD_KEY =
|
const MOD_KEY =
|
||||||
typeof navigator !== "undefined" && /Mac|iPhone|iPad/.test(navigator.platform) ? "⌘" : "Ctrl";
|
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 = {
|
type ProviderSelectionEmptyStateProps = {
|
||||||
selectedSession: ProjectSession | null;
|
selectedSession: ProjectSession | null;
|
||||||
currentSessionId: string | 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">
|
<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>
|
<p className="text-sm font-semibold text-foreground">Choose a model</p>
|
||||||
</div>
|
</div>
|
||||||
<Command>
|
<Command filter={modelSearchFilter}>
|
||||||
<CommandInput
|
<CommandInput
|
||||||
placeholder={t("providerSelection.searchModels", {
|
placeholder={t("providerSelection.searchModels", {
|
||||||
defaultValue: "Search models...",
|
defaultValue: "Search models...",
|
||||||
|
|||||||
@@ -495,6 +495,71 @@ export function useGitPanelController({
|
|||||||
[fetchGitStatus, selectedProject],
|
[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 () => {
|
const fetchRecentCommits = useCallback(async () => {
|
||||||
if (!selectedProject) {
|
if (!selectedProject) {
|
||||||
return;
|
return;
|
||||||
@@ -744,6 +809,8 @@ export function useGitPanelController({
|
|||||||
handlePublish,
|
handlePublish,
|
||||||
discardChanges,
|
discardChanges,
|
||||||
deleteUntrackedFile,
|
deleteUntrackedFile,
|
||||||
|
stageFiles,
|
||||||
|
unstageFiles,
|
||||||
fetchCommitDiff,
|
fetchCommitDiff,
|
||||||
generateCommitMessage,
|
generateCommitMessage,
|
||||||
commitChanges,
|
commitChanges,
|
||||||
|
|||||||
@@ -25,6 +25,8 @@ export type GitStatusResponse = {
|
|||||||
added?: string[];
|
added?: string[];
|
||||||
deleted?: string[];
|
deleted?: string[];
|
||||||
untracked?: string[];
|
untracked?: string[];
|
||||||
|
/** Paths with index-side changes — mirrors the real git index. */
|
||||||
|
staged?: string[];
|
||||||
error?: string;
|
error?: string;
|
||||||
details?: string;
|
details?: string;
|
||||||
};
|
};
|
||||||
@@ -99,6 +101,8 @@ export type GitPanelController = {
|
|||||||
handlePublish: () => Promise<void>;
|
handlePublish: () => Promise<void>;
|
||||||
discardChanges: (filePath: string) => Promise<void>;
|
discardChanges: (filePath: string) => Promise<void>;
|
||||||
deleteUntrackedFile: (filePath: string) => Promise<void>;
|
deleteUntrackedFile: (filePath: string) => Promise<void>;
|
||||||
|
stageFiles: (files: string[]) => Promise<boolean>;
|
||||||
|
unstageFiles: (files: string[]) => Promise<boolean>;
|
||||||
fetchCommitDiff: (commitHash: string) => Promise<void>;
|
fetchCommitDiff: (commitHash: string) => Promise<void>;
|
||||||
generateCommitMessage: (files: string[]) => Promise<string | null>;
|
generateCommitMessage: (files: string[]) => Promise<string | null>;
|
||||||
commitChanges: (message: string, files: string[]) => Promise<boolean>;
|
commitChanges: (message: string, files: string[]) => Promise<boolean>;
|
||||||
|
|||||||
@@ -46,6 +46,8 @@ export default function GitPanel({ selectedProject, isMobile = false, onFileOpen
|
|||||||
handlePublish,
|
handlePublish,
|
||||||
discardChanges,
|
discardChanges,
|
||||||
deleteUntrackedFile,
|
deleteUntrackedFile,
|
||||||
|
stageFiles,
|
||||||
|
unstageFiles,
|
||||||
fetchCommitDiff,
|
fetchCommitDiff,
|
||||||
generateCommitMessage,
|
generateCommitMessage,
|
||||||
commitChanges,
|
commitChanges,
|
||||||
@@ -138,6 +140,8 @@ export default function GitPanel({ selectedProject, isMobile = false, onFileOpen
|
|||||||
onOpenFile={openFile}
|
onOpenFile={openFile}
|
||||||
onDiscardFile={discardChanges}
|
onDiscardFile={discardChanges}
|
||||||
onDeleteFile={deleteUntrackedFile}
|
onDeleteFile={deleteUntrackedFile}
|
||||||
|
onStageFiles={stageFiles}
|
||||||
|
onUnstageFiles={unstageFiles}
|
||||||
onCommitChanges={commitChanges}
|
onCommitChanges={commitChanges}
|
||||||
onGenerateCommitMessage={generateCommitMessage}
|
onGenerateCommitMessage={generateCommitMessage}
|
||||||
onRequestConfirmation={setConfirmAction}
|
onRequestConfirmation={setConfirmAction}
|
||||||
|
|||||||
@@ -1,5 +1,5 @@
|
|||||||
import { AlertCircle, Check, ChevronDown, Download, GitBranch, Plus, RefreshCw, RotateCcw, Upload, X } from 'lucide-react';
|
import { AlertCircle, Check, ChevronDown, Download, GitBranch, Plus, RefreshCw, RotateCcw, Search, Upload, X } from 'lucide-react';
|
||||||
import { useEffect, useRef, useState } from 'react';
|
import { useEffect, useMemo, useRef, useState } from 'react';
|
||||||
import type { ConfirmationRequest, GitRemoteStatus } from '../types/types';
|
import type { ConfirmationRequest, GitRemoteStatus } from '../types/types';
|
||||||
import NewBranchModal from './modals/NewBranchModal';
|
import NewBranchModal from './modals/NewBranchModal';
|
||||||
|
|
||||||
@@ -54,7 +54,26 @@ export default function GitPanelHeader({
|
|||||||
}: GitPanelHeaderProps) {
|
}: GitPanelHeaderProps) {
|
||||||
const [showBranchDropdown, setShowBranchDropdown] = useState(false);
|
const [showBranchDropdown, setShowBranchDropdown] = useState(false);
|
||||||
const [showNewBranchModal, setShowNewBranchModal] = useState(false);
|
const [showNewBranchModal, setShowNewBranchModal] = useState(false);
|
||||||
|
const [branchSearchQuery, setBranchSearchQuery] = useState('');
|
||||||
const dropdownRef = useRef<HTMLDivElement | null>(null);
|
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(() => {
|
useEffect(() => {
|
||||||
const handleClickOutside = (event: MouseEvent) => {
|
const handleClickOutside = (event: MouseEvent) => {
|
||||||
@@ -149,8 +168,31 @@ export default function GitPanelHeader({
|
|||||||
|
|
||||||
{showBranchDropdown && (
|
{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="absolute left-0 top-full z-50 mt-1 w-64 overflow-hidden rounded-xl border border-border bg-card shadow-lg">
|
||||||
|
<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
|
||||||
|
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>
|
||||||
<div className="max-h-64 overflow-y-auto py-1">
|
<div className="max-h-64 overflow-y-auto py-1">
|
||||||
{branches.map((branch) => (
|
{filteredBranches.length === 0 ? (
|
||||||
|
<div className="px-4 py-3 text-center text-sm text-muted-foreground">No matching branches</div>
|
||||||
|
) : (
|
||||||
|
filteredBranches.map((branch) => (
|
||||||
<button
|
<button
|
||||||
key={branch}
|
key={branch}
|
||||||
onClick={() => void handleSwitchBranch(branch)}
|
onClick={() => void handleSwitchBranch(branch)}
|
||||||
@@ -163,7 +205,8 @@ export default function GitPanelHeader({
|
|||||||
<span className={branch === currentBranch ? 'font-medium' : ''}>{branch}</span>
|
<span className={branch === currentBranch ? 'font-medium' : ''}>{branch}</span>
|
||||||
</span>
|
</span>
|
||||||
</button>
|
</button>
|
||||||
))}
|
))
|
||||||
|
)}
|
||||||
</div>
|
</div>
|
||||||
<div className="border-t border-border py-1">
|
<div className="border-t border-border py-1">
|
||||||
<button
|
<button
|
||||||
|
|||||||
@@ -1,5 +1,5 @@
|
|||||||
import { Check, GitBranch, Globe, Plus, RefreshCw, Trash2 } from 'lucide-react';
|
import { Check, GitBranch, Globe, Plus, RefreshCw, Search, Trash2, X } from 'lucide-react';
|
||||||
import { useState } from 'react';
|
import { useMemo, useState } from 'react';
|
||||||
import type { ConfirmationRequest, GitRemoteStatus } from '../../types/types';
|
import type { ConfirmationRequest, GitRemoteStatus } from '../../types/types';
|
||||||
import NewBranchModal from '../modals/NewBranchModal';
|
import NewBranchModal from '../modals/NewBranchModal';
|
||||||
|
|
||||||
@@ -138,10 +138,21 @@ export default function BranchesView({
|
|||||||
onRequestConfirmation,
|
onRequestConfirmation,
|
||||||
}: BranchesViewProps) {
|
}: BranchesViewProps) {
|
||||||
const [showNewBranchModal, setShowNewBranchModal] = useState(false);
|
const [showNewBranchModal, setShowNewBranchModal] = useState(false);
|
||||||
|
const [branchSearchQuery, setBranchSearchQuery] = useState('');
|
||||||
|
|
||||||
const aheadCount = remoteStatus?.ahead ?? 0;
|
const aheadCount = remoteStatus?.ahead ?? 0;
|
||||||
const behindCount = remoteStatus?.behind ?? 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) => {
|
const requestSwitch = (branch: string) => {
|
||||||
onRequestConfirmation({
|
onRequestConfirmation({
|
||||||
type: 'commit', // reuse neutral type for switch
|
type: 'commit', // reuse neutral type for switch
|
||||||
@@ -182,12 +193,33 @@ export default function BranchesView({
|
|||||||
</button>
|
</button>
|
||||||
</div>
|
</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 */}
|
{/* Branch list */}
|
||||||
<div className="flex-1 overflow-y-auto">
|
<div className="flex-1 overflow-y-auto">
|
||||||
{localBranches.length > 0 && (
|
{filteredLocalBranches.length > 0 && (
|
||||||
<>
|
<>
|
||||||
<SectionHeader label="Local" count={localBranches.length} />
|
<SectionHeader label="Local" count={filteredLocalBranches.length} />
|
||||||
{localBranches.map((branch) => (
|
{filteredLocalBranches.map((branch) => (
|
||||||
<BranchRow
|
<BranchRow
|
||||||
key={`local:${branch}`}
|
key={`local:${branch}`}
|
||||||
name={branch}
|
name={branch}
|
||||||
@@ -203,10 +235,10 @@ export default function BranchesView({
|
|||||||
</>
|
</>
|
||||||
)}
|
)}
|
||||||
|
|
||||||
{remoteBranches.length > 0 && (
|
{filteredRemoteBranches.length > 0 && (
|
||||||
<>
|
<>
|
||||||
<SectionHeader label="Remote" count={remoteBranches.length} />
|
<SectionHeader label="Remote" count={filteredRemoteBranches.length} />
|
||||||
{remoteBranches.map((branch) => (
|
{filteredRemoteBranches.map((branch) => (
|
||||||
<BranchRow
|
<BranchRow
|
||||||
key={`remote:${branch}`}
|
key={`remote:${branch}`}
|
||||||
name={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">
|
<div className="flex h-32 flex-col items-center justify-center gap-2 text-muted-foreground">
|
||||||
<GitBranch className="h-10 w-10 opacity-30" />
|
<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>
|
||||||
)}
|
)}
|
||||||
</div>
|
</div>
|
||||||
|
|||||||
@@ -19,6 +19,8 @@ type ChangesViewProps = {
|
|||||||
onOpenFile: (filePath: string) => Promise<void>;
|
onOpenFile: (filePath: string) => Promise<void>;
|
||||||
onDiscardFile: (filePath: string) => Promise<void>;
|
onDiscardFile: (filePath: string) => Promise<void>;
|
||||||
onDeleteFile: (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>;
|
onCommitChanges: (message: string, files: string[]) => Promise<boolean>;
|
||||||
onGenerateCommitMessage: (files: string[]) => Promise<string | null>;
|
onGenerateCommitMessage: (files: string[]) => Promise<string | null>;
|
||||||
onRequestConfirmation: (request: ConfirmationRequest) => void;
|
onRequestConfirmation: (request: ConfirmationRequest) => void;
|
||||||
@@ -38,6 +40,8 @@ export default function ChangesView({
|
|||||||
onOpenFile,
|
onOpenFile,
|
||||||
onDiscardFile,
|
onDiscardFile,
|
||||||
onDeleteFile,
|
onDeleteFile,
|
||||||
|
onStageFiles,
|
||||||
|
onUnstageFiles,
|
||||||
onCommitChanges,
|
onCommitChanges,
|
||||||
onGenerateCommitMessage,
|
onGenerateCommitMessage,
|
||||||
onRequestConfirmation,
|
onRequestConfirmation,
|
||||||
@@ -55,12 +59,9 @@ export default function ChangesView({
|
|||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
// Remove any selected files that no longer exist in the status
|
// The Staged section mirrors the real git index reported by /status, so
|
||||||
setSelectedFiles((prev) => {
|
// files staged outside the app (VSCode, terminal) show up here too.
|
||||||
const allFiles = new Set(getAllChangedFiles(gitStatus));
|
setSelectedFiles(new Set(gitStatus.staged ?? []));
|
||||||
const next = new Set([...prev].filter((f) => allFiles.has(f)));
|
|
||||||
return next;
|
|
||||||
});
|
|
||||||
}, [gitStatus]);
|
}, [gitStatus]);
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
@@ -85,17 +86,25 @@ export default function ChangesView({
|
|||||||
});
|
});
|
||||||
}, []);
|
}, []);
|
||||||
|
|
||||||
const toggleFileSelected = useCallback((filePath: string) => {
|
// 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) => {
|
setSelectedFiles((previous) => {
|
||||||
const next = new Set(previous);
|
const next = new Set(previous);
|
||||||
if (next.has(filePath)) {
|
if (isStaged) {
|
||||||
next.delete(filePath);
|
next.delete(filePath);
|
||||||
} else {
|
} else {
|
||||||
next.add(filePath);
|
next.add(filePath);
|
||||||
}
|
}
|
||||||
return next;
|
return next;
|
||||||
});
|
});
|
||||||
}, []);
|
void (isStaged ? onUnstageFiles([filePath]) : onStageFiles([filePath]));
|
||||||
|
},
|
||||||
|
[onStageFiles, onUnstageFiles, selectedFiles],
|
||||||
|
);
|
||||||
|
|
||||||
const requestFileAction = useCallback(
|
const requestFileAction = useCallback(
|
||||||
(filePath: string, status: FileStatusCode) => {
|
(filePath: string, status: FileStatusCode) => {
|
||||||
@@ -197,7 +206,11 @@ export default function ChangesView({
|
|||||||
</span>
|
</span>
|
||||||
{selectedFiles.size > 0 && (
|
{selectedFiles.size > 0 && (
|
||||||
<button
|
<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"
|
className="text-xs text-primary transition-colors hover:text-primary/80"
|
||||||
>
|
>
|
||||||
Unstage All
|
Unstage All
|
||||||
@@ -230,7 +243,11 @@ export default function ChangesView({
|
|||||||
</span>
|
</span>
|
||||||
{unstagedFiles.size > 0 && (
|
{unstagedFiles.size > 0 && (
|
||||||
<button
|
<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"
|
className="text-xs text-primary transition-colors hover:text-primary/80"
|
||||||
>
|
>
|
||||||
Stage All
|
Stage All
|
||||||
|
|||||||
Reference in New Issue
Block a user