mirror of
https://github.com/chriswritescode-dev/opencode-manager.git
synced 2026-12-05 20:34:18 +01:00
fix(frontend): resolve the deepest owning remote project and refresh VCS info after branch changes
findRemoteProjectForDirectory now returns the longest matching canonical path, so nested linked-server projects attribute sessions to the innermost project. Switching, creating and renaming a local branch invalidate that directory's VCS info query, so branch labels refresh immediately.
This commit is contained in:
1 parent
4b7652451b
commit
adb251081f
8 files changed
+128
-15
No files matched your search
@@ -851,6 +851,37 @@ describe('project helpers', () => {
|
||||
expect(findRemoteProjectForDirectory(projects, '/work/beta/packages/web')?.id).toBe('p2')
|
||||
})
|
||||
|
||||
it('picks the deepest project when one canonical directory contains another', () => {
|
||||
const projects = [
|
||||
project('p_parent', 'Repo', '/work/repo', { created: 1, updated: 2 }),
|
||||
project('p_child', 'App', '/work/repo/packages/app', { created: 1, updated: 3 }),
|
||||
]
|
||||
|
||||
expect(findRemoteProjectForDirectory(projects, '/work/repo')?.id).toBe('p_parent')
|
||||
expect(findRemoteProjectForDirectory(projects, '/work/repo/packages/app')?.id).toBe('p_child')
|
||||
expect(findRemoteProjectForDirectory(projects, '/work/repo/packages/app/src')?.id).toBe('p_child')
|
||||
})
|
||||
|
||||
it('credits a session in a nested project to the deepest project', () => {
|
||||
const projects = [
|
||||
project('p_parent', 'Repo', '/work/repo', { created: 1, updated: 20 }),
|
||||
project('p_child', 'App', '/work/repo/packages/app', { created: 1, updated: 10 }),
|
||||
]
|
||||
|
||||
const ranked = rankProjectsBySessionActivity(projects, [
|
||||
session('ses_nested', '/work/repo/packages/app/src', 400),
|
||||
])
|
||||
|
||||
expect(ranked.find((entry) => entry.project.id === 'p_child')?.activityAt).toBe(400)
|
||||
expect(ranked.find((entry) => entry.project.id === 'p_parent')?.activityAt).toBe(20)
|
||||
})
|
||||
|
||||
it('returns no project when no canonical directory contains the directory', () => {
|
||||
const projects = [project('p1', 'Alpha', '/work/alpha', { created: 1, updated: 2 })]
|
||||
|
||||
expect(findRemoteProjectForDirectory(projects, '/srv/elsewhere')).toBeUndefined()
|
||||
})
|
||||
|
||||
it('does not match a directory that only shares a prefix with a canonical directory', () => {
|
||||
const projects = [project('p1', 'Alpha', '/work/alpha', { created: 1, updated: 2 })]
|
||||
|
||||
|
||||
@@ -112,7 +112,7 @@ export function remoteProjectName(project: OpenCodeProject): string {
|
||||
|
||||
/**
|
||||
* Finds the project that owns a directory, matching its canonical directory and anything nested
|
||||
* inside it.
|
||||
* inside it. Nested projects share a canonical prefix, so the deepest match owns the directory.
|
||||
*
|
||||
* @param projects Projects of the server that owns the directory.
|
||||
* @param directory Directory whose owning project is resolved.
|
||||
@@ -122,9 +122,14 @@ export function findRemoteProjectForDirectory(
|
||||
projects: OpenCodeProject[],
|
||||
directory: string,
|
||||
): OpenCodeProject | undefined {
|
||||
return projects.find(
|
||||
(project) => directory === project.canonical || directory.startsWith(`${project.canonical}/`),
|
||||
)
|
||||
let owner: OpenCodeProject | undefined
|
||||
for (const project of projects) {
|
||||
if (directory !== project.canonical && !directory.startsWith(`${project.canonical}/`)) continue
|
||||
if (!owner || project.canonical.length > owner.canonical.length) {
|
||||
owner = project
|
||||
}
|
||||
}
|
||||
return owner
|
||||
}
|
||||
|
||||
export type VcsInfo = Awaited<ReturnType<OpenCodeApi['vcs']['get']>>['data']
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest'
|
||||
import { render, screen } from '@testing-library/react'
|
||||
import { render, screen, waitFor } from '@testing-library/react'
|
||||
import userEvent from '@testing-library/user-event'
|
||||
import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
|
||||
import { BranchesTab } from './BranchesTab'
|
||||
@@ -39,7 +39,8 @@ vi.mock('@/components/repo/CreateWorktreeDialog', () => ({
|
||||
CreateWorktreeDialog: () => null,
|
||||
}))
|
||||
|
||||
import { listBranches, getRepo } from '@/api/repos'
|
||||
import { listBranches, getRepo, switchBranch } from '@/api/repos'
|
||||
import { fetchGitStatus } from '@/api/git'
|
||||
|
||||
const createWrapper = () => {
|
||||
const queryClient = new QueryClient({
|
||||
@@ -89,4 +90,35 @@ describe('BranchesTab', () => {
|
||||
|
||||
expect(await screen.findByText('origin/feature')).toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('invalidates the vcs info of the switched repository', async () => {
|
||||
vi.mocked(switchBranch).mockResolvedValue({
|
||||
id: 1,
|
||||
fullPath: '/abs/repos/my-repo',
|
||||
currentBranch: 'feature',
|
||||
} as never)
|
||||
vi.mocked(fetchGitStatus).mockResolvedValue({
|
||||
branch: 'feature',
|
||||
ahead: 0,
|
||||
behind: 0,
|
||||
files: [],
|
||||
hasChanges: false,
|
||||
operation: null,
|
||||
})
|
||||
const queryClient = new QueryClient({
|
||||
defaultOptions: { queries: { retry: false }, mutations: { retry: false } },
|
||||
})
|
||||
const invalidateSpy = vi.spyOn(queryClient, 'invalidateQueries')
|
||||
const user = userEvent.setup()
|
||||
render(<BranchesTab repoId={1} currentBranch="main" />, {
|
||||
wrapper: ({ children }) => <QueryClientProvider client={queryClient}>{children}</QueryClientProvider>,
|
||||
})
|
||||
|
||||
await user.click(await screen.findByRole('button', { name: /^feature/ }))
|
||||
|
||||
await waitFor(() => expect(invalidateSpy).toHaveBeenCalledWith({
|
||||
queryKey: ['opencode', 'vcs', '/abs/repos/my-repo', 'info'],
|
||||
exact: true,
|
||||
}))
|
||||
})
|
||||
})
|
||||
@@ -14,7 +14,7 @@ import { useGit } from '@/hooks/useGit'
|
||||
import { GIT_UI_COLORS } from '@/lib/git-status-styles'
|
||||
import { CreateWorktreeDialog } from '@/components/repo/CreateWorktreeDialog'
|
||||
import { IntegrateBranchDialog } from '@/components/source-control/IntegrateBranchDialog'
|
||||
import { invalidateRepoGitCaches, setRepoGitStatusCaches } from '@/lib/queryInvalidation'
|
||||
import { invalidateRepoGitCaches, invalidateVcsInfoCache, setRepoGitStatusCaches } from '@/lib/queryInvalidation'
|
||||
|
||||
interface BranchesTabProps {
|
||||
repoId: number
|
||||
@@ -72,6 +72,7 @@ export function BranchesTab({ repoId, currentBranch }: BranchesTabProps) {
|
||||
queryClient.setQueryData(['repo', repoId], updatedRepo)
|
||||
setRepoGitStatusCaches(queryClient, repoId, status)
|
||||
invalidateRepoGitCaches(queryClient, repoId, { invalidateStatus: false })
|
||||
invalidateVcsInfoCache(queryClient, updatedRepo.fullPath)
|
||||
refetch()
|
||||
showToast.success(`Switched to branch: ${updatedRepo.currentBranch}`)
|
||||
},
|
||||
|
||||
@@ -66,6 +66,7 @@ vi.mock('@tanstack/react-query', async () => {
|
||||
invalidateQueries: (...args: unknown[]) => unknown
|
||||
setQueryData: (...args: unknown[]) => unknown
|
||||
setQueriesData: (...args: unknown[]) => unknown
|
||||
getQueryData: (...args: unknown[]) => unknown
|
||||
} | null
|
||||
return {
|
||||
invalidateQueries: (...args: unknown[]) => {
|
||||
@@ -80,6 +81,7 @@ vi.mock('@tanstack/react-query', async () => {
|
||||
mockSetQueriesData(...args)
|
||||
return real?.setQueriesData(...args)
|
||||
},
|
||||
getQueryData: (...args: unknown[]) => real?.getQueryData(...args),
|
||||
}
|
||||
})
|
||||
}
|
||||
@@ -335,6 +337,8 @@ describe('useGit', () => {
|
||||
|
||||
describe('renameBranch mutation', () => {
|
||||
it('calls correct API and updates the status cache on success', async () => {
|
||||
const realClient = mockRealQueryClient.current as QueryClient
|
||||
realClient.setQueryData(['repo', 1], { fullPath: '/abs/repos/my-repo' })
|
||||
const { result } = renderHook(() => useGit(1), { wrapper: createWrapper() })
|
||||
|
||||
await waitFor(() => {
|
||||
@@ -343,6 +347,10 @@ describe('useGit', () => {
|
||||
|
||||
expect(gitApi.gitRenameBranch).toHaveBeenCalledWith(1, { from: 'main', to: 'renamed' })
|
||||
expectTargetedStatusCacheUpdate()
|
||||
expect(mockInvalidateQueries).toHaveBeenCalledWith({
|
||||
queryKey: ['opencode', 'vcs', '/abs/repos/my-repo', 'info'],
|
||||
exact: true,
|
||||
})
|
||||
expect(toast.showToast.success).toHaveBeenCalledWith('Branch renamed')
|
||||
})
|
||||
|
||||
|
||||
@@ -3,9 +3,10 @@ import type { QueryClient } from '@tanstack/react-query'
|
||||
import { gitFetch, gitPull, gitPush, gitCommit, gitStageFiles, gitUnstageFiles, gitDiscardFiles, fetchGitLog, fetchGitDiff, gitReset, gitRenameBranch, gitDeleteBranch, gitStashPush, gitStashApply, gitStashDrop, gitContinueOperation, gitAbortOperation, gitGenerateCommitMessage, gitIntegrateBranch, getApiErrorMessage, fetchGitStatus } from '@/api/git'
|
||||
import { createBranch } from '@/api/repos'
|
||||
import type { DeleteBranchRequest, DeleteBranchResult, IntegrateBranchRequest, RenameBranchRequest, StashPushRequest } from '@opencode-manager/shared'
|
||||
import type { Repo } from '@/api/types'
|
||||
import type { GitStatusResponse } from '@/types/git'
|
||||
import { showToast } from '@/lib/toast'
|
||||
import { invalidateRepoGitCaches, setRepoGitStatusCaches } from '@/lib/queryInvalidation'
|
||||
import { invalidateRepoGitCaches, invalidateVcsInfoCache, setRepoGitStatusCaches } from '@/lib/queryInvalidation'
|
||||
|
||||
interface RepoGitMutationConfig<TData, TVariables> {
|
||||
mutationFn: (repoId: number, variables: TVariables) => Promise<TData>
|
||||
@@ -160,12 +161,13 @@ export function useGit(repoId: number | undefined, onError?: (error: unknown) =>
|
||||
const createBranchMutation = useMutation({
|
||||
mutationFn: async (branchName: string) => {
|
||||
if (!repoId) throw new Error('No repo ID')
|
||||
await createBranch(repoId, branchName)
|
||||
return fetchGitStatus(repoId)
|
||||
const createdRepo = await createBranch(repoId, branchName)
|
||||
return { createdRepo, status: await fetchGitStatus(repoId) }
|
||||
},
|
||||
onSuccess: (data) => {
|
||||
if (repoId) setRepoGitStatusCaches(queryClient, repoId, data)
|
||||
onSuccess: ({ createdRepo, status }) => {
|
||||
if (repoId) setRepoGitStatusCaches(queryClient, repoId, status)
|
||||
invalidateRepoGitCaches(queryClient, repoId, { invalidateStatus: false })
|
||||
invalidateVcsInfoCache(queryClient, createdRepo.fullPath)
|
||||
showToast.success('Branch created')
|
||||
},
|
||||
onError: handleError,
|
||||
@@ -191,7 +193,10 @@ export function useGit(repoId: number | undefined, onError?: (error: unknown) =>
|
||||
{
|
||||
mutationFn: gitRenameBranch,
|
||||
statusFromData: (data) => data,
|
||||
invalidate: (client, id) => invalidateRepoGitCaches(client, id, { invalidateStatus: false }),
|
||||
invalidate: (client, id) => {
|
||||
invalidateRepoGitCaches(client, id, { invalidateStatus: false })
|
||||
invalidateVcsInfoCache(client, client.getQueryData<Repo>(['repo', id])?.fullPath)
|
||||
},
|
||||
successMessage: 'Branch renamed',
|
||||
},
|
||||
)
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import { useQuery } from '@tanstack/react-query'
|
||||
import { getVcsInfo } from '@/api/opencode'
|
||||
import { serverScopedKey } from '@/lib/serverScope'
|
||||
import { vcsInfoQueryKey } from '@/lib/queryInvalidation'
|
||||
|
||||
export interface UseVcsInfoOptions {
|
||||
enabled?: boolean
|
||||
@@ -14,7 +14,7 @@ export function useVcsInfo(
|
||||
const { enabled = true } = options
|
||||
|
||||
return useQuery({
|
||||
queryKey: [...serverScopedKey(['opencode', 'vcs', directory ?? ''], serverId), 'info'],
|
||||
queryKey: vcsInfoQueryKey(directory, serverId),
|
||||
queryFn: () => getVcsInfo(directory ?? '', serverId),
|
||||
enabled: enabled && Boolean(directory),
|
||||
staleTime: 30_000,
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import type { QueryClient } from '@tanstack/react-query'
|
||||
import { LOCAL_OPENCODE_SERVER_ID } from '@opencode-manager/shared/schemas'
|
||||
import { serverScopedKey } from '@/lib/serverScope'
|
||||
import type { GitStatusResponse } from '@/types/git'
|
||||
|
||||
export function sessionTranscriptQueryKey(sessionID: string | null | undefined) {
|
||||
@@ -14,6 +15,36 @@ export function invalidateShellCaches(queryClient: QueryClient) {
|
||||
queryClient.invalidateQueries({ queryKey: ['opencode', 'shells'] })
|
||||
}
|
||||
|
||||
/**
|
||||
* Query key of the VCS info cached for one directory on one server.
|
||||
*
|
||||
* @param directory Directory the info describes; a missing directory keeps the placeholder key.
|
||||
* @param serverId Server that owns the directory; defaults to the local one.
|
||||
*/
|
||||
export function vcsInfoQueryKey(
|
||||
directory: string | null | undefined,
|
||||
serverId: string = LOCAL_OPENCODE_SERVER_ID,
|
||||
) {
|
||||
return [...serverScopedKey(['opencode', 'vcs', directory ?? ''], serverId), 'info']
|
||||
}
|
||||
|
||||
/**
|
||||
* Invalidates the VCS info of one directory so a branch change reaches every surface that shows the
|
||||
* branch, while the status and diff caches of the same directory stay untouched.
|
||||
*
|
||||
* @param queryClient Client that owns the cache.
|
||||
* @param directory Directory whose info is invalidated; a missing directory is ignored.
|
||||
* @param serverId Server that owns the directory; defaults to the local one.
|
||||
*/
|
||||
export function invalidateVcsInfoCache(
|
||||
queryClient: QueryClient,
|
||||
directory: string | null | undefined,
|
||||
serverId: string = LOCAL_OPENCODE_SERVER_ID,
|
||||
) {
|
||||
if (!directory) return
|
||||
queryClient.invalidateQueries({ queryKey: vcsInfoQueryKey(directory, serverId), exact: true })
|
||||
}
|
||||
|
||||
export function childSessionReconciliationQueryKey(sessionID: string | null | undefined) {
|
||||
return ['opencode', 'session-reconcile', sessionID]
|
||||
}
|
||||
|
||||
Reference in new issue
Block a user