From adb251081fcf4d4071cff722e35ef673d36ca39d Mon Sep 17 00:00:00 2001 From: Chris Scott <99081550+chriswritescode-dev@users.noreply.github.com> Date: Sat, 24 Oct 2026 10:37:41 -0400 Subject: [PATCH] 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. --- frontend/src/api/opencode.test.ts | 31 ++++++++++++++++ frontend/src/api/opencode.ts | 13 ++++--- .../source-control/BranchesTab.test.tsx | 36 +++++++++++++++++-- .../components/source-control/BranchesTab.tsx | 3 +- frontend/src/hooks/useGit.test.tsx | 8 +++++ frontend/src/hooks/useGit.ts | 17 +++++---- frontend/src/hooks/useVcsInfo.ts | 4 +-- frontend/src/lib/queryInvalidation.ts | 31 ++++++++++++++++ 8 files changed, 128 insertions(+), 15 deletions(-) diff --git a/frontend/src/api/opencode.test.ts b/frontend/src/api/opencode.test.ts index 5ce3e3c5..a75180a5 100644 --- a/frontend/src/api/opencode.test.ts +++ b/frontend/src/api/opencode.test.ts @@ -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 })] diff --git a/frontend/src/api/opencode.ts b/frontend/src/api/opencode.ts index bbefa387..40bbabf9 100644 --- a/frontend/src/api/opencode.ts +++ b/frontend/src/api/opencode.ts @@ -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>['data'] diff --git a/frontend/src/components/source-control/BranchesTab.test.tsx b/frontend/src/components/source-control/BranchesTab.test.tsx index d1fa416e..971b1682 100644 --- a/frontend/src/components/source-control/BranchesTab.test.tsx +++ b/frontend/src/components/source-control/BranchesTab.test.tsx @@ -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(, { + wrapper: ({ children }) => {children}, + }) + + await user.click(await screen.findByRole('button', { name: /^feature/ })) + + await waitFor(() => expect(invalidateSpy).toHaveBeenCalledWith({ + queryKey: ['opencode', 'vcs', '/abs/repos/my-repo', 'info'], + exact: true, + })) + }) }) diff --git a/frontend/src/components/source-control/BranchesTab.tsx b/frontend/src/components/source-control/BranchesTab.tsx index 1a185357..73370345 100644 --- a/frontend/src/components/source-control/BranchesTab.tsx +++ b/frontend/src/components/source-control/BranchesTab.tsx @@ -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}`) }, diff --git a/frontend/src/hooks/useGit.test.tsx b/frontend/src/hooks/useGit.test.tsx index 7725e183..fa16da66 100644 --- a/frontend/src/hooks/useGit.test.tsx +++ b/frontend/src/hooks/useGit.test.tsx @@ -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') }) diff --git a/frontend/src/hooks/useGit.ts b/frontend/src/hooks/useGit.ts index 8f5e4987..cbd06981 100644 --- a/frontend/src/hooks/useGit.ts +++ b/frontend/src/hooks/useGit.ts @@ -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 { mutationFn: (repoId: number, variables: TVariables) => Promise @@ -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', id])?.fullPath) + }, successMessage: 'Branch renamed', }, ) diff --git a/frontend/src/hooks/useVcsInfo.ts b/frontend/src/hooks/useVcsInfo.ts index 8238e9df..b1d27ce7 100644 --- a/frontend/src/hooks/useVcsInfo.ts +++ b/frontend/src/hooks/useVcsInfo.ts @@ -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, diff --git a/frontend/src/lib/queryInvalidation.ts b/frontend/src/lib/queryInvalidation.ts index 501666c5..764bb323 100644 --- a/frontend/src/lib/queryInvalidation.ts +++ b/frontend/src/lib/queryInvalidation.ts @@ -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] }