diff --git a/src/main/git/repo-search-ref-compat.test.ts b/src/main/git/repo-search-ref-compat.test.ts new file mode 100644 index 000000000..9e9659a11 --- /dev/null +++ b/src/main/git/repo-search-ref-compat.test.ts @@ -0,0 +1,47 @@ +import { afterEach, describe, expect, it, vi } from 'vitest' + +const { gitExecFileAsyncMock } = vi.hoisted(() => ({ + gitExecFileAsyncMock: vi.fn() +})) + +vi.mock('./runner', () => ({ + gitExecFileAsync: gitExecFileAsyncMock, + gitExecFileSync: vi.fn() +})) + +import { searchBaseRefs } from './repo' + +describe('searchBaseRefs git compatibility', () => { + afterEach(() => { + gitExecFileAsyncMock.mockReset() + }) + + it('falls back when older git does not support for-each-ref --exclude', async () => { + gitExecFileAsyncMock.mockImplementation(async (args: string[]) => { + if (args[0] === 'remote') { + return { stdout: 'origin\n', stderr: '' } + } + if (args.includes('--exclude=refs/remotes/**/HEAD')) { + throw Object.assign(new Error("unknown option `exclude'"), { + stderr: "error: unknown option `exclude'" + }) + } + return { + stdout: [ + 'refs/remotes/origin/main\0origin/main', + 'refs/remotes/origin/HEAD\0origin/HEAD' + ].join('\n'), + stderr: '' + } + }) + + await expect(searchBaseRefs('/repo', '', 1)).resolves.toEqual(['origin/main']) + const forEachRefCalls = gitExecFileAsyncMock.mock.calls.filter( + (call) => (call[0] as string[])[0] === 'for-each-ref' + ) + expect(forEachRefCalls).toHaveLength(2) + expect(forEachRefCalls[0][0]).toContain('--exclude=refs/remotes/**/HEAD') + expect(forEachRefCalls[1][0]).not.toContain('--exclude=refs/remotes/**/HEAD') + expect(forEachRefCalls[1][0]).toContain('--count=104') + }) +}) diff --git a/src/main/git/repo.test.ts b/src/main/git/repo.test.ts index 8cdb1852b..8521d3469 100644 --- a/src/main/git/repo.test.ts +++ b/src/main/git/repo.test.ts @@ -5,6 +5,7 @@ import { tmpdir } from 'os' import path from 'path' import { + buildSearchBaseRefsArgv, getDefaultBaseRef, getBranchConflictKind, getRemoteCount, @@ -218,10 +219,32 @@ describe('searchBaseRefs (widened glob)', () => { expect(results).toEqual([]) }) - it('returns [] without error for an empty query', async () => { + it('returns recent refs for an empty query so branch pickers can open populated', async () => { + const sha = getHeadSha(tmpDir) + createRemoteRef(tmpDir, 'upstream/main', sha) + createRemoteRef(tmpDir, 'upstream/feature-x', sha) + const results = await searchBaseRefs(tmpDir, '') - expect(results).toEqual([]) + expect(results).toEqual(['main', 'upstream/feature-x', 'upstream/main']) + }) + + it('caps broad ref-search argv before git output is captured', () => { + const argv = buildSearchBaseRefsArgv('', 12) + + expect(argv).toContain('--exclude=refs/remotes/**/HEAD') + expect(argv).toContain('--count=48') + }) + + it('does not hard-cap large explicit ref-search limits below the request size', () => { + const argv = buildSearchBaseRefsArgv('', 600) + + expect(argv).toContain('--count=2400') + }) + + it('returns [] for invalid search limits instead of running an uncapped search', async () => { + await expect(searchBaseRefs(tmpDir, '', 0.5)).resolves.toEqual([]) + await expect(searchBaseRefs(tmpDir, '', Number.NaN)).resolves.toEqual([]) }) // Why: the picker displays results as `/` and labels diff --git a/src/main/git/repo.ts b/src/main/git/repo.ts index ad23d8e77..fff8ad5a5 100644 --- a/src/main/git/repo.ts +++ b/src/main/git/repo.ts @@ -478,8 +478,39 @@ async function getDefaultBaseRefAsync(path: string): Promise { * Why shared: the local path and the SSH relay path must send the exact * same argv so results cannot diverge between transports. */ -export function buildSearchBaseRefsArgv(normalizedQuery: string): string[] { - const base = ['for-each-ref', '--format=%(refname)%00%(refname:short)', '--sort=-committerdate'] +const REF_SEARCH_CANDIDATE_MULTIPLIER = 4 +const REF_SEARCH_LEGACY_HEADROOM = 100 + +function getRefSearchCandidateCount(limit: number, excludesRemoteHead: boolean): number { + if (!Number.isInteger(limit) || limit <= 0) { + throw new Error('invalid_limit') + } + const baseCount = limit * REF_SEARCH_CANDIDATE_MULTIPLIER + return excludesRemoteHead ? baseCount : baseCount + REF_SEARCH_LEGACY_HEADROOM +} + +export function buildSearchBaseRefsArgv( + normalizedQuery: string, + limit: number, + options: { excludeRemoteHead?: boolean } = {} +): string[] { + const excludeRemoteHead = options.excludeRemoteHead ?? true + const candidateCount = getRefSearchCandidateCount(limit, excludeRemoteHead) + const base = [ + 'for-each-ref', + '--format=%(refname)%00%(refname:short)', + '--sort=-committerdate', + ...(excludeRemoteHead + ? [ + // Why: exclude remote HEAD pseudo-refs before --count so the bounded + // candidate window is spent on refs the picker can actually display. + '--exclude=refs/remotes/**/HEAD' + ] + : []), + // Why: empty Branch-tab searches use broad globs; cap git output before + // execFile/SSH buffers capture every ref in very large repositories. + `--count=${candidateCount}` + ] // Why: split on `/` so display-format queries (`upstream/main`) route // each token to one git ref segment. Filter empty tokens so trailing // (`upstream/`), leading (`/main`), or doubled (`upstream//main`) @@ -512,6 +543,18 @@ export function buildSearchBaseRefsArgv(normalizedQuery: string): string[] { return [...base, `refs/remotes/${segmented}`, `refs/heads/${segmented}`] } +export function isForEachRefExcludeUnsupportedError(error: unknown): boolean { + if (!error || typeof error !== 'object') { + return false + } + const maybe = error as { message?: unknown; stderr?: unknown; stdout?: unknown } + const text = [maybe.message, maybe.stderr, maybe.stdout] + .filter((value): value is string => typeof value === 'string') + .join('\n') + .toLowerCase() + return text.includes('unknown option') && text.includes('exclude') +} + /** * Resolve the default push remote for a repo. * Order: remote configured on the current default branch → origin → the single @@ -578,20 +621,32 @@ export async function searchBaseRefDetails( query: string, limit = 25 ): Promise { - const normalizedQuery = normalizeRefSearchQuery(query) - if (!normalizedQuery) { + if (!Number.isInteger(limit) || limit <= 0) { return [] } + const normalizedQuery = normalizeRefSearchQuery(query) try { // Why: argv (including the two-remote-glob rationale) lives in // buildSearchBaseRefsArgv so the SSH sibling cannot drift. - const [{ stdout }, remotes] = await Promise.all([ - gitExecFileAsync(buildSearchBaseRefsArgv(normalizedQuery), { cwd: path }), - listRemoteNames(path) - ]) + const remotesPromise = listRemoteNames(path) + let result: { stdout: string } + try { + result = await gitExecFileAsync(buildSearchBaseRefsArgv(normalizedQuery, limit), { + cwd: path + }) + } catch (err) { + if (!isForEachRefExcludeUnsupportedError(err)) { + throw err + } + result = await gitExecFileAsync( + buildSearchBaseRefsArgv(normalizedQuery, limit, { excludeRemoteHead: false }), + { cwd: path } + ) + } + const remotes = await remotesPromise - return parseAndFilterSearchRefDetails(stdout, limit, remotes) + return parseAndFilterSearchRefDetails(result.stdout, limit, remotes) } catch (err) { // Why: surface the failure for diagnostics; callers treat `[]` as "no // matches", but silently swallowing the error makes a missing result diff --git a/src/main/ipc/repos-remote.test.ts b/src/main/ipc/repos-remote.test.ts index da6b5c79f..8af78912a 100644 --- a/src/main/ipc/repos-remote.test.ts +++ b/src/main/ipc/repos-remote.test.ts @@ -1332,7 +1332,17 @@ describe('repos:searchBaseRefs SSH relay', () => { expect(mockGitProvider.exec).not.toHaveBeenCalled() }) - it('short-circuits an empty query without calling the relay', async () => { + it('returns refs for an empty query so remote Branch pickers open populated', async () => { + const stdout = [ + 'refs/remotes/origin/main\0origin/main', + 'refs/remotes/upstream/feature-x\0upstream/feature-x' + ].join('\n') + mockGitProvider.exec = vi.fn().mockImplementation((argv: string[]) => { + if (argv[0] === 'remote') { + return Promise.resolve({ stdout: 'origin\nupstream\n', stderr: '' }) + } + return Promise.resolve({ stdout, stderr: '' }) + }) mockStore.getRepo.mockReturnValue({ id: 'r1', path: '/remote/repo', @@ -1345,14 +1355,47 @@ describe('repos:searchBaseRefs SSH relay', () => { query: '' }) - // Why: empty-query short-circuit must happen in the handler (mirrors the - // local path's normalizeRefSearchQuery guard). Without it a user-typed - // empty query would leak every ref from the remote. - expect(result).toEqual([]) - expect(mockGitProvider.exec).not.toHaveBeenCalled() + expect(result).toEqual(['origin/main', 'upstream/feature-x']) + expect(mockGitProvider.exec).toHaveBeenCalledTimes(2) + const [argv] = mockGitProvider.exec.mock.calls.find( + (call) => (call[0] as string[])[0] === 'for-each-ref' + )! + expect(argv).toContain('--exclude=refs/remotes/**/HEAD') + expect(argv).toContain('--count=100') + expect(argv).toContain('refs/heads/**/**') + expect(argv).toContain('refs/heads/**/**/**') + expect(argv).toContain('refs/remotes/**/**') + expect(argv).toContain('refs/remotes/**/**/**') }) - it('short-circuits a query containing only glob metacharacters', async () => { + it('sanitizes glob metacharacter-only queries into the empty-query branch list', async () => { + mockGitProvider.exec = vi.fn().mockResolvedValue({ stdout: '', stderr: '' }) + mockStore.getRepo.mockReturnValue({ + id: 'r1', + path: '/remote/repo', + connectionId: 'conn-1', + kind: 'git' + }) + + await handlers.get('repos:searchBaseRefs')!(null, { + repoId: 'r1', + query: '***' + }) + + // Why: normalizeRefSearchQuery still strips glob metacharacters before + // building argv; the resulting empty query now intentionally lists refs. + const [argv] = mockGitProvider.exec.mock.calls.find( + (call) => (call[0] as string[])[0] === 'for-each-ref' + )! + expect(argv).toContain('--exclude=refs/remotes/**/HEAD') + expect(argv).toContain('--count=100') + expect(argv).toContain('refs/heads/**/**') + expect(argv).toContain('refs/heads/**/**/**') + expect(argv).toContain('refs/remotes/**/**') + expect(argv).toContain('refs/remotes/**/**/**') + }) + + it('rejects invalid limits before building broad relay searches', async () => { mockStore.getRepo.mockReturnValue({ id: 'r1', path: '/remote/repo', @@ -1362,17 +1405,55 @@ describe('repos:searchBaseRefs SSH relay', () => { const result = await handlers.get('repos:searchBaseRefs')!(null, { repoId: 'r1', - query: '***' + query: '', + limit: 0.5 }) - // Why: normalizeRefSearchQuery strips `*?[]\`, so a query made up only of - // glob metacharacters normalizes to '' and must be treated like an empty - // query (no relay call, no leaked refs). Guards against glob injection - // via the SSH branch. expect(result).toEqual([]) expect(mockGitProvider.exec).not.toHaveBeenCalled() }) + it('retries without --exclude for older git on SSH hosts', async () => { + const stdout = [ + 'refs/remotes/origin/main\0origin/main', + 'refs/remotes/origin/HEAD\0origin/HEAD' + ].join('\n') + mockGitProvider.exec = vi.fn().mockImplementation((argv: string[]) => { + if (argv[0] === 'remote') { + return Promise.resolve({ stdout: 'origin\n', stderr: '' }) + } + if (argv.includes('--exclude=refs/remotes/**/HEAD')) { + return Promise.reject( + Object.assign(new Error("unknown option `exclude'"), { + stderr: "error: unknown option `exclude'" + }) + ) + } + return Promise.resolve({ stdout, stderr: '' }) + }) + mockStore.getRepo.mockReturnValue({ + id: 'r1', + path: '/remote/repo', + connectionId: 'conn-1', + kind: 'git' + }) + + const result = await handlers.get('repos:searchBaseRefs')!(null, { + repoId: 'r1', + query: '', + limit: 1 + }) + + expect(result).toEqual(['origin/main']) + const forEachRefCalls = mockGitProvider.exec.mock.calls.filter( + (call) => (call[0] as string[])[0] === 'for-each-ref' + ) + expect(forEachRefCalls).toHaveLength(2) + expect(forEachRefCalls[0][0]).toContain('--exclude=refs/remotes/**/HEAD') + expect(forEachRefCalls[1][0]).not.toContain('--exclude=refs/remotes/**/HEAD') + expect(forEachRefCalls[1][0]).toContain('--count=104') + }) + it('sends the widened `**` argv so all remotes and slash-named branches are discoverable', async () => { // Why: this is the core issue-624 behavior — the SSH path must glob all // remotes, not just origin. The `**` globs additionally span ref segments @@ -1390,7 +1471,9 @@ describe('repos:searchBaseRefs SSH relay', () => { await handlers.get('repos:searchBaseRefs')!(null, { repoId: 'r1', query: 'upstream' }) expect(mockGitProvider.exec).toHaveBeenCalledTimes(2) - const [argv, path] = mockGitProvider.exec.mock.calls[0] + const [argv, path] = mockGitProvider.exec.mock.calls.find( + (call) => (call[0] as string[])[0] === 'for-each-ref' + )! expect(path).toBe('/remote/repo') expect(argv[0]).toBe('for-each-ref') expect(argv).toContain('refs/heads/**/*upstream*') @@ -1399,7 +1482,7 @@ describe('repos:searchBaseRefs SSH relay', () => { expect(argv).toContain('refs/remotes/**/*upstream*/**') // Guard against regression to the old origin-only glob. expect(argv).not.toContain('refs/remotes/origin/*upstream*') - expect(mockGitProvider.exec.mock.calls[1]).toEqual([['remote'], '/remote/repo']) + expect(mockGitProvider.exec).toHaveBeenCalledWith(['remote'], '/remote/repo') }) it('sends segmented argv for display-format queries like `upstream/main`', async () => { @@ -1420,7 +1503,9 @@ describe('repos:searchBaseRefs SSH relay', () => { await handlers.get('repos:searchBaseRefs')!(null, { repoId: 'r1', query: 'upstream/main' }) expect(mockGitProvider.exec).toHaveBeenCalledTimes(2) - const [argv] = mockGitProvider.exec.mock.calls[0] + const [argv] = mockGitProvider.exec.mock.calls.find( + (call) => (call[0] as string[])[0] === 'for-each-ref' + )! expect(argv).toContain('refs/remotes/*upstream*/*main*') expect(argv).toContain('refs/heads/*upstream*/*main*') // Regression guard: the literal slash must never appear inside a @@ -1428,7 +1513,7 @@ describe('repos:searchBaseRefs SSH relay', () => { // which fnmatch cannot match because `*` doesn't cross `/`. expect(argv).not.toContain('refs/remotes/*upstream/main*/*') expect(argv).not.toContain('refs/remotes/*/*upstream/main*') - expect(mockGitProvider.exec.mock.calls[1]).toEqual([['remote'], '/remote/repo']) + expect(mockGitProvider.exec).toHaveBeenCalledWith(['remote'], '/remote/repo') }) it('parses NUL-delimited stdout and filters /HEAD pseudo-refs', async () => { diff --git a/src/main/ipc/repos.ts b/src/main/ipc/repos.ts index 66ec75eaf..148c00e4b 100644 --- a/src/main/ipc/repos.ts +++ b/src/main/ipc/repos.ts @@ -50,6 +50,7 @@ import { parseRemoteCount, resolveDefaultBaseRefViaExec, buildSearchBaseRefsArgv, + isForEachRefExcludeUnsupportedError, searchBaseRefDetails } from '../git/repo' import { getSshGitProvider } from '../providers/ssh-git-dispatch' @@ -1385,6 +1386,9 @@ async function searchBaseRefDetailsForRepo( return [] } const limit = args.limit ?? 25 + if (!Number.isInteger(limit) || limit <= 0) { + return [] + } // Why: remote repos need the relay to list branches on the remote host. if (repo.connectionId) { const provider = getSshGitProvider(repo.connectionId) @@ -1393,20 +1397,25 @@ async function searchBaseRefDetailsForRepo( } // Why: mirror the local path's sanitization (normalizeRefSearchQuery // in ../git/repo.ts) — strip glob metacharacters to prevent glob - // injection via the SSH branch, and short-circuit empty queries so - // we don't leak every ref. Without this the SSH path diverges from - // the local path's behavior. + // injection via the SSH branch while preserving empty-query branch lists. const normalizedQuery = normalizeRefSearchQuery(args.query) - if (!normalizedQuery) { - return [] - } try { // Why: argv (including the two-remote-glob rationale) lives in // buildSearchBaseRefsArgv so the SSH and local paths cannot drift. - const [result, remotesResult] = await Promise.all([ - provider.exec(buildSearchBaseRefsArgv(normalizedQuery), repo.path), - provider.exec(['remote'], repo.path).catch(() => ({ stdout: '' })) - ]) + const remotesPromise = provider.exec(['remote'], repo.path).catch(() => ({ stdout: '' })) + let result: { stdout: string } + try { + result = await provider.exec(buildSearchBaseRefsArgv(normalizedQuery, limit), repo.path) + } catch (err) { + if (!isForEachRefExcludeUnsupportedError(err)) { + throw err + } + result = await provider.exec( + buildSearchBaseRefsArgv(normalizedQuery, limit, { excludeRemoteHead: false }), + repo.path + ) + } + const remotesResult = await remotesPromise // Why: delegate the NUL-parse + HEAD filter + dedup + limit pipeline // to the shared helper so the SSH and local paths cannot diverge. // See parseAndFilterSearchRefs in ../git/repo.ts for the dedup + diff --git a/src/main/runtime/orca-runtime.test.ts b/src/main/runtime/orca-runtime.test.ts index 16e4031af..6a389e005 100644 --- a/src/main/runtime/orca-runtime.test.ts +++ b/src/main/runtime/orca-runtime.test.ts @@ -6134,6 +6134,118 @@ describe('OrcaRuntimeService', () => { await expect(runtime.searchRepoRefs('id:repo-1', 'main', -5)).rejects.toThrow('invalid_limit') }) + it('returns capped SSH refs for empty runtime repo searches', async () => { + const remoteRepo = { + id: 'remote-repo', + path: '/home/user/repo', + displayName: 'remote', + badgeColor: 'blue', + addedAt: 1, + connectionId: 'ssh-1' + } + const runtimeStore = { + ...store, + getRepos: () => [remoteRepo], + getRepo: () => remoteRepo + } + const provider = { + exec: vi.fn().mockImplementation((argv: string[]) => { + if (argv[0] === 'remote') { + return Promise.resolve({ stdout: 'origin\nupstream\n', stderr: '' }) + } + return Promise.resolve({ + stdout: [ + 'refs/remotes/origin/main\0origin/main', + 'refs/remotes/upstream/feature-x\0upstream/feature-x', + 'refs/remotes/upstream/HEAD\0upstream/HEAD', + 'refs/heads/local-only\0local-only' + ].join('\n'), + stderr: '' + }) + }) + } + registerSshGitProvider('ssh-1', provider as never) + const runtime = new OrcaRuntimeService(runtimeStore as never) + + const result = await runtime.searchRepoRefs('id:remote-repo', '', 2) + + expect(result).toEqual({ + refs: ['origin/main', 'upstream/feature-x'], + refDetails: [ + { refName: 'origin/main', localBranchName: 'main' }, + { refName: 'upstream/feature-x', localBranchName: 'feature-x' } + ], + truncated: true + }) + expect(provider.exec).toHaveBeenCalledWith( + expect.arrayContaining([ + '--exclude=refs/remotes/**/HEAD', + '--count=12', + 'refs/heads/**/**', + 'refs/heads/**/**/**', + 'refs/remotes/**/**', + 'refs/remotes/**/**/**' + ]), + '/home/user/repo' + ) + expect(provider.exec).toHaveBeenCalledWith(['remote'], '/home/user/repo') + }) + + it('retries runtime SSH ref searches without --exclude for older git hosts', async () => { + const remoteRepo = { + id: 'remote-repo', + path: '/home/user/repo', + displayName: 'remote', + badgeColor: 'blue', + addedAt: 1, + connectionId: 'ssh-1' + } + const runtimeStore = { + ...store, + getRepos: () => [remoteRepo], + getRepo: () => remoteRepo + } + const provider = { + exec: vi.fn().mockImplementation((argv: string[]) => { + if (argv[0] === 'remote') { + return Promise.resolve({ stdout: 'origin\n', stderr: '' }) + } + if (argv.includes('--exclude=refs/remotes/**/HEAD')) { + return Promise.reject( + Object.assign(new Error("unknown option `exclude'"), { + stderr: "error: unknown option `exclude'" + }) + ) + } + return Promise.resolve({ + stdout: [ + 'refs/remotes/origin/main\0origin/main', + 'refs/remotes/origin/HEAD\0origin/HEAD', + 'refs/remotes/origin/feature-x\0origin/feature-x' + ].join('\n'), + stderr: '' + }) + }) + } + registerSshGitProvider('ssh-1', provider as never) + const runtime = new OrcaRuntimeService(runtimeStore as never) + + const result = await runtime.searchRepoRefs('id:remote-repo', '', 1) + + expect(result).toEqual({ + refs: ['origin/main'], + refDetails: [{ refName: 'origin/main', localBranchName: 'main' }], + truncated: true + }) + const forEachRefCalls = provider.exec.mock.calls.filter( + (call) => (call[0] as string[])[0] === 'for-each-ref' + ) + expect(forEachRefCalls).toHaveLength(2) + expect(forEachRefCalls[0][0]).toContain('--exclude=refs/remotes/**/HEAD') + expect(forEachRefCalls[1][0]).not.toContain('--exclude=refs/remotes/**/HEAD') + expect(forEachRefCalls[1][0]).toContain('--count=108') + }) + it('resolves SSH worktrees when manually updating lineage', async () => { const remoteRepo = { id: 'remote-repo', diff --git a/src/main/runtime/orca-runtime.ts b/src/main/runtime/orca-runtime.ts index f4806c941..976371284 100644 --- a/src/main/runtime/orca-runtime.ts +++ b/src/main/runtime/orca-runtime.ts @@ -306,6 +306,7 @@ import { parseRemoteCount, resolveDefaultBaseRefViaExec, buildSearchBaseRefsArgv, + isForEachRefExcludeUnsupportedError, getRemoteDrift, getRecentDriftSubjects } from '../git/repo' @@ -5796,14 +5797,21 @@ export class OrcaRuntimeService { return [] } const normalizedQuery = normalizeRefSearchQuery(query) - if (!normalizedQuery) { - return [] - } try { - const [result, remotesResult] = await Promise.all([ - provider.exec(buildSearchBaseRefsArgv(normalizedQuery), repo.path), - provider.exec(['remote'], repo.path).catch(() => ({ stdout: '' })) - ]) + const remotesPromise = provider.exec(['remote'], repo.path).catch(() => ({ stdout: '' })) + let result: { stdout: string } + try { + result = await provider.exec(buildSearchBaseRefsArgv(normalizedQuery, limit), repo.path) + } catch (err) { + if (!isForEachRefExcludeUnsupportedError(err)) { + throw err + } + result = await provider.exec( + buildSearchBaseRefsArgv(normalizedQuery, limit, { excludeRemoteHead: false }), + repo.path + ) + } + const remotesResult = await remotesPromise const remotes = remotesResult.stdout .split('\n') .map((line) => line.trim()) diff --git a/src/renderer/src/components/new-workspace/SmartWorkspaceNameField.tsx b/src/renderer/src/components/new-workspace/SmartWorkspaceNameField.tsx index f3356ce7a..e6bbaa4bd 100644 --- a/src/renderer/src/components/new-workspace/SmartWorkspaceNameField.tsx +++ b/src/renderer/src/components/new-workspace/SmartWorkspaceNameField.tsx @@ -43,6 +43,14 @@ import { parseGitLabIssueOrMRLink } from '@/lib/gitlab-links' import { cn } from '@/lib/utils' import { LinearIcon } from '@/components/icons/LinearIcon' import { searchRuntimeRepoBaseRefDetails } from '@/runtime/runtime-repo-client' +import { + buildSmartWorkspaceSourceRows, + getBranchSearchRequest, + getSmartWorkspaceEmptyHint, + getVisibleBranchResults, + type SmartNameMode, + type SmartWorkspaceSourceRow +} from './smart-workspace-source-results' import { filterAvailableTaskProviders } from '../../../../shared/task-providers' import type { BaseRefSearchResult, @@ -51,8 +59,6 @@ import type { LinearIssue } from '../../../../shared/types' -type SmartNameMode = 'smart' | 'github' | 'gitlab' | 'branches' | 'linear' | 'text' - // Why: GitLab MR list filter — Open / Merged / Closed / All — replaces // GitHub's search-DSL on the GitLab tab per the agreed scope. type MrStateFilter = 'opened' | 'merged' | 'closed' | 'all' @@ -117,22 +123,7 @@ const MODES: { { id: 'text', label: 'Name', Icon: CaseSensitive } ] -const emptyHintByMode: Record = { - smart: 'Start typing to create a name or find a source.', - github: 'Start typing to search GitHub PRs and issues.', - gitlab: 'Start typing to search GitLab MRs and issues.', - branches: 'Start typing to find a branch or create a new one.', - linear: 'Start typing to search Linear issues.', - text: '' -} - -type RowEntry = - | { kind: 'use-name'; value: string; name: string } - | { kind: 'create-branch'; value: string; name: string } - | { kind: 'github'; value: string; item: GitHubWorkItem } - | { kind: 'gitlab'; value: string; item: GitLabWorkItem } - | { kind: 'branch'; value: string; refName: string; localBranchName: string } - | { kind: 'linear'; value: string; issue: LinearIssue } +type RowEntry = SmartWorkspaceSourceRow export default function SmartWorkspaceNameField({ repos, @@ -192,6 +183,10 @@ export default function SmartWorkspaceNameField({ const [githubItems, setGithubItems] = useState([]) const [gitlabItems, setGitlabItems] = useState([]) const [branches, setBranches] = useState([]) + const [branchResultsSource, setBranchResultsSource] = useState<{ + repoId: string + query: string + } | null>(null) const [linearIssues, setLinearIssues] = useState([]) const [githubLoading, setGithubLoading] = useState(false) const [gitlabLoading, setGitlabLoading] = useState(false) @@ -293,6 +288,7 @@ export default function SmartWorkspaceNameField({ setGithubItems([]) setGitlabItems([]) setBranches([]) + setBranchResultsSource(null) setLinearIssues([]) setGithubLoading(false) setGitlabLoading(false) @@ -322,7 +318,6 @@ export default function SmartWorkspaceNameField({ ) const parsedGhLink = useMemo(() => parseGitHubIssueOrPRLink(debouncedQuery), [debouncedQuery]) const shouldQueryGithub = !textOnly && (mode === 'smart' || mode === 'github') - const shouldQueryBranches = !textOnly && (mode === 'smart' || mode === 'branches') const shouldQueryLinear = !textOnly && linearAvailable && (mode === 'smart' || mode === 'linear') useEffect(() => { @@ -463,28 +458,49 @@ export default function SmartWorkspaceNameField({ shouldQueryGithub ]) + const branchSearchRequest = useMemo( + () => + getBranchSearchRequest({ + disabled, + textOnly, + mode, + selectedRepoId: selectedRepo?.id ?? null, + query: debouncedQuery, + limit: RESULT_LIMIT + }), + [debouncedQuery, disabled, mode, selectedRepo?.id, textOnly] + ) + useEffect(() => { - if (disabled || !shouldQueryBranches || !selectedRepo) { + if (!branchSearchRequest) { setBranches([]) + setBranchResultsSource(null) setBranchesLoading(false) return } let stale = false + setBranches([]) + setBranchResultsSource(null) setBranchesLoading(true) void searchRuntimeRepoBaseRefDetails( settings, - selectedRepo.id, - debouncedQuery.trim(), - RESULT_LIMIT + branchSearchRequest.repoId, + branchSearchRequest.query, + branchSearchRequest.limit ) .then((results) => { if (!stale) { setBranches(results) + setBranchResultsSource({ + repoId: branchSearchRequest.repoId, + query: branchSearchRequest.query + }) } }) .catch(() => { if (!stale) { setBranches([]) + setBranchResultsSource(null) } }) .finally(() => { @@ -495,7 +511,7 @@ export default function SmartWorkspaceNameField({ return () => { stale = true } - }, [debouncedQuery, disabled, selectedRepo, settings, shouldQueryBranches]) + }, [branchSearchRequest, settings]) useEffect(() => { if (disabled || !shouldQueryLinear || !linearStatus.connected) { @@ -667,87 +683,39 @@ export default function SmartWorkspaceNameField({ shouldQueryGitlab ]) - const rows = useMemo(() => { - const trimmed = value.trim() - // Why: on the Branches tab the generic "Use … as workspace name" row - // reads as off-topic — the user is picking/creating a branch. Swap it - // for a branch-creation row that's pinned above existing-branch results - // (suppressed when an existing branch matches exactly so we don't offer - // to "create" something that already exists). - const branchExactMatch = - mode === 'branches' && - trimmed.length > 0 && - branches.some((branch) => branch.refName === trimmed || branch.localBranchName === trimmed) - // Why: the "Use … as workspace name" row only makes sense in Smart - // mode, where the user might be typing a free-form name. On dedicated - // source tabs (GitHub/Linear/Branches) it's off-topic — the user is - // there to pick (or, on Branches, create) a source. - const useNameRow: RowEntry | null = - trimmed && mode === 'smart' - ? { kind: 'use-name', value: `use-name-${trimmed}`, name: trimmed } - : null - const createBranchRow: RowEntry | null = - trimmed && mode === 'branches' && !branchExactMatch - ? { kind: 'create-branch', value: `create-branch-${trimmed}`, name: trimmed } - : null - const nextRows: RowEntry[] = [] - if (useNameRow) { - nextRows.push(useNameRow) - } - if (mode === 'text') { - return nextRows - } - if (mode === 'smart' || mode === 'github') { - nextRows.push( - ...githubItems.map((item) => ({ - kind: 'github' as const, - value: `github-${item.type}-${item.number}`, - item - })) - ) - } - if (gitlabAvailable && (mode === 'smart' || mode === 'gitlab')) { - nextRows.push( - ...gitlabItems.map((item) => ({ - kind: 'gitlab' as const, - value: `gitlab-${item.type}-${item.number}`, - item - })) - ) - } - if (mode === 'smart' || mode === 'branches') { - if (createBranchRow) { - nextRows.push(createBranchRow) - } - nextRows.push( - ...branches.map((branch) => ({ - kind: 'branch' as const, - value: `branch-${branch.refName}`, - refName: branch.refName, - localBranchName: branch.localBranchName - })) - ) - } - if (linearAvailable && (mode === 'smart' || mode === 'linear')) { - nextRows.push( - ...linearIssues.map((issue) => ({ - kind: 'linear' as const, - value: `linear-${issue.id}`, - issue - })) - ) - } - return nextRows.slice(0, RESULT_LIMIT + 1) - }, [ - branches, - githubItems, - gitlabAvailable, - gitlabItems, - linearIssues, - linearAvailable, - mode, - value - ]) + const rows = useMemo( + () => + buildSmartWorkspaceSourceRows({ + branches: getVisibleBranchResults({ + branches, + mode, + resultRepoId: branchResultsSource?.repoId ?? null, + resultQuery: branchResultsSource?.query ?? null, + selectedRepoId: selectedRepo?.id ?? null, + value + }), + githubItems, + gitlabAvailable, + gitlabItems, + linearAvailable, + linearIssues, + mode, + resultLimit: RESULT_LIMIT, + value + }), + [ + branches, + branchResultsSource, + githubItems, + gitlabAvailable, + gitlabItems, + linearAvailable, + linearIssues, + mode, + selectedRepo?.id, + value + ] + ) // Why: source rows (GitHub/branches/Linear) are driven by debouncedQuery, // so they're stale until the user pauses typing for SEARCH_DEBOUNCE_MS. @@ -915,8 +883,9 @@ export default function SmartWorkspaceNameField({ { - setMode(next as SmartNameMode) - setOpen(!disabled && next !== 'text') + const nextMode = next as SmartNameMode + setMode(nextMode) + setOpen(!disabled && nextMode !== 'text') requestAnimationFrame(() => localInputRef.current?.focus({ preventScroll: true })) }} className="gap-0" @@ -1166,7 +1135,7 @@ export default function SmartWorkspaceNameField({
{mode === 'linear' && linearStatusChecked && !linearStatus.connected ? 'Connect Linear in Settings to search issues.' - : emptyHintByMode[mode]} + : getSmartWorkspaceEmptyHint(mode)}
) : ( diff --git a/src/renderer/src/components/new-workspace/smart-workspace-source-results.test.ts b/src/renderer/src/components/new-workspace/smart-workspace-source-results.test.ts new file mode 100644 index 000000000..c2d02d7d9 --- /dev/null +++ b/src/renderer/src/components/new-workspace/smart-workspace-source-results.test.ts @@ -0,0 +1,108 @@ +import { describe, expect, it } from 'vitest' +import { + buildSmartWorkspaceSourceRows, + getBranchSearchRequest, + getSmartWorkspaceEmptyHint, + getVisibleBranchResults +} from './smart-workspace-source-results' + +describe('Branch source results', () => { + it('requests empty-query branch results in Branch mode', () => { + expect( + getBranchSearchRequest({ + disabled: false, + textOnly: false, + mode: 'branches', + selectedRepoId: 'repo-1', + query: '', + limit: 12 + }) + ).toEqual({ repoId: 'repo-1', query: '', limit: 12 }) + }) + + it('keeps Smart mode in its start-typing state for an empty query', () => { + expect( + getBranchSearchRequest({ + disabled: false, + textOnly: false, + mode: 'smart', + selectedRepoId: 'repo-1', + query: '', + limit: 12 + }) + ).toBeNull() + }) + + it('hides stale branch rows when Smart mode input is cleared', () => { + const rows = buildSmartWorkspaceSourceRows({ + mode: 'smart', + value: '', + branches: [{ refName: 'origin/old-result', localBranchName: 'old-result' }], + githubItems: [], + gitlabItems: [], + linearIssues: [], + gitlabAvailable: false, + linearAvailable: false, + resultLimit: 12 + }) + + expect(rows).toEqual([]) + }) + + it('hides branch results from a stale Branch-mode query', () => { + expect( + getVisibleBranchResults({ + mode: 'branches', + value: '', + selectedRepoId: 'repo-1', + resultRepoId: 'repo-1', + resultQuery: 'feature', + branches: [{ refName: 'origin/feature', localBranchName: 'feature' }] + }) + ).toEqual([]) + }) + + it('keeps matching empty-query branch results visible in Branch mode', () => { + expect( + getVisibleBranchResults({ + mode: 'branches', + value: '', + selectedRepoId: 'repo-1', + resultRepoId: 'repo-1', + resultQuery: '', + branches: [{ refName: 'origin/main', localBranchName: 'main' }] + }) + ).toEqual([{ refName: 'origin/main', localBranchName: 'main' }]) + }) + + it('keeps returned branch rows visible before the user types', () => { + const rows = buildSmartWorkspaceSourceRows({ + mode: 'branches', + value: '', + branches: [ + { refName: 'main', localBranchName: 'main' }, + { refName: 'origin/feature/autofill', localBranchName: 'feature/autofill' } + ], + githubItems: [], + gitlabItems: [], + linearIssues: [], + gitlabAvailable: false, + linearAvailable: false, + resultLimit: 12 + }) + + expect(rows).toEqual([ + { kind: 'branch', value: 'branch-main', refName: 'main', localBranchName: 'main' }, + { + kind: 'branch', + value: 'branch-origin/feature/autofill', + refName: 'origin/feature/autofill', + localBranchName: 'feature/autofill' + } + ]) + }) + + it('describes empty Branch results after the empty-query search runs', () => { + expect(getSmartWorkspaceEmptyHint('branches')).toBe('No matching branches.') + }) +}) diff --git a/src/renderer/src/components/new-workspace/smart-workspace-source-results.ts b/src/renderer/src/components/new-workspace/smart-workspace-source-results.ts new file mode 100644 index 000000000..6c3cb6940 --- /dev/null +++ b/src/renderer/src/components/new-workspace/smart-workspace-source-results.ts @@ -0,0 +1,153 @@ +import type { + BaseRefSearchResult, + GitHubWorkItem, + GitLabWorkItem, + LinearIssue +} from '../../../../shared/types' + +export type SmartNameMode = 'smart' | 'github' | 'gitlab' | 'branches' | 'linear' | 'text' + +export type SmartWorkspaceSourceRow = + | { kind: 'use-name'; value: string; name: string } + | { kind: 'create-branch'; value: string; name: string } + | { kind: 'github'; value: string; item: GitHubWorkItem } + | { kind: 'gitlab'; value: string; item: GitLabWorkItem } + | { kind: 'branch'; value: string; refName: string; localBranchName: string } + | { kind: 'linear'; value: string; issue: LinearIssue } + +const EMPTY_HINT_BY_MODE: Record = { + smart: 'Start typing to create a name or find a source.', + github: 'Start typing to search GitHub PRs and issues.', + gitlab: 'Start typing to search GitLab MRs and issues.', + branches: 'No matching branches.', + linear: 'Start typing to search Linear issues.', + text: '' +} + +export function getSmartWorkspaceEmptyHint(mode: SmartNameMode): string { + return EMPTY_HINT_BY_MODE[mode] +} + +export function getBranchSearchRequest({ + disabled, + textOnly, + mode, + selectedRepoId, + query, + limit +}: { + disabled: boolean + textOnly: boolean + mode: SmartNameMode + selectedRepoId: string | null + query: string + limit: number +}): { repoId: string; query: string; limit: number } | null { + const trimmedQuery = query.trim() + const shouldSearchBranches = mode === 'branches' || (mode === 'smart' && trimmedQuery.length > 0) + if (disabled || textOnly || !selectedRepoId || !shouldSearchBranches) { + return null + } + return { repoId: selectedRepoId, query: trimmedQuery, limit } +} + +export function getVisibleBranchResults({ + branches, + mode, + resultRepoId, + resultQuery, + selectedRepoId, + value +}: { + branches: BaseRefSearchResult[] + mode: SmartNameMode + resultRepoId: string | null + resultQuery: string | null + selectedRepoId: string | null + value: string +}): BaseRefSearchResult[] { + const currentQuery = value.trim() + if (mode !== 'branches' && mode !== 'smart') { + return [] + } + if (!selectedRepoId || resultRepoId !== selectedRepoId || resultQuery !== currentQuery) { + return [] + } + return branches +} + +export function buildSmartWorkspaceSourceRows({ + branches, + githubItems, + gitlabAvailable, + gitlabItems, + linearAvailable, + linearIssues, + mode, + resultLimit, + value +}: { + branches: BaseRefSearchResult[] + githubItems: GitHubWorkItem[] + gitlabAvailable: boolean + gitlabItems: GitLabWorkItem[] + linearAvailable: boolean + linearIssues: LinearIssue[] + mode: SmartNameMode + resultLimit: number + value: string +}): SmartWorkspaceSourceRow[] { + const trimmed = value.trim() + const nextRows: SmartWorkspaceSourceRow[] = [] + if (trimmed && mode === 'smart') { + nextRows.push({ kind: 'use-name', value: `use-name-${trimmed}`, name: trimmed }) + } + if (mode === 'text') { + return nextRows + } + if (mode === 'smart' || mode === 'github') { + nextRows.push( + ...githubItems.map((item) => ({ + kind: 'github' as const, + value: `github-${item.type}-${item.number}`, + item + })) + ) + } + if (gitlabAvailable && (mode === 'smart' || mode === 'gitlab')) { + nextRows.push( + ...gitlabItems.map((item) => ({ + kind: 'gitlab' as const, + value: `gitlab-${item.type}-${item.number}`, + item + })) + ) + } + const shouldShowBranches = mode === 'branches' || (mode === 'smart' && trimmed.length > 0) + if (shouldShowBranches) { + const branchExactMatch = branches.some( + (branch) => branch.refName === trimmed || branch.localBranchName === trimmed + ) + if (trimmed && mode === 'branches' && !branchExactMatch) { + nextRows.push({ kind: 'create-branch', value: `create-branch-${trimmed}`, name: trimmed }) + } + nextRows.push( + ...branches.map((branch) => ({ + kind: 'branch' as const, + value: `branch-${branch.refName}`, + refName: branch.refName, + localBranchName: branch.localBranchName + })) + ) + } + if (linearAvailable && (mode === 'smart' || mode === 'linear')) { + nextRows.push( + ...linearIssues.map((issue) => ({ + kind: 'linear' as const, + value: `linear-${issue.id}`, + issue + })) + ) + } + return nextRows.slice(0, resultLimit + 1) +}