From 570cc46e51f1117d0bac302c8fee2ee0983ec813 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Fri, 8 May 2026 19:16:22 -0700 Subject: [PATCH] Replace git react-query layer with vcsRefManager and source control acti - Migrate branch selector and git actions to useVcsRefs and new source control action hooks - Remove gitReactQuery and projectReactQuery modules in favor of sourceControlActions and vcsRefState - Add staleTimeMs to mobile vcs ref manager configuration --- apps/mobile/src/state/use-vcs-refs.ts | 8 +- .../BranchToolbarBranchSelector.tsx | 70 ++-- .../components/GitActionsControl.browser.tsx | 79 ++-- apps/web/src/components/GitActionsControl.tsx | 134 +++--- .../components/PullRequestThreadDialog.tsx | 76 ++-- .../runtime/service.savedEnvironments.test.ts | 6 - apps/web/src/environments/runtime/service.ts | 2 - apps/web/src/hooks/useThreadActions.ts | 7 +- apps/web/src/lib/gitReactQuery.test.ts | 130 ------ apps/web/src/lib/gitReactQuery.ts | 327 --------------- apps/web/src/lib/projectReactQuery.ts | 52 --- apps/web/src/lib/sourceControlActions.ts | 381 ++++++++++++++++++ apps/web/src/lib/vcsRefState.ts | 48 +++ .../client-runtime/src/vcsRefState.test.ts | 108 ++++- packages/client-runtime/src/vcsRefState.ts | 69 +++- 15 files changed, 770 insertions(+), 727 deletions(-) delete mode 100644 apps/web/src/lib/gitReactQuery.test.ts delete mode 100644 apps/web/src/lib/gitReactQuery.ts delete mode 100644 apps/web/src/lib/projectReactQuery.ts create mode 100644 apps/web/src/lib/sourceControlActions.ts create mode 100644 apps/web/src/lib/vcsRefState.ts diff --git a/apps/mobile/src/state/use-vcs-refs.ts b/apps/mobile/src/state/use-vcs-refs.ts index 8e9e4dac29..5067fc7fc4 100644 --- a/apps/mobile/src/state/use-vcs-refs.ts +++ b/apps/mobile/src/state/use-vcs-refs.ts @@ -16,6 +16,9 @@ import { subscribeEnvironmentConnections, } from "./environment-session-registry"; +const VCS_REF_LIST_LIMIT = 100; +const VCS_REF_STALE_TIME_MS = 5_000; + export const vcsRefManager = createVcsRefManager({ getRegistry: () => appAtomRegistry, getClient: (environmentId) => { @@ -23,7 +26,8 @@ export const vcsRefManager = createVcsRefManager({ return client ? client.git : null; }, subscribeClientChanges: subscribeEnvironmentConnections, - watchLimit: 100, + watchLimit: VCS_REF_LIST_LIMIT, + staleTimeMs: VCS_REF_STALE_TIME_MS, onBackgroundError: (error) => { console.warn("[vcs-refs] background refresh failed", error); }, @@ -39,7 +43,9 @@ export function useVcsRefs(target: VcsRefTarget): VcsRefState { [target.cwd, target.environmentId, target.query], ); const targetKey = getVcsRefTargetKey(stableTarget); + useEffect(() => vcsRefManager.watch(stableTarget), [stableTarget]); + const state = useAtomValue(targetKey !== null ? vcsRefStateAtom(targetKey) : EMPTY_VCS_REF_ATOM); return targetKey === null ? EMPTY_VCS_REF_STATE : state; } diff --git a/apps/web/src/components/BranchToolbarBranchSelector.tsx b/apps/web/src/components/BranchToolbarBranchSelector.tsx index 2e30edfc02..2e92519f21 100644 --- a/apps/web/src/components/BranchToolbarBranchSelector.tsx +++ b/apps/web/src/components/BranchToolbarBranchSelector.tsx @@ -1,6 +1,5 @@ import { scopeProjectRef, scopeThreadRef } from "@t3tools/client-runtime"; import type { EnvironmentId, VcsRef, ThreadId } from "@t3tools/contracts"; -import { useInfiniteQuery, useQueryClient } from "@tanstack/react-query"; import { LegendList, type LegendListRef } from "@legendapp/list/react"; import { ChevronDownIcon } from "lucide-react"; import { @@ -16,8 +15,8 @@ import { import { useComposerDraftStore, type DraftId } from "../composerDraftStore"; import { readEnvironmentApi } from "../environmentApi"; -import { gitBranchSearchInfiniteQueryOptions, gitQueryKeys } from "../lib/gitReactQuery"; import { useGitStatus } from "../lib/gitStatusState"; +import { useVcsRefs, vcsRefManager } from "../lib/vcsRefState"; import { newCommandId } from "../lib/utils"; import { cn } from "../lib/utils"; import { parsePullRequestReference } from "../pullRequestReference"; @@ -59,6 +58,8 @@ interface BranchToolbarBranchSelectorProps { onComposerFocusRequest?: () => void; } +const EMPTY_REFS: ReadonlyArray = []; + function toBranchActionErrorMessage(error: unknown): string { return error instanceof Error ? error.message : "An error occurred."; } @@ -196,7 +197,6 @@ export function BranchToolbarBranchSelector({ // --------------------------------------------------------------------------- // Git ref queries // --------------------------------------------------------------------------- - const queryClient = useQueryClient(); const [isBranchMenuOpen, setIsBranchMenuOpen] = useState(false); const [branchQuery, setBranchQuery] = useState(""); const deferredBranchQuery = useDeferredValue(branchQuery); @@ -204,31 +204,20 @@ export function BranchToolbarBranchSelector({ const branchStatusQuery = useGitStatus({ environmentId, cwd: branchCwd }); const trimmedBranchQuery = branchQuery.trim(); const deferredTrimmedBranchQuery = deferredBranchQuery.trim(); - - useEffect(() => { - if (!branchCwd) return; - void queryClient.prefetchInfiniteQuery( - gitBranchSearchInfiniteQueryOptions({ environmentId, cwd: branchCwd, query: "" }), - ); - }, [branchCwd, environmentId, queryClient]); - - const { - data: branchesSearchData, - fetchNextPage, - hasNextPage, - isFetchingNextPage, - isPending: isBranchesSearchPending, - } = useInfiniteQuery( - gitBranchSearchInfiniteQueryOptions({ + const branchRefTarget = useMemo( + () => ({ environmentId, cwd: branchCwd, query: deferredTrimmedBranchQuery, }), + [branchCwd, deferredTrimmedBranchQuery, environmentId], ); - const refs = useMemo( - () => branchesSearchData?.pages.flatMap((page) => page.refs) ?? [], - [branchesSearchData?.pages], - ); + const branchRefState = useVcsRefs(branchRefTarget); + const refs = branchRefState.data?.refs ?? EMPTY_REFS; + const hasNextPage = + branchRefState.data?.nextCursor !== null && branchRefState.data?.nextCursor !== undefined; + const [isFetchingNextPage, setIsFetchingNextPage] = useState(false); + const isInitialBranchesLoadPending = branchRefState.isPending && branchRefState.data === null; const currentGitBranch = branchStatusQuery.data?.refName ?? refs.find((refName) => refName.current)?.name ?? null; const sourceControlPresentation = useMemo( @@ -293,8 +282,8 @@ export function BranchToolbarBranchSelector({ ); const [isBranchActionPending, startBranchActionTransition] = useTransition(); const shouldVirtualizeBranchList = filteredBranchPickerItems.length > 40; - const totalBranchCount = branchesSearchData?.pages[0]?.totalCount ?? 0; - const branchStatusText = isBranchesSearchPending + const totalBranchCount = branchRefState.data?.totalCount ?? 0; + const branchStatusText = isInitialBranchesLoadPending ? "Loading refs..." : isFetchingNextPage ? "Loading more refs..." @@ -308,8 +297,8 @@ export function BranchToolbarBranchSelector({ const runBranchAction = (action: () => Promise) => { startBranchActionTransition(async () => { await action().catch(() => undefined); - await queryClient - .invalidateQueries({ queryKey: gitQueryKeys.refs(environmentId, branchCwd) }) + await vcsRefManager + .load(branchRefTarget, undefined, { limit: 100, preserveLoadedRefs: true }) .catch(() => undefined); }); }; @@ -425,14 +414,25 @@ export function BranchToolbarBranchSelector({ setBranchQuery(""); return; } - void queryClient.invalidateQueries({ - queryKey: gitQueryKeys.refs(environmentId, branchCwd), - }); + void vcsRefManager + .load(branchRefTarget, undefined, { limit: 100, preserveLoadedRefs: true }) + .catch(() => undefined); }, - [branchCwd, environmentId, queryClient], + [branchRefTarget], ); const branchListScrollElementRef = useRef(null); + const fetchNextBranchPage = useCallback(() => { + if (!hasNextPage || isFetchingNextPage) { + return; + } + + setIsFetchingNextPage(true); + void vcsRefManager + .loadNext(branchRefTarget, undefined, { limit: 100 }) + .catch(() => undefined) + .finally(() => setIsFetchingNextPage(false)); + }, [branchRefTarget, hasNextPage, isFetchingNextPage]); const maybeFetchNextBranchPage = useCallback(() => { if (!isBranchMenuOpen || !hasNextPage || isFetchingNextPage) { return; @@ -449,8 +449,8 @@ export function BranchToolbarBranchSelector({ return; } - void fetchNextPage().catch(() => undefined); - }, [fetchNextPage, hasNextPage, isBranchMenuOpen, isFetchingNextPage]); + fetchNextBranchPage(); + }, [fetchNextBranchPage, hasNextPage, isBranchMenuOpen, isFetchingNextPage]); const branchListRef = useRef(null); const setBranchListRef = useCallback((element: HTMLDivElement | null) => { branchListScrollElementRef.current = (element?.parentElement as HTMLDivElement | null) ?? null; @@ -592,7 +592,7 @@ export function BranchToolbarBranchSelector({ } className={cn("min-w-0 text-muted-foreground/70 hover:text-foreground/80", className)} - disabled={(isBranchesSearchPending && refs.length === 0) || isBranchActionPending} + disabled={isInitialBranchesLoadPending || isBranchActionPending} > {triggerLabel} @@ -622,7 +622,7 @@ export function BranchToolbarBranchSelector({ drawDistance={336} onEndReached={() => { if (hasNextPage && !isFetchingNextPage) { - void fetchNextPage().catch(() => undefined); + fetchNextBranchPage(); } }} style={{ maxHeight: "14rem" }} diff --git a/apps/web/src/components/GitActionsControl.browser.tsx b/apps/web/src/components/GitActionsControl.browser.tsx index a2a801d54a..1338b0a755 100644 --- a/apps/web/src/components/GitActionsControl.browser.tsx +++ b/apps/web/src/components/GitActionsControl.browser.tsx @@ -26,9 +26,9 @@ const { activeRunStackedActionDeferredRef, activeDraftThreadRef, hasServerThreadRef, - invalidateGitQueriesSpy, + invalidateSourceControlStateSpy, refreshGitStatusSpy, - runStackedActionMutateAsyncSpy, + runStackedActionSpy, setDraftThreadContextSpy, setThreadBranchSpy, toastAddSpy, @@ -39,9 +39,9 @@ const { activeRunStackedActionDeferredRef: { current: createDeferredPromise() }, activeDraftThreadRef: { current: null as unknown }, hasServerThreadRef: { current: true }, - invalidateGitQueriesSpy: vi.fn(() => Promise.resolve()), + invalidateSourceControlStateSpy: vi.fn(() => Promise.resolve()), refreshGitStatusSpy: vi.fn(() => Promise.resolve(null)), - runStackedActionMutateAsyncSpy: vi.fn(() => activeRunStackedActionDeferredRef.current.promise), + runStackedActionSpy: vi.fn(() => activeRunStackedActionDeferredRef.current.promise), setDraftThreadContextSpy: vi.fn(), setThreadBranchSpy: vi.fn(), toastAddSpy: vi.fn(() => "toast-1"), @@ -50,39 +50,6 @@ const { toastUpdateSpy: vi.fn(), })); -vi.mock("@tanstack/react-query", async () => { - const actual = - await vi.importActual("@tanstack/react-query"); - - return { - ...actual, - useIsMutating: vi.fn(() => 0), - useMutation: vi.fn((options: { __kind?: string }) => { - if (options.__kind === "run-stacked-action") { - return { - mutateAsync: runStackedActionMutateAsyncSpy, - isPending: false, - }; - } - - if (options.__kind === "pull") { - return { - mutateAsync: vi.fn(), - isPending: false, - }; - } - - return { - mutate: vi.fn(), - mutateAsync: vi.fn(), - isPending: false, - }; - }), - useQuery: vi.fn(() => ({ data: null, error: null })), - useQueryClient: vi.fn(() => ({})), - }; -}); - vi.mock("~/components/ui/toast", () => ({ toastManager: { add: toastAddSpy, @@ -97,17 +64,33 @@ vi.mock("~/editorPreferences", () => ({ openInPreferredEditor: vi.fn(), })); -vi.mock("~/lib/gitReactQuery", () => ({ - gitInitMutationOptions: vi.fn(() => ({ __kind: "init" })), - gitMutationKeys: { - publishRepository: vi.fn(() => ["publish-repository"]), - pull: vi.fn(() => ["pull"]), - runStackedAction: vi.fn(() => ["run-stacked-action"]), - }, - gitPullMutationOptions: vi.fn(() => ({ __kind: "pull" })), - gitRunStackedActionMutationOptions: vi.fn(() => ({ __kind: "run-stacked-action" })), - invalidateGitQueries: invalidateGitQueriesSpy, - sourceControlPublishRepositoryMutationOptions: vi.fn(() => ({ __kind: "publish-repository" })), +vi.mock("~/lib/sourceControlActions", () => ({ + invalidateSourceControlState: invalidateSourceControlStateSpy, + useGitStackedAction: vi.fn(() => ({ + error: null, + isPending: false, + resetError: vi.fn(), + run: runStackedActionSpy, + })), + useSourceControlActionRunning: vi.fn(() => false), + useSourceControlPublishRepositoryAction: vi.fn(() => ({ + error: null, + isPending: false, + resetError: vi.fn(), + run: vi.fn(), + })), + useVcsInitAction: vi.fn(() => ({ + error: null, + isPending: false, + resetError: vi.fn(), + run: vi.fn(), + })), + useVcsPullAction: vi.fn(() => ({ + error: null, + isPending: false, + resetError: vi.fn(), + run: vi.fn(), + })), })); vi.mock("~/lib/gitStatusState", () => ({ diff --git a/apps/web/src/components/GitActionsControl.tsx b/apps/web/src/components/GitActionsControl.tsx index 341aaed9f1..61835e57df 100644 --- a/apps/web/src/components/GitActionsControl.tsx +++ b/apps/web/src/components/GitActionsControl.tsx @@ -10,7 +10,6 @@ import type { SourceControlRepositoryVisibility, VcsStatusResult, } from "@t3tools/contracts"; -import { useIsMutating, useMutation, useQueryClient } from "@tanstack/react-query"; import { useNavigate } from "@tanstack/react-router"; import * as Option from "effect/Option"; import { useCallback, useEffect, useEffectEvent, useMemo, useRef, useState } from "react"; @@ -65,12 +64,12 @@ import { stackedThreadToast, toastManager, type ThreadToastData } from "~/compon import { Tooltip, TooltipPopup, TooltipTrigger } from "~/components/ui/tooltip"; import { openInPreferredEditor } from "~/editorPreferences"; import { - gitInitMutationOptions, - gitMutationKeys, - gitPullMutationOptions, - gitRunStackedActionMutationOptions, - sourceControlPublishRepositoryMutationOptions, -} from "~/lib/gitReactQuery"; + useGitStackedAction, + useSourceControlActionRunning, + useSourceControlPublishRepositoryAction, + useVcsInitAction, + useVcsPullAction, +} from "~/lib/sourceControlActions"; import { refreshGitStatus, useGitStatus } from "~/lib/gitStatusState"; import { useSourceControlDiscovery } from "~/lib/sourceControlDiscoveryState"; import { newCommandId, randomUUID } from "~/lib/utils"; @@ -128,6 +127,7 @@ interface RunGitActionWithToastInput { } const GIT_STATUS_WINDOW_REFRESH_DEBOUNCE_MS = 250; +const RUNNING_SOURCE_CONTROL_ACTIONS = ["runStackedAction", "pull", "publishRepository"] as const; const PUBLISH_PROVIDER_OPTIONS = [ { @@ -346,7 +346,6 @@ interface PublishRepositoryDialogProps { } function PublishRepositoryDialog(props: PublishRepositoryDialogProps) { - const queryClient = useQueryClient(); const navigate = useNavigate(); const sourceControlDiscovery = useSourceControlDiscovery(); const [publishProvider, setPublishProvider] = useState("github"); @@ -362,13 +361,14 @@ function PublishRepositoryDialog(props: PublishRepositoryDialogProps) { null, ); const [hasUserEditedPublishRepository, setHasUserEditedPublishRepository] = useState(false); - const publishRepositoryMutation = useMutation( - sourceControlPublishRepositoryMutationOptions({ + const sourceControlScope = useMemo( + () => ({ environmentId: props.environmentId, cwd: props.gitCwd, - queryClient, }), + [props.environmentId, props.gitCwd], ); + const publishRepositoryAction = useSourceControlPublishRepositoryAction(sourceControlScope); const publishAccountByProvider = useMemo(() => { const accounts: Record = { github: null, @@ -435,13 +435,13 @@ function PublishRepositoryDialog(props: PublishRepositoryDialogProps) { const canSubmitPublishRepository = useMemo(() => { if (!selectedPublishProviderReadiness.ready) return false; - if (publishRepositoryMutation.isPending) return false; + if (publishRepositoryAction.isPending) return false; const repositoryParts = publishRepository.trim().split("/"); const owner = repositoryParts[0]?.trim() ?? ""; const rest = repositoryParts.slice(1); const name = rest.join("/").trim(); return owner.length > 0 && name.length > 0; - }, [publishRepository, publishRepositoryMutation.isPending, selectedPublishProviderReadiness]); + }, [publishRepository, publishRepositoryAction.isPending, selectedPublishProviderReadiness]); useEffect(() => { if (!props.open) { @@ -465,8 +465,8 @@ function PublishRepositoryDialog(props: PublishRepositoryDialogProps) { setPublishError(null); - void publishRepositoryMutation - .mutateAsync({ + void publishRepositoryAction + .run({ provider: publishProvider, repository: publishRepository.trim(), visibility: publishVisibility, @@ -493,7 +493,7 @@ function PublishRepositoryDialog(props: PublishRepositoryDialogProps) { publishProvider, publishRemoteName, publishRepository, - publishRepositoryMutation, + publishRepositoryAction, publishVisibility, ]); @@ -689,7 +689,7 @@ function PublishRepositoryDialog(props: PublishRepositoryDialogProps) { } }} placeholder={publishPathPlaceholder} - disabled={publishRepositoryMutation.isPending} + disabled={publishRepositoryAction.isPending} className="w-full bg-transparent px-3 py-2 font-mono text-sm placeholder:text-muted-foreground/60 focus:outline-none" /> @@ -708,7 +708,7 @@ function PublishRepositoryDialog(props: PublishRepositoryDialogProps) { setPublishVisibility(value as SourceControlRepositoryVisibility) } aria-labelledby="publish-visibility-cards-label" - disabled={publishRepositoryMutation.isPending} + disabled={publishRepositoryAction.isPending} className="grid grid-cols-2 gap-2.5" > {[ @@ -780,7 +780,7 @@ function PublishRepositoryDialog(props: PublishRepositoryDialogProps) { value={publishRemoteName} onChange={(event) => setPublishRemoteName(event.target.value)} placeholder="origin" - disabled={publishRepositoryMutation.isPending} + disabled={publishRepositoryAction.isPending} />
@@ -796,7 +796,7 @@ function PublishRepositoryDialog(props: PublishRepositoryDialogProps) { setPublishProtocol(value as SourceControlCloneProtocol) } aria-labelledby="publish-protocol-label" - disabled={publishRepositoryMutation.isPending} + disabled={publishRepositoryAction.isPending} className="grid grid-cols-2 gap-2" > {(["ssh", "https"] as const).map((value) => { @@ -823,7 +823,7 @@ function PublishRepositoryDialog(props: PublishRepositoryDialogProps) { ) : null}
- {publishRepositoryMutation.isPending ? ( + {publishRepositoryAction.isPending ? (
) : null} - {publishError && !publishRepositoryMutation.isPending ? ( + {publishError && !publishRepositoryAction.isPending ? (
{ if (publishWizardStep === 0) { handleOpenChange(false); @@ -926,7 +926,7 @@ function PublishRepositoryDialog(props: PublishRepositoryDialogProps) { disabled={!canSubmitPublishRepository} onClick={submitPublishRepository} > - {publishRepositoryMutation.isPending ? ( + {publishRepositoryAction.isPending ? ( <> Publishing... @@ -969,7 +969,6 @@ export default function GitActionsControl({ ); const setDraftThreadContext = useComposerDraftStore((store) => store.setDraftThreadContext); const setThreadBranch = useStore((store) => store.setThreadBranch); - const queryClient = useQueryClient(); const [isCommitDialogOpen, setIsCommitDialogOpen] = useState(false); const [dialogCommitMessage, setDialogCommitMessage] = useState(""); const [excludedFiles, setExcludedFiles] = useState>(new Set()); @@ -978,6 +977,10 @@ export default function GitActionsControl({ const [pendingDefaultBranchAction, setPendingDefaultBranchAction] = useState(null); const activeGitActionProgressRef = useRef(null); + const sourceControlScope = useMemo( + () => ({ environmentId: activeEnvironmentId, cwd: gitCwd }), + [activeEnvironmentId, gitCwd], + ); let runGitActionWithToast: (input: RunGitActionWithToastInput) => Promise; const updateActiveProgressToast = useCallback(() => { @@ -1074,32 +1077,13 @@ export default function GitActionsControl({ const allSelected = excludedFiles.size === 0; const noneSelected = selectedFiles.length === 0; - const initMutation = useMutation( - gitInitMutationOptions({ environmentId: activeEnvironmentId, cwd: gitCwd, queryClient }), + const initAction = useVcsInitAction(sourceControlScope); + const runImmediateGitAction = useGitStackedAction(sourceControlScope); + const pullAction = useVcsPullAction(sourceControlScope); + const isGitActionRunning = useSourceControlActionRunning( + sourceControlScope, + RUNNING_SOURCE_CONTROL_ACTIONS, ); - - const runImmediateGitActionMutation = useMutation( - gitRunStackedActionMutationOptions({ - environmentId: activeEnvironmentId, - cwd: gitCwd, - queryClient, - }), - ); - const pullMutation = useMutation( - gitPullMutationOptions({ environmentId: activeEnvironmentId, cwd: gitCwd, queryClient }), - ); - - const isRunStackedActionRunning = - useIsMutating({ - mutationKey: gitMutationKeys.runStackedAction(activeEnvironmentId, gitCwd), - }) > 0; - const isPullRunning = - useIsMutating({ mutationKey: gitMutationKeys.pull(activeEnvironmentId, gitCwd) }) > 0; - const isPublishRunning = - useIsMutating({ - mutationKey: gitMutationKeys.publishRepository(activeEnvironmentId, gitCwd), - }) > 0; - const isGitActionRunning = isRunStackedActionRunning || isPullRunning || isPublishRunning; const isSelectingWorktreeBase = !activeServerThread && activeDraftThread?.envMode === "worktree" && @@ -1376,7 +1360,7 @@ export default function GitActionsControl({ updateActiveProgressToast(); }; - const promise = runImmediateGitActionMutation.mutateAsync({ + const promise = runImmediateGitAction.run({ actionId, action, ...(commitMessage ? { commitMessage } : {}), @@ -1516,26 +1500,26 @@ export default function GitActionsControl({ return; } if (quickAction.kind === "run_pull") { - const promise = pullMutation.mutateAsync(); - void toastManager.promise< - Awaited>, - ThreadToastData - >(promise, { - loading: { title: "Pulling...", data: threadToastData }, - success: (result) => ({ - title: result.status === "pulled" ? "Pulled" : "Already up to date", - description: - result.status === "pulled" - ? `Updated ${result.refName} from ${result.upstreamRef ?? "upstream"}` - : `${result.refName} is already synchronized.`, - data: threadToastData, - }), - error: (err) => ({ - title: "Pull failed", - description: err instanceof Error ? err.message : "An error occurred.", - data: threadToastData, - }), - }); + const promise = pullAction.run(); + void toastManager.promise>, ThreadToastData>( + promise, + { + loading: { title: "Pulling...", data: threadToastData }, + success: (result) => ({ + title: result.status === "pulled" ? "Pulled" : "Already up to date", + description: + result.status === "pulled" + ? `Updated ${result.refName} from ${result.upstreamRef ?? "upstream"}` + : `${result.refName} is already synchronized.`, + data: threadToastData, + }), + error: (err) => ({ + title: "Pull failed", + description: err instanceof Error ? err.message : "An error occurred.", + data: threadToastData, + }), + }, + ); void promise.catch(() => undefined); return; } @@ -1622,10 +1606,12 @@ export default function GitActionsControl({ ) : ( diff --git a/apps/web/src/components/PullRequestThreadDialog.tsx b/apps/web/src/components/PullRequestThreadDialog.tsx index 7c241afded..998703a975 100644 --- a/apps/web/src/components/PullRequestThreadDialog.tsx +++ b/apps/web/src/components/PullRequestThreadDialog.tsx @@ -1,12 +1,12 @@ -import type { EnvironmentId, GitResolvePullRequestResult, ThreadId } from "@t3tools/contracts"; -import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query"; +import type { EnvironmentId, ThreadId } from "@t3tools/contracts"; import { useDebouncedValue } from "@tanstack/react-pacer"; import { useCallback, useEffect, useMemo, useRef, useState } from "react"; import { - gitPreparePullRequestThreadMutationOptions, - gitResolvePullRequestQueryOptions, -} from "~/lib/gitReactQuery"; + readCachedPullRequestResolution, + usePreparePullRequestThreadAction, + usePullRequestResolution, +} from "~/lib/sourceControlActions"; import { useGitStatus } from "~/lib/gitStatusState"; import { cn } from "~/lib/utils"; import { parsePullRequestReference } from "~/pullRequestReference"; @@ -43,7 +43,6 @@ export function PullRequestThreadDialog({ onOpenChange, onPrepared, }: PullRequestThreadDialogProps) { - const queryClient = useQueryClient(); const referenceInputRef = useRef(null); const [reference, setReference] = useState(initialReference ?? ""); const [referenceDirty, setReferenceDirty] = useState(false); @@ -81,33 +80,30 @@ export function PullRequestThreadDialog({ const parsedReference = parsePullRequestReference(reference); const parsedDebouncedReference = parsePullRequestReference(debouncedReference); - const resolvePullRequestQuery = useQuery( - gitResolvePullRequestQueryOptions({ + const sourceControlScope = useMemo( + () => ({ environmentId, cwd, - reference: open ? parsedDebouncedReference : null, }), + [cwd, environmentId], ); + const pullRequestResolution = usePullRequestResolution({ + ...sourceControlScope, + reference: open ? parsedDebouncedReference : null, + }); const cachedPullRequest = useMemo(() => { - if (!cwd || !parsedReference) { - return null; - } - const cached = queryClient.getQueryData([ - "git", - "pull-request", - environmentId, - cwd, - parsedReference, - ]); - return cached?.pullRequest ?? null; - }, [cwd, environmentId, parsedReference, queryClient]); - const preparePullRequestThreadMutation = useMutation( - gitPreparePullRequestThreadMutationOptions({ environmentId, cwd, queryClient }), - ); + return ( + readCachedPullRequestResolution({ + ...sourceControlScope, + reference: parsedReference, + })?.pullRequest ?? null + ); + }, [parsedReference, sourceControlScope]); + const preparePullRequestThreadAction = usePreparePullRequestThreadAction(sourceControlScope); const liveResolvedPullRequest = parsedReference !== null && parsedReference === parsedDebouncedReference - ? (resolvePullRequestQuery.data?.pullRequest ?? null) + ? (pullRequestResolution.data?.pullRequest ?? null) : null; const resolvedPullRequest = liveResolvedPullRequest ?? cachedPullRequest; const isResolving = @@ -116,8 +112,8 @@ export function PullRequestThreadDialog({ resolvedPullRequest === null && (referenceDebouncer.state.isPending || parsedReference !== parsedDebouncedReference || - resolvePullRequestQuery.isPending || - resolvePullRequestQuery.isFetching); + pullRequestResolution.isPending || + pullRequestResolution.isFetching); const statusTone = useMemo(() => { switch (resolvedPullRequest?.state) { case "merged": @@ -142,7 +138,7 @@ export function PullRequestThreadDialog({ } setPreparingMode(mode); try { - const result = await preparePullRequestThreadMutation.mutateAsync({ + const result = await preparePullRequestThreadAction.run({ reference: parsedReference, mode, ...(mode === "worktree" ? { threadId } : {}), @@ -161,7 +157,7 @@ export function PullRequestThreadDialog({ onOpenChange, onPrepared, parsedReference, - preparePullRequestThreadMutation, + preparePullRequestThreadAction, resolvedPullRequest, threadId, ], @@ -176,13 +172,13 @@ export function PullRequestThreadDialog({ : null; const errorMessage = validationMessage ?? - (resolvedPullRequest === null && resolvePullRequestQuery.isError - ? resolvePullRequestQuery.error instanceof Error - ? resolvePullRequestQuery.error.message + (resolvedPullRequest === null && pullRequestResolution.error + ? pullRequestResolution.error instanceof Error + ? pullRequestResolution.error.message : `Failed to resolve ${terminology.singular}.` - : preparePullRequestThreadMutation.error instanceof Error - ? preparePullRequestThreadMutation.error.message - : preparePullRequestThreadMutation.error + : preparePullRequestThreadAction.error instanceof Error + ? preparePullRequestThreadAction.error.message + : preparePullRequestThreadAction.error ? `Failed to prepare ${terminology.singular} thread.` : null); @@ -190,7 +186,7 @@ export function PullRequestThreadDialog({ { - if (!preparePullRequestThreadMutation.isPending) { + if (!preparePullRequestThreadAction.isPending) { onOpenChange(nextOpen); } }} @@ -224,7 +220,7 @@ export function PullRequestThreadDialog({ return; } event.preventDefault(); - if (!isResolving && !preparePullRequestThreadMutation.isPending) { + if (!isResolving && !preparePullRequestThreadAction.isPending) { void handleConfirm("local"); } }} @@ -263,7 +259,7 @@ export function PullRequestThreadDialog({ variant="outline" size="sm" onClick={() => onOpenChange(false)} - disabled={preparePullRequestThreadMutation.isPending} + disabled={preparePullRequestThreadAction.isPending} > Cancel @@ -278,7 +274,7 @@ export function PullRequestThreadDialog({ !cwd || !resolvedPullRequest || isResolving || - preparePullRequestThreadMutation.isPending + preparePullRequestThreadAction.isPending } > {preparingMode === "local" ? "Preparing local..." : "Local"} @@ -293,7 +289,7 @@ export function PullRequestThreadDialog({ !cwd || !resolvedPullRequest || isResolving || - preparePullRequestThreadMutation.isPending + preparePullRequestThreadAction.isPending } > {preparingMode === "worktree" ? "Preparing worktree..." : "Worktree"} diff --git a/apps/web/src/environments/runtime/service.savedEnvironments.test.ts b/apps/web/src/environments/runtime/service.savedEnvironments.test.ts index 7f5b5baa49..78b4e88ced 100644 --- a/apps/web/src/environments/runtime/service.savedEnvironments.test.ts +++ b/apps/web/src/environments/runtime/service.savedEnvironments.test.ts @@ -108,12 +108,6 @@ vi.mock("~/orchestrationEventEffects", () => ({ })), })); -vi.mock("~/lib/projectReactQuery", () => ({ - projectQueryKeys: { - all: ["projects"], - }, -})); - vi.mock("~/lib/providerReactQuery", () => ({ providerQueryKeys: { all: ["providers"], diff --git a/apps/web/src/environments/runtime/service.ts b/apps/web/src/environments/runtime/service.ts index b36c572a74..b1485bf32d 100644 --- a/apps/web/src/environments/runtime/service.ts +++ b/apps/web/src/environments/runtime/service.ts @@ -29,7 +29,6 @@ import { import { ensureLocalApi } from "~/localApi"; import { collectActiveTerminalUiThreadKeys } from "~/lib/terminalUiStateCleanup"; import { deriveOrchestrationBatchEffects } from "~/orchestrationEventEffects"; -import { projectQueryKeys } from "~/lib/projectReactQuery"; import { providerQueryKeys } from "~/lib/providerReactQuery"; import { getPrimaryKnownEnvironment } from "../primary"; import { @@ -1763,7 +1762,6 @@ export function startEnvironmentConnectionService(queryClient: QueryClient): () } needsProviderInvalidation = false; void queryClient.invalidateQueries({ queryKey: providerQueryKeys.all }); - void queryClient.invalidateQueries({ queryKey: projectQueryKeys.all }); }, { wait: 100, diff --git a/apps/web/src/hooks/useThreadActions.ts b/apps/web/src/hooks/useThreadActions.ts index 9fa3dccdc5..7325a96913 100644 --- a/apps/web/src/hooks/useThreadActions.ts +++ b/apps/web/src/hooks/useThreadActions.ts @@ -1,6 +1,5 @@ import { parseScopedThreadKey, scopeProjectRef, scopeThreadRef } from "@t3tools/client-runtime"; import { type ScopedThreadRef, ThreadId } from "@t3tools/contracts"; -import { useQueryClient } from "@tanstack/react-query"; import { useRouter } from "@tanstack/react-router"; import { useCallback, useRef } from "react"; @@ -8,7 +7,7 @@ import { getFallbackThreadIdAfterDelete } from "../components/Sidebar.logic"; import { useComposerDraftStore } from "../composerDraftStore"; import { useNewThreadHandler } from "./useHandleNewThread"; import { ensureEnvironmentApi, readEnvironmentApi } from "../environmentApi"; -import { invalidateGitQueries } from "../lib/gitReactQuery"; +import { invalidateSourceControlState } from "../lib/sourceControlActions"; import { refreshArchivedThreadsForEnvironment } from "../lib/archivedThreadsState"; import { newCommandId } from "../lib/utils"; import { readLocalApi } from "../localApi"; @@ -40,7 +39,6 @@ export function useThreadActions() { // sidebar row via archiveThread → attemptArchiveThread. const handleNewThreadRef = useRef(handleNewThread); handleNewThreadRef.current = handleNewThread; - const queryClient = useQueryClient(); const resolveThreadTarget = useCallback((target: ScopedThreadRef) => { const state = useStore.getState(); @@ -229,7 +227,7 @@ export function useThreadActions() { path: orphanedWorktreePath, force: true, }); - await invalidateGitQueries(queryClient, { + await invalidateSourceControlState({ environmentId: threadRef.environmentId, }); } catch (error) { @@ -255,7 +253,6 @@ export function useThreadActions() { clearTerminalUiState, getCurrentRouteThreadRef, router, - queryClient, resolveThreadTarget, sidebarThreadSortOrder, ], diff --git a/apps/web/src/lib/gitReactQuery.test.ts b/apps/web/src/lib/gitReactQuery.test.ts deleted file mode 100644 index e6a5d8cba1..0000000000 --- a/apps/web/src/lib/gitReactQuery.test.ts +++ /dev/null @@ -1,130 +0,0 @@ -import { QueryClient } from "@tanstack/react-query"; -import { describe, expect, it, vi } from "vitest"; - -vi.mock("../environmentApi", () => ({ - ensureEnvironmentApi: vi.fn(), -})); - -import type { InfiniteData } from "@tanstack/react-query"; -import { EnvironmentId, type VcsListRefsResult } from "@t3tools/contracts"; - -import { - gitBranchSearchInfiniteQueryOptions, - gitMutationKeys, - gitPreparePullRequestThreadMutationOptions, - gitPullMutationOptions, - gitRunStackedActionMutationOptions, - invalidateGitQueries, -} from "./gitReactQuery"; - -const BRANCH_QUERY_RESULT: VcsListRefsResult = { - refs: [], - isRepo: true, - hasPrimaryRemote: true, - nextCursor: null, - totalCount: 0, -}; - -const BRANCH_SEARCH_RESULT: InfiniteData = { - pages: [BRANCH_QUERY_RESULT], - pageParams: [0], -}; -const ENVIRONMENT_A = EnvironmentId.make("environment-a"); -const ENVIRONMENT_B = EnvironmentId.make("environment-b"); - -describe("gitMutationKeys", () => { - it("scopes stacked action keys by cwd", () => { - expect(gitMutationKeys.runStackedAction(ENVIRONMENT_A, "/repo/a")).not.toEqual( - gitMutationKeys.runStackedAction(ENVIRONMENT_A, "/repo/b"), - ); - }); - - it("scopes pull keys by cwd", () => { - expect(gitMutationKeys.pull(ENVIRONMENT_A, "/repo/a")).not.toEqual( - gitMutationKeys.pull(ENVIRONMENT_A, "/repo/b"), - ); - }); - - it("scopes pull request thread preparation keys by cwd", () => { - expect(gitMutationKeys.preparePullRequestThread(ENVIRONMENT_A, "/repo/a")).not.toEqual( - gitMutationKeys.preparePullRequestThread(ENVIRONMENT_A, "/repo/b"), - ); - }); -}); - -describe("git mutation options", () => { - const queryClient = new QueryClient(); - - it("attaches cwd-scoped mutation key for runStackedAction", () => { - const options = gitRunStackedActionMutationOptions({ - environmentId: ENVIRONMENT_A, - cwd: "/repo/a", - queryClient, - }); - expect(options.mutationKey).toEqual(gitMutationKeys.runStackedAction(ENVIRONMENT_A, "/repo/a")); - }); - - it("attaches cwd-scoped mutation key for pull", () => { - const options = gitPullMutationOptions({ - environmentId: ENVIRONMENT_A, - cwd: "/repo/a", - queryClient, - }); - expect(options.mutationKey).toEqual(gitMutationKeys.pull(ENVIRONMENT_A, "/repo/a")); - }); - - it("attaches cwd-scoped mutation key for preparePullRequestThread", () => { - const options = gitPreparePullRequestThreadMutationOptions({ - environmentId: ENVIRONMENT_A, - cwd: "/repo/a", - queryClient, - }); - expect(options.mutationKey).toEqual( - gitMutationKeys.preparePullRequestThread(ENVIRONMENT_A, "/repo/a"), - ); - }); -}); - -describe("invalidateGitQueries", () => { - it("can invalidate a single cwd without blasting other git query scopes", async () => { - const queryClient = new QueryClient(); - - queryClient.setQueryData( - gitBranchSearchInfiniteQueryOptions({ - environmentId: ENVIRONMENT_A, - cwd: "/repo/a", - query: "feature", - }).queryKey, - BRANCH_SEARCH_RESULT, - ); - queryClient.setQueryData( - gitBranchSearchInfiniteQueryOptions({ - environmentId: ENVIRONMENT_B, - cwd: "/repo/b", - query: "feature", - }).queryKey, - BRANCH_SEARCH_RESULT, - ); - - await invalidateGitQueries(queryClient, { environmentId: ENVIRONMENT_A, cwd: "/repo/a" }); - - expect( - queryClient.getQueryState( - gitBranchSearchInfiniteQueryOptions({ - environmentId: ENVIRONMENT_A, - cwd: "/repo/a", - query: "feature", - }).queryKey, - )?.isInvalidated, - ).toBe(true); - expect( - queryClient.getQueryState( - gitBranchSearchInfiniteQueryOptions({ - environmentId: ENVIRONMENT_B, - cwd: "/repo/b", - query: "feature", - }).queryKey, - )?.isInvalidated, - ).toBe(false); - }); -}); diff --git a/apps/web/src/lib/gitReactQuery.ts b/apps/web/src/lib/gitReactQuery.ts deleted file mode 100644 index 9db96420aa..0000000000 --- a/apps/web/src/lib/gitReactQuery.ts +++ /dev/null @@ -1,327 +0,0 @@ -import { - type EnvironmentId, - type GitActionProgressEvent, - type GitStackedAction, - type SourceControlPublishRepositoryInput, - type ThreadId, -} from "@t3tools/contracts"; -import { - infiniteQueryOptions, - mutationOptions, - queryOptions, - type QueryClient, -} from "@tanstack/react-query"; -import { ensureEnvironmentApi } from "../environmentApi"; -import { requireEnvironmentConnection } from "../environments/runtime"; - -const GIT_BRANCHES_STALE_TIME_MS = 15_000; -const GIT_BRANCHES_REFETCH_INTERVAL_MS = 60_000; -const GIT_BRANCHES_PAGE_SIZE = 100; - -export const gitQueryKeys = { - all: ["git"] as const, - refs: (environmentId: EnvironmentId | null, cwd: string | null) => - ["git", "refs", environmentId ?? null, cwd] as const, - branchSearch: (environmentId: EnvironmentId | null, cwd: string | null, query: string) => - ["git", "refs", environmentId ?? null, cwd, "search", query] as const, -}; - -export const gitMutationKeys = { - init: (environmentId: EnvironmentId | null, cwd: string | null) => - ["git", "mutation", "init", environmentId ?? null, cwd] as const, - switchRef: (environmentId: EnvironmentId | null, cwd: string | null) => - ["git", "mutation", "switchRef", environmentId ?? null, cwd] as const, - runStackedAction: (environmentId: EnvironmentId | null, cwd: string | null) => - ["git", "mutation", "run-stacked-action", environmentId ?? null, cwd] as const, - pull: (environmentId: EnvironmentId | null, cwd: string | null) => - ["git", "mutation", "pull", environmentId ?? null, cwd] as const, - preparePullRequestThread: (environmentId: EnvironmentId | null, cwd: string | null) => - ["git", "mutation", "prepare-pull-request-thread", environmentId ?? null, cwd] as const, - publishRepository: (environmentId: EnvironmentId | null, cwd: string | null) => - ["git", "mutation", "publish-repository", environmentId ?? null, cwd] as const, -}; - -export function invalidateGitQueries( - queryClient: QueryClient, - input?: { environmentId?: EnvironmentId | null; cwd?: string | null }, -) { - const environmentId = input?.environmentId ?? null; - const cwd = input?.cwd ?? null; - if (cwd !== null) { - return queryClient.invalidateQueries({ queryKey: gitQueryKeys.refs(environmentId, cwd) }); - } - - return queryClient.invalidateQueries({ queryKey: gitQueryKeys.all }); -} - -function invalidateGitBranchQueries( - queryClient: QueryClient, - environmentId: EnvironmentId | null, - cwd: string | null, -) { - if (cwd === null) { - return Promise.resolve(); - } - - return queryClient.invalidateQueries({ queryKey: gitQueryKeys.refs(environmentId, cwd) }); -} - -/** - * @deprecated Use a VCS-named query helper once the UI naming migration lands. - */ -export function gitBranchSearchInfiniteQueryOptions(input: { - environmentId: EnvironmentId | null; - cwd: string | null; - query: string; - enabled?: boolean; -}) { - const normalizedQuery = input.query.trim(); - - return infiniteQueryOptions({ - queryKey: gitQueryKeys.branchSearch(input.environmentId, input.cwd, normalizedQuery), - initialPageParam: 0, - queryFn: async ({ pageParam }) => { - if (!input.cwd) throw new Error("Git refs are unavailable."); - if (!input.environmentId) throw new Error("Git refs are unavailable."); - const api = ensureEnvironmentApi(input.environmentId); - return api.vcs.listRefs({ - cwd: input.cwd, - ...(normalizedQuery.length > 0 ? { query: normalizedQuery } : {}), - cursor: pageParam, - limit: GIT_BRANCHES_PAGE_SIZE, - }); - }, - getNextPageParam: (lastPage) => lastPage.nextCursor ?? undefined, - enabled: input.cwd !== null && (input.enabled ?? true), - staleTime: GIT_BRANCHES_STALE_TIME_MS, - refetchOnWindowFocus: true, - refetchOnReconnect: true, - refetchInterval: GIT_BRANCHES_REFETCH_INTERVAL_MS, - }); -} - -export function gitResolvePullRequestQueryOptions(input: { - environmentId: EnvironmentId | null; - cwd: string | null; - reference: string | null; -}) { - return queryOptions({ - queryKey: [ - "git", - "pull-request", - input.environmentId ?? null, - input.cwd, - input.reference, - ] as const, - queryFn: async () => { - if (!input.cwd || !input.reference || !input.environmentId) { - throw new Error("Pull request lookup is unavailable."); - } - const api = ensureEnvironmentApi(input.environmentId); - return api.git.resolvePullRequest({ cwd: input.cwd, reference: input.reference }); - }, - enabled: input.environmentId !== null && input.cwd !== null && input.reference !== null, - staleTime: 30_000, - refetchOnWindowFocus: false, - refetchOnReconnect: false, - }); -} - -/** - * @deprecated Use a VCS-named mutation helper once the UI naming migration lands. - */ -export function gitInitMutationOptions(input: { - environmentId: EnvironmentId | null; - cwd: string | null; - queryClient: QueryClient; -}) { - return mutationOptions({ - mutationKey: gitMutationKeys.init(input.environmentId, input.cwd), - mutationFn: async () => { - if (!input.cwd || !input.environmentId) throw new Error("Git init is unavailable."); - const api = ensureEnvironmentApi(input.environmentId); - return api.vcs.init({ cwd: input.cwd }); - }, - onSettled: async () => { - await invalidateGitBranchQueries(input.queryClient, input.environmentId, input.cwd); - }, - }); -} - -/** - * @deprecated Use a VCS-named mutation helper once the UI naming migration lands. - */ -export function gitCheckoutMutationOptions(input: { - environmentId: EnvironmentId | null; - cwd: string | null; - queryClient: QueryClient; -}) { - return mutationOptions({ - mutationKey: gitMutationKeys.switchRef(input.environmentId, input.cwd), - mutationFn: async (refName: string) => { - if (!input.cwd || !input.environmentId) throw new Error("Git switchRef is unavailable."); - const api = ensureEnvironmentApi(input.environmentId); - return api.vcs.switchRef({ cwd: input.cwd, refName }); - }, - onSettled: async () => { - await invalidateGitBranchQueries(input.queryClient, input.environmentId, input.cwd); - }, - }); -} - -export function gitRunStackedActionMutationOptions(input: { - environmentId: EnvironmentId | null; - cwd: string | null; - queryClient: QueryClient; -}) { - return mutationOptions({ - mutationKey: gitMutationKeys.runStackedAction(input.environmentId, input.cwd), - mutationFn: async ({ - actionId, - action, - commitMessage, - featureBranch, - filePaths, - onProgress, - }: { - actionId: string; - action: GitStackedAction; - commitMessage?: string; - featureBranch?: boolean; - filePaths?: string[]; - onProgress?: (event: GitActionProgressEvent) => void; - }) => { - if (!input.cwd || !input.environmentId) throw new Error("Git action is unavailable."); - return requireEnvironmentConnection(input.environmentId).client.git.runStackedAction( - { - action, - actionId, - cwd: input.cwd, - ...(commitMessage ? { commitMessage } : {}), - ...(featureBranch ? { featureBranch: true } : {}), - ...(filePaths && filePaths.length > 0 ? { filePaths } : {}), - }, - ...(onProgress ? [{ onProgress }] : []), - ); - }, - onSuccess: async () => { - await invalidateGitBranchQueries(input.queryClient, input.environmentId, input.cwd); - }, - }); -} - -/** - * @deprecated Use a VCS-named mutation helper once the UI naming migration lands. - */ -export function gitPullMutationOptions(input: { - environmentId: EnvironmentId | null; - cwd: string | null; - queryClient: QueryClient; -}) { - return mutationOptions({ - mutationKey: gitMutationKeys.pull(input.environmentId, input.cwd), - mutationFn: async () => { - if (!input.cwd || !input.environmentId) throw new Error("Git pull is unavailable."); - const api = ensureEnvironmentApi(input.environmentId); - return api.vcs.pull({ cwd: input.cwd }); - }, - onSuccess: async () => { - await invalidateGitBranchQueries(input.queryClient, input.environmentId, input.cwd); - }, - }); -} - -export function sourceControlPublishRepositoryMutationOptions(input: { - environmentId: EnvironmentId | null; - cwd: string | null; - queryClient: QueryClient; -}) { - return mutationOptions({ - mutationKey: gitMutationKeys.publishRepository(input.environmentId, input.cwd), - mutationFn: async (args: Omit) => { - if (!input.cwd || !input.environmentId) { - throw new Error("Repository publishing is unavailable."); - } - const api = ensureEnvironmentApi(input.environmentId); - return api.sourceControl.publishRepository({ cwd: input.cwd, ...args }); - }, - onSuccess: async () => { - await invalidateGitBranchQueries(input.queryClient, input.environmentId, input.cwd); - }, - }); -} - -/** - * @deprecated Use a VCS-named mutation helper once the UI naming migration lands. - */ -export function gitCreateWorktreeMutationOptions(input: { - environmentId: EnvironmentId | null; - queryClient: QueryClient; -}) { - return mutationOptions({ - mutationKey: ["git", "mutation", "create-worktree", input.environmentId ?? null] as const, - mutationFn: ( - args: Parameters["vcs"]["createWorktree"]>[0], - ) => { - if (!input.environmentId) { - throw new Error("Worktree creation is unavailable."); - } - return ensureEnvironmentApi(input.environmentId).vcs.createWorktree(args); - }, - onSuccess: async () => { - await invalidateGitQueries(input.queryClient, { environmentId: input.environmentId }); - }, - }); -} - -/** - * @deprecated Use a VCS-named mutation helper once the UI naming migration lands. - */ -export function gitRemoveWorktreeMutationOptions(input: { - environmentId: EnvironmentId | null; - queryClient: QueryClient; -}) { - return mutationOptions({ - mutationKey: ["git", "mutation", "remove-worktree", input.environmentId ?? null] as const, - mutationFn: ( - args: Parameters["vcs"]["removeWorktree"]>[0], - ) => { - if (!input.environmentId) { - throw new Error("Worktree removal is unavailable."); - } - return ensureEnvironmentApi(input.environmentId).vcs.removeWorktree(args); - }, - onSuccess: async () => { - await invalidateGitQueries(input.queryClient, { environmentId: input.environmentId }); - }, - }); -} - -export function gitPreparePullRequestThreadMutationOptions(input: { - environmentId: EnvironmentId | null; - cwd: string | null; - queryClient: QueryClient; -}) { - return mutationOptions({ - mutationKey: gitMutationKeys.preparePullRequestThread(input.environmentId, input.cwd), - mutationFn: async (args: { - reference: string; - mode: "local" | "worktree"; - threadId?: ThreadId; - }) => { - if (!input.cwd || !input.environmentId) { - throw new Error("Pull request thread preparation is unavailable."); - } - const api = ensureEnvironmentApi(input.environmentId); - return api.git.preparePullRequestThread({ - cwd: input.cwd, - reference: args.reference, - mode: args.mode, - ...(args.threadId ? { threadId: args.threadId } : {}), - }); - }, - onSuccess: async () => { - await invalidateGitBranchQueries(input.queryClient, input.environmentId, input.cwd); - }, - }); -} diff --git a/apps/web/src/lib/projectReactQuery.ts b/apps/web/src/lib/projectReactQuery.ts deleted file mode 100644 index 5977129809..0000000000 --- a/apps/web/src/lib/projectReactQuery.ts +++ /dev/null @@ -1,52 +0,0 @@ -import type { EnvironmentId, ProjectSearchEntriesResult } from "@t3tools/contracts"; -import { queryOptions } from "@tanstack/react-query"; -import { ensureEnvironmentApi } from "~/environmentApi"; - -export const projectQueryKeys = { - all: ["projects"] as const, - searchEntries: ( - environmentId: EnvironmentId | null, - cwd: string | null, - query: string, - limit: number, - ) => ["projects", "search-entries", environmentId ?? null, cwd, query, limit] as const, -}; - -const DEFAULT_SEARCH_ENTRIES_LIMIT = 80; -const DEFAULT_SEARCH_ENTRIES_STALE_TIME = 15_000; -const EMPTY_SEARCH_ENTRIES_RESULT: ProjectSearchEntriesResult = { - entries: [], - truncated: false, -}; - -export function projectSearchEntriesQueryOptions(input: { - environmentId: EnvironmentId | null; - cwd: string | null; - query: string; - enabled?: boolean; - limit?: number; - staleTime?: number; -}) { - const limit = input.limit ?? DEFAULT_SEARCH_ENTRIES_LIMIT; - return queryOptions({ - queryKey: projectQueryKeys.searchEntries(input.environmentId, input.cwd, input.query, limit), - queryFn: async () => { - if (!input.cwd || !input.environmentId) { - throw new Error("Workspace entry search is unavailable."); - } - const api = ensureEnvironmentApi(input.environmentId); - return api.projects.searchEntries({ - cwd: input.cwd, - query: input.query, - limit, - }); - }, - enabled: - (input.enabled ?? true) && - input.environmentId !== null && - input.cwd !== null && - input.query.length > 0, - staleTime: input.staleTime ?? DEFAULT_SEARCH_ENTRIES_STALE_TIME, - placeholderData: (previous) => previous ?? EMPTY_SEARCH_ENTRIES_RESULT, - }); -} diff --git a/apps/web/src/lib/sourceControlActions.ts b/apps/web/src/lib/sourceControlActions.ts new file mode 100644 index 0000000000..481fede420 --- /dev/null +++ b/apps/web/src/lib/sourceControlActions.ts @@ -0,0 +1,381 @@ +import { + type EnvironmentId, + type GitActionProgressEvent, + type GitRunStackedActionResult, + type GitStackedAction, + type GitResolvePullRequestResult, + type SourceControlCloneProtocol, + type SourceControlPublishRepositoryResult, + type SourceControlRepositoryVisibility, + type ThreadId, + type VcsPullResult, +} from "@t3tools/contracts"; +import { + useCallback, + useEffect, + useMemo, + useState, + useSyncExternalStore, + useTransition, +} from "react"; + +import { ensureEnvironmentApi } from "../environmentApi"; +import { requireEnvironmentConnection } from "../environments/runtime"; +import { refreshGitStatus } from "./gitStatusState"; +import { vcsRefManager } from "./vcsRefState"; + +type SourceControlActionKind = + | "init" + | "pull" + | "publishRepository" + | "runStackedAction" + | "preparePullRequestThread"; + +interface SourceControlActionScope { + readonly environmentId: EnvironmentId | null; + readonly cwd: string | null; +} + +interface SourceControlActionState, TResult> { + readonly isPending: boolean; + readonly error: unknown; + readonly run: (...args: TArgs) => Promise; + readonly resetError: () => void; +} + +const actionListeners = new Set<() => void>(); +const activeActionCounts = new Map(); + +function notifyActionListeners(): void { + for (const listener of actionListeners) { + listener(); + } +} + +function subscribeActionState(listener: () => void): () => void { + actionListeners.add(listener); + return () => { + actionListeners.delete(listener); + }; +} + +function actionKey(kind: SourceControlActionKind, scope: SourceControlActionScope): string { + return `${kind}:${scope.environmentId ?? ""}:${scope.cwd ?? ""}`; +} + +function beginAction(key: string): () => void { + activeActionCounts.set(key, (activeActionCounts.get(key) ?? 0) + 1); + notifyActionListeners(); + let ended = false; + return () => { + if (ended) { + return; + } + ended = true; + const next = (activeActionCounts.get(key) ?? 1) - 1; + if (next <= 0) { + activeActionCounts.delete(key); + } else { + activeActionCounts.set(key, next); + } + notifyActionListeners(); + }; +} + +function isAnyActionRunning( + kinds: ReadonlyArray, + scope: SourceControlActionScope, +): boolean { + return kinds.some((kind) => (activeActionCounts.get(actionKey(kind, scope)) ?? 0) > 0); +} + +export function invalidateSourceControlState(scope?: { + readonly environmentId?: EnvironmentId | null; + readonly cwd?: string | null; +}): Promise { + const environmentId = scope?.environmentId ?? null; + const cwd = scope?.cwd ?? null; + if (cwd !== null) { + vcsRefManager.invalidateScope({ environmentId, cwd }); + if (environmentId !== null) { + return refreshGitStatus({ environmentId, cwd }).then( + () => undefined, + () => undefined, + ); + } + return Promise.resolve(); + } + + vcsRefManager.invalidate(); + return Promise.resolve(); +} + +function useSourceControlAction, TResult>(input: { + readonly kind: SourceControlActionKind; + readonly scope: SourceControlActionScope; + readonly action: (...args: TArgs) => Promise; + readonly invalidateOnSuccess?: boolean; +}): SourceControlActionState { + const { action, invalidateOnSuccess = true, kind, scope } = input; + const [error, setError] = useState(null); + const [activeCount, setActiveCount] = useState(0); + const [isTransitionPending, startTransition] = useTransition(); + const key = actionKey(kind, scope); + + const resetError = useCallback(() => { + startTransition(() => setError(null)); + }, [startTransition]); + + const run = useCallback( + async (...args: TArgs): Promise => { + const endAction = beginAction(key); + startTransition(() => { + setError(null); + setActiveCount((count) => count + 1); + }); + try { + const result = await action(...args); + if (invalidateOnSuccess) { + await invalidateSourceControlState(scope); + } + return result; + } catch (nextError) { + startTransition(() => setError(nextError)); + throw nextError; + } finally { + endAction(); + startTransition(() => setActiveCount((count) => Math.max(0, count - 1))); + } + }, + [action, invalidateOnSuccess, key, scope, startTransition], + ); + + return { + error, + isPending: activeCount > 0 || isTransitionPending, + resetError, + run, + }; +} + +export function useSourceControlActionRunning( + scope: SourceControlActionScope, + kinds: ReadonlyArray, +): boolean { + const stableKinds = useMemo(() => [...kinds].sort(), [kinds]); + return useSyncExternalStore( + subscribeActionState, + () => isAnyActionRunning(stableKinds, scope), + () => false, + ); +} + +export function useVcsInitAction(scope: SourceControlActionScope) { + const action = useCallback(async () => { + if (!scope.cwd || !scope.environmentId) throw new Error("Git init is unavailable."); + return ensureEnvironmentApi(scope.environmentId).vcs.init({ cwd: scope.cwd }); + }, [scope]); + + return useSourceControlAction({ + kind: "init", + scope, + action, + }); +} + +export function useGitStackedAction(scope: SourceControlActionScope) { + const action = useCallback( + async ({ + actionId, + action, + commitMessage, + featureBranch, + filePaths, + onProgress, + }: { + actionId: string; + action: GitStackedAction; + commitMessage?: string; + featureBranch?: boolean; + filePaths?: string[]; + onProgress?: (event: GitActionProgressEvent) => void; + }): Promise => { + if (!scope.cwd || !scope.environmentId) throw new Error("Git action is unavailable."); + return requireEnvironmentConnection(scope.environmentId).client.git.runStackedAction( + { + action, + actionId, + cwd: scope.cwd, + ...(commitMessage ? { commitMessage } : {}), + ...(featureBranch ? { featureBranch: true } : {}), + ...(filePaths && filePaths.length > 0 ? { filePaths } : {}), + }, + ...(onProgress ? [{ onProgress }] : []), + ); + }, + [scope], + ); + + return useSourceControlAction({ + kind: "runStackedAction", + scope, + action, + }); +} + +export function useVcsPullAction(scope: SourceControlActionScope) { + const action = useCallback(async (): Promise => { + if (!scope.cwd || !scope.environmentId) throw new Error("Git pull is unavailable."); + return ensureEnvironmentApi(scope.environmentId).vcs.pull({ cwd: scope.cwd }); + }, [scope]); + + return useSourceControlAction({ + kind: "pull", + scope, + action, + }); +} + +export function useSourceControlPublishRepositoryAction(scope: SourceControlActionScope) { + const action = useCallback( + async (args: { + provider: "github" | "gitlab" | "bitbucket" | "azure-devops"; + repository: string; + visibility: SourceControlRepositoryVisibility; + remoteName: string; + protocol: SourceControlCloneProtocol; + }): Promise => { + if (!scope.cwd || !scope.environmentId) { + throw new Error("Repository publishing is unavailable."); + } + return ensureEnvironmentApi(scope.environmentId).sourceControl.publishRepository({ + cwd: scope.cwd, + ...args, + }); + }, + [scope], + ); + + return useSourceControlAction({ + kind: "publishRepository", + scope, + action, + }); +} + +export function usePreparePullRequestThreadAction(scope: SourceControlActionScope) { + const action = useCallback( + async (args: { reference: string; mode: "local" | "worktree"; threadId?: ThreadId }) => { + if (!scope.cwd || !scope.environmentId) { + throw new Error("Pull request thread preparation is unavailable."); + } + return ensureEnvironmentApi(scope.environmentId).git.preparePullRequestThread({ + cwd: scope.cwd, + reference: args.reference, + mode: args.mode, + ...(args.threadId ? { threadId: args.threadId } : {}), + }); + }, + [scope], + ); + + return useSourceControlAction({ + kind: "preparePullRequestThread", + scope, + action, + }); +} + +interface PullRequestResolutionTarget { + readonly environmentId: EnvironmentId | null; + readonly cwd: string | null; + readonly reference: string | null; +} + +interface PullRequestResolutionState { + readonly data: GitResolvePullRequestResult | null; + readonly error: unknown; + readonly isPending: boolean; + readonly isFetching: boolean; +} + +const EMPTY_PULL_REQUEST_RESOLUTION: PullRequestResolutionState = { + data: null, + error: null, + isPending: false, + isFetching: false, +}; + +const pullRequestResolutionCache = new Map(); + +function pullRequestResolutionKey(target: PullRequestResolutionTarget): string | null { + if (!target.environmentId || !target.cwd || !target.reference) { + return null; + } + return `${target.environmentId}:${target.cwd}:${target.reference}`; +} + +export function readCachedPullRequestResolution( + target: PullRequestResolutionTarget, +): GitResolvePullRequestResult | null { + const key = pullRequestResolutionKey(target); + return key ? (pullRequestResolutionCache.get(key) ?? null) : null; +} + +export function usePullRequestResolution( + target: PullRequestResolutionTarget, +): PullRequestResolutionState { + const stableTarget = useMemo( + () => ({ + environmentId: target.environmentId, + cwd: target.cwd, + reference: target.reference, + }), + [target.cwd, target.environmentId, target.reference], + ); + const key = pullRequestResolutionKey(stableTarget); + const [state, setState] = useState(() => { + const cached = readCachedPullRequestResolution(stableTarget); + return cached + ? { data: cached, error: null, isPending: false, isFetching: false } + : EMPTY_PULL_REQUEST_RESOLUTION; + }); + + useEffect(() => { + if (!key || !stableTarget.environmentId || !stableTarget.cwd || !stableTarget.reference) { + setState(EMPTY_PULL_REQUEST_RESOLUTION); + return; + } + + const cached = pullRequestResolutionCache.get(key) ?? null; + setState({ + data: cached, + error: null, + isPending: cached === null, + isFetching: true, + }); + + let cancelled = false; + ensureEnvironmentApi(stableTarget.environmentId) + .git.resolvePullRequest({ cwd: stableTarget.cwd, reference: stableTarget.reference }) + .then((result) => { + if (cancelled) { + return; + } + pullRequestResolutionCache.set(key, result); + setState({ data: result, error: null, isPending: false, isFetching: false }); + }) + .catch((error: unknown) => { + if (cancelled) { + return; + } + setState({ data: cached, error, isPending: false, isFetching: false }); + }); + + return () => { + cancelled = true; + }; + }, [key, stableTarget]); + + return state; +} diff --git a/apps/web/src/lib/vcsRefState.ts b/apps/web/src/lib/vcsRefState.ts new file mode 100644 index 0000000000..8addc03c5f --- /dev/null +++ b/apps/web/src/lib/vcsRefState.ts @@ -0,0 +1,48 @@ +import { useAtomValue } from "@effect/atom-react"; +import { + type VcsRefState, + type VcsRefTarget, + EMPTY_VCS_REF_ATOM, + EMPTY_VCS_REF_STATE, + createVcsRefManager, + getVcsRefTargetKey, + vcsRefStateAtom, +} from "@t3tools/client-runtime"; +import { useEffect, useMemo } from "react"; + +import { + readEnvironmentConnection, + subscribeEnvironmentConnections, +} from "../environments/runtime"; +import { appAtomRegistry } from "../rpc/atomRegistry"; + +const VCS_REF_LIST_LIMIT = 100; +const VCS_REF_STALE_TIME_MS = 5_000; + +export const vcsRefManager = createVcsRefManager({ + getRegistry: () => appAtomRegistry, + getClient: (environmentId) => readEnvironmentConnection(environmentId)?.client.vcs ?? null, + subscribeClientChanges: subscribeEnvironmentConnections, + watchLimit: VCS_REF_LIST_LIMIT, + staleTimeMs: VCS_REF_STALE_TIME_MS, + onBackgroundError: (error) => { + console.warn("[vcs-refs] background refresh failed", error); + }, +}); + +export function useVcsRefs(target: VcsRefTarget): VcsRefState { + const stableTarget = useMemo( + () => ({ + environmentId: target.environmentId, + cwd: target.cwd, + query: target.query ?? null, + }), + [target.cwd, target.environmentId, target.query], + ); + const targetKey = getVcsRefTargetKey(stableTarget); + + useEffect(() => vcsRefManager.watch(stableTarget), [stableTarget]); + + const state = useAtomValue(targetKey !== null ? vcsRefStateAtom(targetKey) : EMPTY_VCS_REF_ATOM); + return targetKey === null ? EMPTY_VCS_REF_STATE : state; +} diff --git a/packages/client-runtime/src/vcsRefState.test.ts b/packages/client-runtime/src/vcsRefState.test.ts index a42bf8792f..2b508b5ed0 100644 --- a/packages/client-runtime/src/vcsRefState.test.ts +++ b/packages/client-runtime/src/vcsRefState.test.ts @@ -102,7 +102,7 @@ describe("createVcsRefManager", () => { expect(mock.listRefs).toHaveBeenCalledWith({ cwd: "/repo", limit: 100 }); }); - it("loads the next page and appends branches", async () => { + it("loads the next page and appends refs", async () => { const mock = createMockClient(); const manager = createVcsRefManager({ getRegistry: () => atomRegistry, @@ -126,6 +126,70 @@ describe("createVcsRefManager", () => { }); }); + it("keeps cached refs visible while refreshing", async () => { + const nextLoad = deferred(); + let callCount = 0; + const listRefs = vi.fn((async () => { + callCount += 1; + return callCount === 1 ? FIRST_PAGE : nextLoad.promise; + }) satisfies VcsRefClient["listRefs"]); + const client = { listRefs } satisfies VcsRefClient; + const manager = createVcsRefManager({ + getRegistry: () => atomRegistry, + getClient: () => client, + }); + + await manager.load(TARGET, client); + + const refresh = manager.load(TARGET, client); + expect(manager.getSnapshot(TARGET)).toEqual({ + data: FIRST_PAGE, + isPending: true, + error: null, + }); + + nextLoad.resolve(SECOND_PAGE); + await expect(refresh).resolves.toEqual(SECOND_PAGE); + expect(manager.getSnapshot(TARGET)).toEqual({ + data: SECOND_PAGE, + isPending: false, + error: null, + }); + }); + + it("preserves loaded pages during first-page revalidation", async () => { + const refreshedFirstPage: VcsListRefsResult = { + ...FIRST_PAGE, + refs: [{ name: "main", current: true, isDefault: true, worktreePath: null }], + nextCursor: 1, + totalCount: 3, + }; + let callCount = 0; + const listRefs = vi.fn((async (input) => { + callCount += 1; + if (input.cursor === 2) { + return SECOND_PAGE; + } + return callCount === 1 ? FIRST_PAGE : refreshedFirstPage; + }) satisfies VcsRefClient["listRefs"]); + const client = { listRefs } satisfies VcsRefClient; + const manager = createVcsRefManager({ + getRegistry: () => atomRegistry, + getClient: () => client, + }); + + await manager.load(TARGET, client); + await manager.loadNext(TARGET, client); + const beforeRefresh = manager.getSnapshot(TARGET).data; + expect(beforeRefresh?.refs.map((ref) => ref.name)).toEqual(["main", "feature/a", "feature/b"]); + + await manager.load(TARGET, client, { preserveLoadedRefs: true }); + + const afterRefresh = manager.getSnapshot(TARGET).data; + expect(afterRefresh?.refs.map((ref) => ref.name)).toEqual(["main", "feature/a", "feature/b"]); + expect(afterRefresh?.nextCursor).toBeNull(); + }); + it("stores query-specific state independently", async () => { const mock = createMockClient(); const manager = createVcsRefManager({ @@ -171,7 +235,24 @@ describe("createVcsRefManager", () => { expect(manager.getSnapshot(TARGET)).toEqual(EMPTY_VCS_REF_STATE); }); - it("watches branches with a ref-counted client-change subscription", async () => { + it("invalidates every query for a cwd scope", async () => { + const mock = createMockClient(); + const manager = createVcsRefManager({ + getRegistry: () => atomRegistry, + getClient: () => mock.client, + }); + const queriedTarget = { ...TARGET, query: "feature" } as const; + + await manager.load(TARGET, mock.client); + await manager.load(queriedTarget, mock.client); + + manager.invalidateScope({ environmentId: TARGET.environmentId, cwd: TARGET.cwd }); + + expect(manager.getSnapshot(TARGET)).toEqual(EMPTY_VCS_REF_STATE); + expect(manager.getSnapshot(queriedTarget)).toEqual(EMPTY_VCS_REF_STATE); + }); + + it("watches refs with a ref-counted client-change subscription", async () => { const mock = createMockClient(); let listener: () => void = noop; const unsubscribe = vi.fn(); @@ -202,6 +283,29 @@ describe("createVcsRefManager", () => { expect(unsubscribe).toHaveBeenCalledTimes(1); }); + it("skips watched refresh while cached refs are fresh", async () => { + const mock = createMockClient(); + const manager = createVcsRefManager({ + getRegistry: () => atomRegistry, + getClient: () => mock.client, + staleTimeMs: 60_000, + watchLimit: 100, + }); + + await manager.load(TARGET, mock.client, { limit: 100 }); + const unwatch = manager.watch(TARGET); + await Promise.resolve(); + + expect(mock.listRefs).toHaveBeenCalledTimes(1); + expect(manager.getSnapshot(TARGET)).toEqual({ + data: FIRST_PAGE, + isPending: false, + error: null, + }); + + unwatch(); + }); + it("swallows watched refresh failures after storing error state", async () => { const refreshError = new Error("backend unavailable"); const listRefs = vi.fn(async () => { diff --git a/packages/client-runtime/src/vcsRefState.ts b/packages/client-runtime/src/vcsRefState.ts index 692d8d53e9..13df8f2c3f 100644 --- a/packages/client-runtime/src/vcsRefState.ts +++ b/packages/client-runtime/src/vcsRefState.ts @@ -4,6 +4,8 @@ import type { VcsListRefsResult, VcsRef as ContractVcsRef, } from "@t3tools/contracts"; +import * as Clock from "effect/Clock"; +import * as Effect from "effect/Effect"; import { Atom, type AtomRegistry } from "effect/unstable/reactivity"; import type { WsRpcClient } from "./wsRpcClient.ts"; @@ -14,6 +16,11 @@ export interface VcsRefTarget { readonly query?: string | null; } +export interface VcsRefScope { + readonly environmentId: EnvironmentId | null; + readonly cwd: string | null; +} + export interface VcsRefState { readonly data: VcsListRefsResult | null; readonly isPending: boolean; @@ -82,6 +89,7 @@ export interface VcsRefManagerConfig { readonly getClient: (environmentId: EnvironmentId) => VcsRefClient | null; readonly subscribeClientChanges?: (listener: () => void) => () => void; readonly watchLimit?: number; + readonly staleTimeMs?: number; readonly onBackgroundError?: (error: unknown) => void; } @@ -102,8 +110,11 @@ export function createVcsRefManager(config: VcsRefManagerConfig) { >(); const loadVersions = new Map(); const watched = new Map(); + const lastLoadedAt = new Map(); const watchLoadOptions = - config.watchLimit === undefined ? undefined : { limit: config.watchLimit }; + config.watchLimit === undefined + ? undefined + : { limit: config.watchLimit, preserveLoadedRefs: true }; function getLoadVersion(targetKey: string): number { return loadVersions.get(targetKey) ?? 0; @@ -136,6 +147,7 @@ export function createVcsRefManager(config: VcsRefManagerConfig) { } function setData(targetKey: string, data: VcsListRefsResult): void { + lastLoadedAt.set(targetKey, Effect.runSync(Clock.currentTimeMillis)); setState(targetKey, { data, isPending: false, @@ -159,6 +171,7 @@ export function createVcsRefManager(config: VcsRefManagerConfig) { readonly cursor?: number; readonly limit?: number; readonly append?: boolean; + readonly preserveLoadedRefs?: boolean; }, ): Promise { const targetKey = getVcsRefTargetKey(target); @@ -196,7 +209,14 @@ export function createVcsRefManager(config: VcsRefManagerConfig) { ...result, refs: mergeRefs(current.refs, result.refs), } - : result; + : options?.preserveLoadedRefs && current && current.refs.length > result.refs.length + ? { + ...result, + refs: mergeRefs(result.refs, current.refs), + nextCursor: current.nextCursor, + totalCount: Math.max(result.totalCount, current.totalCount), + } + : result; if (getLoadVersion(targetKey) === loadVersion) { setData(targetKey, nextData); } @@ -227,6 +247,7 @@ export function createVcsRefManager(config: VcsRefManagerConfig) { readonly cursor?: number; readonly limit?: number; readonly append?: boolean; + readonly preserveLoadedRefs?: boolean; }, ): void { void load(target, client, options).catch((error: unknown) => { @@ -264,9 +285,21 @@ export function createVcsRefManager(config: VcsRefManagerConfig) { } let teardown: () => void; + const shouldRefresh = () => { + if (config.staleTimeMs === undefined) { + return true; + } + const lastLoaded = lastLoadedAt.get(targetKey); + return ( + lastLoaded === undefined || + Effect.runSync(Clock.currentTimeMillis) - lastLoaded >= config.staleTimeMs + ); + }; if (client) { - loadInBackground(target, client, watchLoadOptions); + if (shouldRefresh()) { + loadInBackground(target, client, watchLoadOptions); + } teardown = NOOP; } else if (config.subscribeClientChanges) { let currentClient: VcsRefClient | null = null; @@ -281,7 +314,9 @@ export function createVcsRefManager(config: VcsRefManagerConfig) { } currentClient = resolved; - loadInBackground(target, resolved, watchLoadOptions); + if (shouldRefresh()) { + loadInBackground(target, resolved, watchLoadOptions); + } }; const unsubscribe = config.subscribeClientChanges(sync); @@ -292,7 +327,9 @@ export function createVcsRefManager(config: VcsRefManagerConfig) { if (!resolved) { return NOOP; } - loadInBackground(target, resolved, watchLoadOptions); + if (shouldRefresh()) { + loadInBackground(target, resolved, watchLoadOptions); + } teardown = NOOP; } @@ -329,6 +366,26 @@ export function createVcsRefManager(config: VcsRefManagerConfig) { } } + function invalidateScope(scope: VcsRefScope): void { + if (scope.environmentId === null || scope.cwd === null) { + return; + } + + const keyPrefix = `${scope.environmentId}:${scope.cwd}:`; + for (const key of knownVcsRefKeys) { + if (key.startsWith(keyPrefix)) { + bumpLoadVersion(key); + setState(key, EMPTY_VCS_REF_STATE); + } + } + + for (const key of inFlight.keys()) { + if (key.startsWith(keyPrefix)) { + inFlight.delete(key); + } + } + } + function reset(): void { for (const entry of watched.values()) { entry.teardown(); @@ -336,6 +393,7 @@ export function createVcsRefManager(config: VcsRefManagerConfig) { watched.clear(); inFlight.clear(); loadVersions.clear(); + lastLoadedAt.clear(); invalidate(); } @@ -345,6 +403,7 @@ export function createVcsRefManager(config: VcsRefManagerConfig) { load, loadNext, invalidate, + invalidateScope, reset, }; }