diff --git a/apps/mobile/src/features/threads/new-task-flow-provider.tsx b/apps/mobile/src/features/threads/new-task-flow-provider.tsx index fe1dd482f6..a8f7284d80 100644 --- a/apps/mobile/src/features/threads/new-task-flow-provider.tsx +++ b/apps/mobile/src/features/threads/new-task-flow-provider.tsx @@ -1,9 +1,7 @@ import React, { useCallback, useEffect, useMemo, useState } from "react"; import type { - ClaudeAgentEffort, EnvironmentId, - GitBranch, ModelSelection, ProviderInteractionMode, RuntimeMode, @@ -17,19 +15,20 @@ import type { ModelOption, ProviderGroup } from "../../lib/modelOptions"; import { buildModelOptions, groupByProvider } from "../../lib/modelOptions"; import { groupProjectsByRepository } from "../../lib/repositoryGroups"; import { scopedProjectKey } from "../../lib/scopedEntities"; -import { gitBranchManager, useGitBranches } from "../../state/use-git-branches"; +import { vcsRefManager, useVcsRefs } from "../../state/use-vcs-refs"; import { useRemoteCatalog } from "../../state/use-remote-catalog"; import { setPendingConnectionError, useRemoteEnvironmentState, } from "../../state/use-remote-environment-registry"; -import { EnvironmentScopedProjectShell } from "@t3tools/client-runtime"; +import { EnvironmentScopedProjectShell, type VcsRef } from "@t3tools/client-runtime"; +import type { ClaudeAgentEffort } from "./claudeEffortOptions"; type WorkspaceMode = "local" | "worktree"; function normalizeSelectedWorktreePath( project: EnvironmentScopedProjectShell, - branch: GitBranch, + branch: VcsRef, ): string | null { if (!branch.worktreePath) { return null; @@ -39,7 +38,7 @@ function normalizeSelectedWorktreePath( } export function branchBadgeLabel(input: { - readonly branch: GitBranch; + readonly branch: VcsRef; readonly project: EnvironmentScopedProjectShell | null; }): string | null { if (input.branch.current) { @@ -73,7 +72,7 @@ type NewTaskFlowContextValue = { readonly submitting: boolean; readonly branchQuery: string; readonly branchesLoading: boolean; - readonly availableBranches: ReadonlyArray; + readonly availableBranches: ReadonlyArray; readonly runtimeMode: RuntimeMode; readonly interactionMode: ProviderInteractionMode; readonly effort: ClaudeAgentEffort; @@ -89,13 +88,13 @@ type NewTaskFlowContextValue = { readonly selectedModel: ModelSelection | null; readonly selectedModelOption: ModelOption | null; readonly providerGroups: ReadonlyArray; - readonly filteredBranches: ReadonlyArray; + readonly filteredBranches: ReadonlyArray; readonly reset: () => void; readonly setProject: (project: EnvironmentScopedProjectShell) => void; readonly selectEnvironment: (environmentId: EnvironmentId) => void; readonly setSelectedModelKey: (key: string | null) => void; readonly setWorkspaceMode: (mode: WorkspaceMode) => void; - readonly selectBranch: (branch: GitBranch) => void; + readonly selectBranch: (branch: VcsRef) => void; readonly setPrompt: (value: string) => void; readonly replaceAttachments: (attachments: ReadonlyArray) => void; readonly appendAttachments: (attachments: ReadonlyArray) => void; @@ -293,7 +292,7 @@ export function NewTaskFlowProvider(props: React.PropsWithChildren) { modelOptions.find( (option) => selectedModel && - option.selection.provider === selectedModel.provider && + option.selection.instanceId === selectedModel.instanceId && option.selection.model === selectedModel.model, ) ?? null; @@ -306,15 +305,15 @@ export function NewTaskFlowProvider(props: React.PropsWithChildren) { }), [selectedProject?.environmentId, selectedProject?.workspaceRoot], ); - const branchState = useGitBranches(branchTarget); + const branchState = useVcsRefs(branchTarget); const branchesLoading = branchState.isPending; const availableBranches = useMemo( () => pipe( - branchState.data?.branches ?? [], + branchState.data?.refs ?? [], Arr.filter((branch) => !branch.isRemote), ), - [branchState.data?.branches], + [branchState.data?.refs], ); const filteredBranches = useMemo(() => { @@ -342,7 +341,7 @@ export function NewTaskFlowProvider(props: React.PropsWithChildren) { }, []); const selectBranch = useCallback( - (branch: GitBranch) => { + (branch: VcsRef) => { setSelectedBranchName(branch.name); setSelectedWorktreePath( selectedProject ? normalizeSelectedWorktreePath(selectedProject, branch) : null, @@ -357,14 +356,14 @@ export function NewTaskFlowProvider(props: React.PropsWithChildren) { } try { - const result = await gitBranchManager.load({ + const result = await vcsRefManager.load({ environmentId: selectedProject.environmentId, cwd: selectedProject.workspaceRoot, query: null, }); setPendingConnectionError(null); const branches = pipe( - result?.branches ?? [], + result?.refs ?? [], Arr.filter((branch) => !branch.isRemote), ); diff --git a/apps/mobile/src/features/threads/use-project-actions.ts b/apps/mobile/src/features/threads/use-project-actions.ts index c5d8a66a28..58a0afbb2b 100644 --- a/apps/mobile/src/features/threads/use-project-actions.ts +++ b/apps/mobile/src/features/threads/use-project-actions.ts @@ -1,6 +1,6 @@ import { useCallback } from "react"; -import { EnvironmentScopedProjectShell } from "@t3tools/client-runtime"; +import { EnvironmentScopedProjectShell, type VcsRef } from "@t3tools/client-runtime"; import { CommandId, DEFAULT_PROVIDER_INTERACTION_MODE, @@ -8,7 +8,6 @@ import { type EnvironmentId, MessageId, ThreadId, - type GitBranch, type ModelSelection, type ProviderInteractionMode, type RuntimeMode, @@ -19,7 +18,7 @@ import type { DraftComposerImageAttachment } from "../../lib/composerImages"; import { uuidv4 } from "../../lib/uuid"; import { getEnvironmentClient } from "../../state/environment-session-registry"; import { environmentRuntimeManager } from "../../state/use-environment-runtime"; -import { gitBranchManager } from "../../state/use-git-branches"; +import { vcsRefManager } from "../../state/use-vcs-refs"; import { useRemoteCatalog } from "../../state/use-remote-catalog"; import { setPendingConnectionError, @@ -186,19 +185,19 @@ export function useProjectActions() { ); const onListProjectBranches = useCallback( - async (project: EnvironmentScopedProjectShell): Promise> => { + async (project: EnvironmentScopedProjectShell): Promise> => { const client = getEnvironmentClient(project.environmentId); if (!client) { return []; } try { - const result = await gitBranchManager.load( + const result = await vcsRefManager.load( { environmentId: project.environmentId, cwd: project.workspaceRoot, query: null }, - client.git, + client.vcs, { limit: 100 }, ); - return (result?.branches ?? []).filter((branch) => !branch.isRemote); + return (result?.refs ?? []).filter((branch) => !branch.isRemote); } catch (error) { setPendingConnectionError( error instanceof Error ? error.message : "Failed to load branches.", @@ -226,19 +225,19 @@ export function useProjectActions() { } try { - const result = await client.git.createWorktree({ + const result = await client.vcs.createWorktree({ cwd: project.workspaceRoot, - branch: nextWorktree.baseBranch, - newBranch: sanitizeFeatureBranchName(nextWorktree.newBranch), + refName: nextWorktree.baseBranch, + newRefName: sanitizeFeatureBranchName(nextWorktree.newBranch), path: null, }); - gitBranchManager.invalidate({ + vcsRefManager.invalidate({ environmentId: project.environmentId, cwd: project.workspaceRoot, query: null, }); return { - branch: result.worktree.branch, + branch: result.worktree.refName, worktreePath: result.worktree.path, }; } catch (error) { diff --git a/apps/mobile/src/state/use-selected-thread-git-actions.ts b/apps/mobile/src/state/use-selected-thread-git-actions.ts index 50c891ed8a..6f7c7530b1 100644 --- a/apps/mobile/src/state/use-selected-thread-git-actions.ts +++ b/apps/mobile/src/state/use-selected-thread-git-actions.ts @@ -3,14 +3,10 @@ import { useCallback, useEffect } from "react"; import { EnvironmentScopedProjectShell, EnvironmentScopedThreadShell, + type VcsRef, type GitActionRequestInput, } from "@t3tools/client-runtime"; -import { - CommandId, - type GitBranch, - type GitRunStackedActionResult, - ThreadId, -} from "@t3tools/contracts"; +import { CommandId, type GitRunStackedActionResult } from "@t3tools/contracts"; import { dedupeRemoteBranchesWithLocalMatches, sanitizeFeatureBranchName, @@ -20,7 +16,7 @@ import { uuidv4 } from "../lib/uuid"; import { getEnvironmentClient } from "./environment-session-registry"; import { setPendingConnectionError } from "./use-remote-environment-registry"; import { gitActionManager, showGitActionResult } from "./use-git-action-state"; -import { gitBranchManager } from "./use-git-branches"; +import { vcsRefManager } from "./use-vcs-refs"; import { gitStatusManager } from "./use-git-status"; import { useThreadSelection } from "./use-thread-selection"; import { useSelectedThreadWorktree } from "./use-selected-thread-worktree"; @@ -74,7 +70,7 @@ export function useSelectedThreadGitActions() { const status = await gitActionManager.refreshStatus( { environmentId: selectedThread.environmentId, cwd }, - client.git, + { ...client.vcs, runStackedAction: client.git.runStackedAction }, options, ); setPendingConnectionError(null); @@ -130,7 +126,7 @@ export function useSelectedThreadGitActions() { [selectedThread, selectedThreadCwd, selectedThreadProject], ); - const refreshSelectedThreadBranches = useCallback(async (): Promise> => { + const refreshSelectedThreadBranches = useCallback(async (): Promise> => { if (!selectedThread || !selectedThreadProject || !selectedThreadGitRootCwd) { return []; } @@ -141,12 +137,12 @@ export function useSelectedThreadGitActions() { } try { - const result = await gitBranchManager.load( + const result = await vcsRefManager.load( { environmentId: selectedThread.environmentId, cwd: selectedThreadGitRootCwd, query: null }, - client.git, + client.vcs, { limit: 100 }, ); - return dedupeRemoteBranchesWithLocalMatches(result?.branches ?? []).filter( + return dedupeRemoteBranchesWithLocalMatches(result?.refs ?? []).filter( (branch) => !branch.isRemote, ); } catch (error) { @@ -173,7 +169,7 @@ export function useSelectedThreadGitActions() { const branchRootCwd = input.branchRootCwd ?? selectedThreadProject?.workspaceRoot ?? null; if (branchRootCwd) { - gitBranchManager.invalidate({ + vcsRefManager.invalidate({ environmentId: input.thread.environmentId, cwd: branchRootCwd, query: null, @@ -194,15 +190,15 @@ export function useSelectedThreadGitActions() { const onCheckoutSelectedThreadBranch = useCallback( async (branch: string) => { await runSelectedThreadGitMutation(async ({ thread, cwd }) => { - const result = await gitActionManager.checkout( + const result = await gitActionManager.switchRef( { environmentId: thread.environmentId, cwd }, - { branch }, + { refName: branch }, ); await syncSelectedThreadBranchState({ thread, cwd, nextThreadState: { - branch: result?.branch ?? thread.branch, + branch: result?.refName ?? thread.branch, worktreePath: selectedThreadWorktreePath, }, }); @@ -214,18 +210,18 @@ export function useSelectedThreadGitActions() { const onCreateSelectedThreadBranch = useCallback( async (branch: string) => { await runSelectedThreadGitMutation(async ({ thread, cwd }) => { - const result = await gitActionManager.createBranch( + const result = await gitActionManager.createRef( { environmentId: thread.environmentId, cwd }, { - branch, - checkout: true, + refName: branch, + switchRef: true, }, ); await syncSelectedThreadBranchState({ thread, cwd, nextThreadState: { - branch: result?.branch ?? thread.branch, + branch: result?.refName ?? thread.branch, worktreePath: selectedThreadWorktreePath, }, }); @@ -240,8 +236,8 @@ export function useSelectedThreadGitActions() { const result = await gitActionManager.createWorktree( { environmentId: thread.environmentId, cwd: project.workspaceRoot }, { - branch: nextWorktree.baseBranch, - newBranch: sanitizeFeatureBranchName(nextWorktree.newBranch), + refName: nextWorktree.baseBranch, + newRefName: sanitizeFeatureBranchName(nextWorktree.newBranch), path: null, }, ); @@ -254,7 +250,7 @@ export function useSelectedThreadGitActions() { cwd: result.worktree.path, branchRootCwd: project.workspaceRoot, nextThreadState: { - branch: result.worktree.branch, + branch: result.worktree.refName, worktreePath: result.worktree.path, }, }); @@ -273,7 +269,7 @@ export function useSelectedThreadGitActions() { title: result.status === "skipped_up_to_date" ? "Already up to date" - : `Pulled latest on ${result.branch}`, + : `Pulled latest on ${result.refName}`, }); } }); diff --git a/apps/mobile/src/state/use-selected-thread-git-state.ts b/apps/mobile/src/state/use-selected-thread-git-state.ts index ea7bec44af..ebc40c3cf4 100644 --- a/apps/mobile/src/state/use-selected-thread-git-state.ts +++ b/apps/mobile/src/state/use-selected-thread-git-state.ts @@ -3,7 +3,7 @@ import { useMemo } from "react"; import { dedupeRemoteBranchesWithLocalMatches } from "@t3tools/shared/git"; import { useGitActionState } from "./use-git-action-state"; -import { useGitBranches } from "./use-git-branches"; +import { useVcsRefs } from "./use-vcs-refs"; import { useSourceControlDiscovery } from "./use-source-control-discovery"; import { useThreadSelection } from "./use-thread-selection"; import { useSelectedThreadWorktree } from "./use-selected-thread-worktree"; @@ -30,7 +30,7 @@ export function useSelectedThreadGitState() { }), [selectedThread?.environmentId, selectedThreadProject?.workspaceRoot], ); - const selectedThreadBranchState = useGitBranches(selectedThreadBranchTarget); + const selectedThreadBranchState = useVcsRefs(selectedThreadBranchTarget); const selectedThreadBranches = useMemo( () => dedupeRemoteBranchesWithLocalMatches(selectedThreadBranchState.data?.branches ?? []).filter( diff --git a/apps/mobile/src/state/use-git-branches.ts b/apps/mobile/src/state/use-vcs-refs.ts similarity index 54% rename from apps/mobile/src/state/use-git-branches.ts rename to apps/mobile/src/state/use-vcs-refs.ts index 5c932a99c1..8e9e4dac29 100644 --- a/apps/mobile/src/state/use-git-branches.ts +++ b/apps/mobile/src/state/use-vcs-refs.ts @@ -1,13 +1,13 @@ import { useAtomValue } from "@effect/atom-react"; import { useEffect, useMemo } from "react"; import { - type GitBranchState, - type GitBranchTarget, - EMPTY_GIT_BRANCH_ATOM, - EMPTY_GIT_BRANCH_STATE, - createGitBranchManager, - getGitBranchTargetKey, - gitBranchStateAtom, + type VcsRefState, + type VcsRefTarget, + EMPTY_VCS_REF_ATOM, + EMPTY_VCS_REF_STATE, + createVcsRefManager, + getVcsRefTargetKey, + vcsRefStateAtom, } from "@t3tools/client-runtime"; import { appAtomRegistry } from "./atom-registry"; @@ -16,7 +16,7 @@ import { subscribeEnvironmentConnections, } from "./environment-session-registry"; -export const gitBranchManager = createGitBranchManager({ +export const vcsRefManager = createVcsRefManager({ getRegistry: () => appAtomRegistry, getClient: (environmentId) => { const client = getEnvironmentClient(environmentId); @@ -24,9 +24,12 @@ export const gitBranchManager = createGitBranchManager({ }, subscribeClientChanges: subscribeEnvironmentConnections, watchLimit: 100, + onBackgroundError: (error) => { + console.warn("[vcs-refs] background refresh failed", error); + }, }); -export function useGitBranches(target: GitBranchTarget): GitBranchState { +export function useVcsRefs(target: VcsRefTarget): VcsRefState { const stableTarget = useMemo( () => ({ environmentId: target.environmentId, @@ -35,10 +38,8 @@ export function useGitBranches(target: GitBranchTarget): GitBranchState { }), [target.cwd, target.environmentId, target.query], ); - const targetKey = getGitBranchTargetKey(stableTarget); - useEffect(() => gitBranchManager.watch(stableTarget), [stableTarget]); - const state = useAtomValue( - targetKey !== null ? gitBranchStateAtom(targetKey) : EMPTY_GIT_BRANCH_ATOM, - ); - return targetKey === null ? EMPTY_GIT_BRANCH_STATE : state; + 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/index.ts b/packages/client-runtime/src/index.ts index 8f35bf51cb..e2a58c652b 100644 --- a/packages/client-runtime/src/index.ts +++ b/packages/client-runtime/src/index.ts @@ -11,7 +11,7 @@ export * from "./threadDetailReducer.ts"; export * from "./threadDetailState.ts"; export * from "./gitActions.ts"; export * from "./gitActionState.ts"; -export * from "./gitBranchState.ts"; +export * from "./vcsRefState.ts"; export * from "./gitStatusState.ts"; export * from "./terminalSessionState.ts"; export * from "./transportError.ts"; diff --git a/packages/client-runtime/src/gitBranchState.test.ts b/packages/client-runtime/src/vcsRefState.test.ts similarity index 50% rename from packages/client-runtime/src/gitBranchState.test.ts rename to packages/client-runtime/src/vcsRefState.test.ts index 5220c6dcac..a42bf8792f 100644 --- a/packages/client-runtime/src/gitBranchState.test.ts +++ b/packages/client-runtime/src/vcsRefState.test.ts @@ -1,13 +1,13 @@ -import { EnvironmentId, type GitListBranchesResult } from "@t3tools/contracts"; +import { EnvironmentId, type VcsListRefsResult } from "@t3tools/contracts"; import { AtomRegistry } from "effect/unstable/reactivity"; import { afterEach, describe, expect, it, vi } from "vitest"; import { - createGitBranchManager, - EMPTY_GIT_BRANCH_STATE, - gitBranchStateAtom, - type GitBranchClient, -} from "./gitBranchState.ts"; + createVcsRefManager, + EMPTY_VCS_REF_STATE, + vcsRefStateAtom, + type VcsRefClient, +} from "./vcsRefState.ts"; let atomRegistry = AtomRegistry.make(); @@ -20,34 +20,34 @@ const noop = () => undefined; const TARGET = { environmentId: EnvironmentId.make("env-local"), cwd: "/repo" } as const; -const FIRST_PAGE: GitListBranchesResult = { - branches: [ +const FIRST_PAGE: VcsListRefsResult = { + refs: [ { name: "main", current: true, isDefault: true, worktreePath: null }, { name: "feature/a", current: false, isDefault: false, worktreePath: null }, ], isRepo: true, - hasOriginRemote: true, + hasPrimaryRemote: true, nextCursor: 2, totalCount: 3, }; -const SECOND_PAGE: GitListBranchesResult = { - branches: [{ name: "feature/b", current: false, isDefault: false, worktreePath: null }], +const SECOND_PAGE: VcsListRefsResult = { + refs: [{ name: "feature/b", current: false, isDefault: false, worktreePath: null }], isRepo: true, - hasOriginRemote: true, + hasPrimaryRemote: true, nextCursor: null, totalCount: 3, }; function createMockClient() { - const listBranches = vi.fn(async (input: Parameters[0]) => { + const listRefs = vi.fn(async (input: Parameters[0]) => { if (input.query === "feature") { return { ...FIRST_PAGE, - branches: FIRST_PAGE.branches.filter((branch) => branch.name.includes("feature")), + refs: FIRST_PAGE.refs.filter((branch) => branch.name.includes("feature")), nextCursor: null, totalCount: 2, - } satisfies GitListBranchesResult; + } satisfies VcsListRefsResult; } if (input.cursor === 2) { @@ -58,19 +58,29 @@ function createMockClient() { }); return { - client: { listBranches } satisfies GitBranchClient, - listBranches, + client: { listRefs } satisfies VcsRefClient, + listRefs, }; } -describe("createGitBranchManager", () => { +function deferred() { + let resolve!: (value: T) => void; + let reject!: (error: unknown) => void; + const promise = new Promise((resolvePromise, rejectPromise) => { + resolve = resolvePromise; + reject = rejectPromise; + }); + return { promise, resolve, reject }; +} + +describe("createVcsRefManager", () => { afterEach(() => { resetAtomRegistry(); }); it("loads the first page and stores it in atom state", async () => { const mock = createMockClient(); - const manager = createGitBranchManager({ + const manager = createVcsRefManager({ getRegistry: () => atomRegistry, getClient: () => mock.client, }); @@ -89,12 +99,12 @@ describe("createGitBranchManager", () => { isPending: false, error: null, }); - expect(mock.listBranches).toHaveBeenCalledWith({ cwd: "/repo", limit: 100 }); + expect(mock.listRefs).toHaveBeenCalledWith({ cwd: "/repo", limit: 100 }); }); it("loads the next page and appends branches", async () => { const mock = createMockClient(); - const manager = createGitBranchManager({ + const manager = createVcsRefManager({ getRegistry: () => atomRegistry, getClient: () => mock.client, }); @@ -104,12 +114,12 @@ describe("createGitBranchManager", () => { expect(next).toEqual({ ...SECOND_PAGE, - branches: [...FIRST_PAGE.branches, ...SECOND_PAGE.branches], + refs: [...FIRST_PAGE.refs, ...SECOND_PAGE.refs], }); expect(manager.getSnapshot(TARGET)).toEqual({ data: { ...SECOND_PAGE, - branches: [...FIRST_PAGE.branches, ...SECOND_PAGE.branches], + refs: [...FIRST_PAGE.refs, ...SECOND_PAGE.refs], }, isPending: false, error: null, @@ -118,7 +128,7 @@ describe("createGitBranchManager", () => { it("stores query-specific state independently", async () => { const mock = createMockClient(); - const manager = createGitBranchManager({ + const manager = createVcsRefManager({ getRegistry: () => atomRegistry, getClient: () => mock.client, }); @@ -126,20 +136,20 @@ describe("createGitBranchManager", () => { const queriedTarget = { ...TARGET, query: "feature" } as const; const queried = await manager.load(queriedTarget, mock.client); - expect(queried?.branches.map((branch) => branch.name)).toEqual(["feature/a"]); + expect(queried?.refs.map((branch) => branch.name)).toEqual(["feature/a"]); expect(manager.getSnapshot(TARGET).data).toBeNull(); - expect(manager.getSnapshot(queriedTarget).data?.branches.map((branch) => branch.name)).toEqual([ + expect(manager.getSnapshot(queriedTarget).data?.refs.map((branch) => branch.name)).toEqual([ "feature/a", ]); }); it("returns cached data when no client is available", async () => { - const manager = createGitBranchManager({ + const manager = createVcsRefManager({ getRegistry: () => atomRegistry, getClient: () => null, }); - atomRegistry.set(gitBranchStateAtom("env-local:/repo:"), { + atomRegistry.set(vcsRefStateAtom("env-local:/repo:"), { data: FIRST_PAGE, isPending: false, error: null, @@ -150,7 +160,7 @@ describe("createGitBranchManager", () => { it("resets state", async () => { const mock = createMockClient(); - const manager = createGitBranchManager({ + const manager = createVcsRefManager({ getRegistry: () => atomRegistry, getClient: () => mock.client, }); @@ -158,14 +168,14 @@ describe("createGitBranchManager", () => { await manager.load(TARGET, mock.client); manager.reset(); - expect(manager.getSnapshot(TARGET)).toEqual(EMPTY_GIT_BRANCH_STATE); + expect(manager.getSnapshot(TARGET)).toEqual(EMPTY_VCS_REF_STATE); }); it("watches branches with a ref-counted client-change subscription", async () => { const mock = createMockClient(); let listener: () => void = noop; const unsubscribe = vi.fn(); - const manager = createGitBranchManager({ + const manager = createVcsRefManager({ getRegistry: () => atomRegistry, getClient: () => mock.client, subscribeClientChanges: (nextListener) => { @@ -191,4 +201,66 @@ describe("createGitBranchManager", () => { secondUnwatch(); expect(unsubscribe).toHaveBeenCalledTimes(1); }); + + it("swallows watched refresh failures after storing error state", async () => { + const refreshError = new Error("backend unavailable"); + const listRefs = vi.fn(async () => { + throw refreshError; + }); + const onBackgroundError = vi.fn(); + const manager = createVcsRefManager({ + getRegistry: () => atomRegistry, + getClient: () => ({ listRefs }), + onBackgroundError, + }); + + manager.watch(TARGET); + await Promise.resolve(); + await Promise.resolve(); + + await vi.waitFor(() => { + expect(manager.getSnapshot(TARGET)).toEqual({ + data: null, + isPending: false, + error: "backend unavailable", + }); + expect(onBackgroundError).toHaveBeenCalledWith(refreshError); + }); + }); + + it("starts a new watched refresh when the client is replaced while a load is in flight", async () => { + const firstLoad = deferred(); + const secondLoad = deferred(); + const firstListRefs = vi.fn(() => firstLoad.promise); + const secondListRefs = vi.fn(() => secondLoad.promise); + const firstClient = { listRefs: firstListRefs } satisfies VcsRefClient; + const secondClient = { listRefs: secondListRefs } satisfies VcsRefClient; + let currentClient: VcsRefClient = firstClient; + let listener: () => void = noop; + const manager = createVcsRefManager({ + getRegistry: () => atomRegistry, + getClient: () => currentClient, + subscribeClientChanges: (nextListener) => { + listener = nextListener; + return noop; + }, + }); + + manager.watch(TARGET); + await Promise.resolve(); + expect(firstListRefs).toHaveBeenCalledTimes(1); + + currentClient = secondClient; + listener(); + await Promise.resolve(); + expect(secondListRefs).toHaveBeenCalledTimes(1); + + secondLoad.resolve(SECOND_PAGE); + await secondLoad.promise; + expect(manager.getSnapshot(TARGET).data).toEqual(SECOND_PAGE); + + firstLoad.resolve(FIRST_PAGE); + await firstLoad.promise; + expect(manager.getSnapshot(TARGET).data).toEqual(SECOND_PAGE); + }); }); diff --git a/packages/client-runtime/src/gitBranchState.ts b/packages/client-runtime/src/vcsRefState.ts similarity index 54% rename from packages/client-runtime/src/gitBranchState.ts rename to packages/client-runtime/src/vcsRefState.ts index 7753b341fb..692d8d53e9 100644 --- a/packages/client-runtime/src/gitBranchState.ts +++ b/packages/client-runtime/src/vcsRefState.ts @@ -1,59 +1,57 @@ import type { EnvironmentId, - GitBranch, - GitListBranchesInput, - GitListBranchesResult, + VcsListRefsInput, + VcsListRefsResult, + VcsRef as ContractVcsRef, } from "@t3tools/contracts"; import { Atom, type AtomRegistry } from "effect/unstable/reactivity"; import type { WsRpcClient } from "./wsRpcClient.ts"; -export interface GitBranchTarget { +export interface VcsRefTarget { readonly environmentId: EnvironmentId | null; readonly cwd: string | null; readonly query?: string | null; } -export interface GitBranchState { - readonly data: GitListBranchesResult | null; +export interface VcsRefState { + readonly data: VcsListRefsResult | null; readonly isPending: boolean; readonly error: string | null; } -export type GitBranchClient = Pick; +export type VcsRef = ContractVcsRef; +export type VcsRefClient = Pick; -export const EMPTY_GIT_BRANCH_STATE = Object.freeze({ +export const EMPTY_VCS_REF_STATE = Object.freeze({ data: null, isPending: false, error: null, }); -const INITIAL_GIT_BRANCH_STATE = Object.freeze({ +const INITIAL_VCS_REF_STATE = Object.freeze({ data: null, isPending: true, error: null, }); -const knownGitBranchKeys = new Set(); +const knownVcsRefKeys = new Set(); -export const gitBranchStateAtom = Atom.family((key: string) => { - knownGitBranchKeys.add(key); - return Atom.make(EMPTY_GIT_BRANCH_STATE).pipe( - Atom.keepAlive, - Atom.withLabel(`git-branches:${key}`), - ); +export const vcsRefStateAtom = Atom.family((key: string) => { + knownVcsRefKeys.add(key); + return Atom.make(EMPTY_VCS_REF_STATE).pipe(Atom.keepAlive, Atom.withLabel(`vcs-refs:${key}`)); }); -export const EMPTY_GIT_BRANCH_ATOM = Atom.make(EMPTY_GIT_BRANCH_STATE).pipe( +export const EMPTY_VCS_REF_ATOM = Atom.make(EMPTY_VCS_REF_STATE).pipe( Atom.keepAlive, - Atom.withLabel("git-branches:null"), + Atom.withLabel("vcs-refs:null"), ); function normalizeQuery(query: string | null | undefined): string { return query?.trim() ?? ""; } -export function getGitBranchTargetKey(target: GitBranchTarget): string | null { +export function getVcsRefTargetKey(target: VcsRefTarget): string | null { if (target.environmentId === null || target.cwd === null) { return null; } @@ -62,14 +60,14 @@ export function getGitBranchTargetKey(target: GitBranchTarget): string | null { } function toErrorMessage(error: unknown): string { - return error instanceof Error ? error.message : "Failed to load branches."; + return error instanceof Error ? error.message : "Failed to load refs."; } -function mergeBranches( - previous: ReadonlyArray, - next: ReadonlyArray, -): ReadonlyArray { - const merged = new Map(); +function mergeRefs( + previous: ReadonlyArray, + next: ReadonlyArray, +): ReadonlyArray { + const merged = new Map(); for (const branch of previous) { merged.set(branch.name, branch); } @@ -79,11 +77,12 @@ function mergeBranches( return [...merged.values()]; } -export interface GitBranchManagerConfig { +export interface VcsRefManagerConfig { readonly getRegistry: () => AtomRegistry.AtomRegistry; - readonly getClient: (environmentId: EnvironmentId) => GitBranchClient | null; + readonly getClient: (environmentId: EnvironmentId) => VcsRefClient | null; readonly subscribeClientChanges?: (listener: () => void) => () => void; readonly watchLimit?: number; + readonly onBackgroundError?: (error: unknown) => void; } interface WatchedEntry { @@ -93,35 +92,50 @@ interface WatchedEntry { const NOOP: () => void = () => undefined; -export function createGitBranchManager(config: GitBranchManagerConfig) { - const inFlight = new Map>(); +export function createVcsRefManager(config: VcsRefManagerConfig) { + const inFlight = new Map< + string, + { + readonly client: VcsRefClient; + readonly promise: Promise; + } + >(); + const loadVersions = new Map(); const watched = new Map(); const watchLoadOptions = config.watchLimit === undefined ? undefined : { limit: config.watchLimit }; - function getSnapshot(target: GitBranchTarget): GitBranchState { - const targetKey = getGitBranchTargetKey(target); - if (targetKey === null) { - return EMPTY_GIT_BRANCH_STATE; - } - return config.getRegistry().get(gitBranchStateAtom(targetKey)); + function getLoadVersion(targetKey: string): number { + return loadVersions.get(targetKey) ?? 0; } - function setState(targetKey: string, nextState: GitBranchState): void { - config.getRegistry().set(gitBranchStateAtom(targetKey), nextState); + function bumpLoadVersion(targetKey: string): number { + const next = getLoadVersion(targetKey) + 1; + loadVersions.set(targetKey, next); + return next; + } + + function getSnapshot(target: VcsRefTarget): VcsRefState { + const targetKey = getVcsRefTargetKey(target); + if (targetKey === null) { + return EMPTY_VCS_REF_STATE; + } + return config.getRegistry().get(vcsRefStateAtom(targetKey)); + } + + function setState(targetKey: string, nextState: VcsRefState): void { + config.getRegistry().set(vcsRefStateAtom(targetKey), nextState); } function markPending(targetKey: string): void { - const current = config.getRegistry().get(gitBranchStateAtom(targetKey)); + const current = config.getRegistry().get(vcsRefStateAtom(targetKey)); setState( targetKey, - current.data === null - ? INITIAL_GIT_BRANCH_STATE - : { ...current, isPending: true, error: null }, + current.data === null ? INITIAL_VCS_REF_STATE : { ...current, isPending: true, error: null }, ); } - function setData(targetKey: string, data: GitListBranchesResult): void { + function setData(targetKey: string, data: VcsListRefsResult): void { setState(targetKey, { data, isPending: false, @@ -130,7 +144,7 @@ export function createGitBranchManager(config: GitBranchManagerConfig) { } function setError(targetKey: string, error: unknown): void { - const current = config.getRegistry().get(gitBranchStateAtom(targetKey)); + const current = config.getRegistry().get(vcsRefStateAtom(targetKey)); setState(targetKey, { data: current.data, isPending: false, @@ -139,15 +153,15 @@ export function createGitBranchManager(config: GitBranchManagerConfig) { } async function load( - target: GitBranchTarget, - client?: GitBranchClient, + target: VcsRefTarget, + client?: VcsRefClient, options?: { readonly cursor?: number; readonly limit?: number; readonly append?: boolean; }, - ): Promise { - const targetKey = getGitBranchTargetKey(target); + ): Promise { + const targetKey = getVcsRefTargetKey(target); if (targetKey === null || target.environmentId === null || target.cwd === null) { return null; } @@ -159,51 +173,72 @@ export function createGitBranchManager(config: GitBranchManagerConfig) { const inFlightKey = `${targetKey}:${options?.cursor ?? "start"}:${options?.append ? "append" : "replace"}`; const existing = inFlight.get(inFlightKey); - if (existing) { - return existing; + if (existing && existing.client === resolved) { + return existing.promise; } markPending(targetKey); + const loadVersion = bumpLoadVersion(targetKey); const current = getSnapshot(target).data; - const request: GitListBranchesInput = { + const request: VcsListRefsInput = { cwd: target.cwd, ...(normalizeQuery(target.query).length > 0 ? { query: normalizeQuery(target.query) } : {}), ...(options?.cursor !== undefined ? { cursor: options.cursor } : {}), ...(options?.limit !== undefined ? { limit: options.limit } : {}), }; - const promise = resolved.listBranches(request).then( + const promise = resolved.listRefs(request).then( (result) => { const nextData = options?.append && current ? { ...result, - branches: mergeBranches(current.branches, result.branches), + refs: mergeRefs(current.refs, result.refs), } : result; - setData(targetKey, nextData); + if (getLoadVersion(targetKey) === loadVersion) { + setData(targetKey, nextData); + } return nextData; }, (error) => { - setError(targetKey, error); + if (getLoadVersion(targetKey) === loadVersion) { + setError(targetKey, error); + } throw error; }, ); - inFlight.set(inFlightKey, promise); + inFlight.set(inFlightKey, { client: resolved, promise }); try { return await promise; } finally { - inFlight.delete(inFlightKey); + if (inFlight.get(inFlightKey)?.promise === promise) { + inFlight.delete(inFlightKey); + } } } + function loadInBackground( + target: VcsRefTarget, + client: VcsRefClient, + options?: { + readonly cursor?: number; + readonly limit?: number; + readonly append?: boolean; + }, + ): void { + void load(target, client, options).catch((error: unknown) => { + config.onBackgroundError?.(error); + }); + } + async function loadNext( - target: GitBranchTarget, - client?: GitBranchClient, + target: VcsRefTarget, + client?: VcsRefClient, options?: { readonly limit?: number }, - ): Promise { + ): Promise { const current = getSnapshot(target).data; if (!current?.nextCursor && current?.nextCursor !== 0) { return current ?? null; @@ -216,8 +251,8 @@ export function createGitBranchManager(config: GitBranchManagerConfig) { }); } - function watch(target: GitBranchTarget, client?: GitBranchClient): () => void { - const targetKey = getGitBranchTargetKey(target); + function watch(target: VcsRefTarget, client?: VcsRefClient): () => void { + const targetKey = getVcsRefTargetKey(target); if (targetKey === null || target.environmentId === null || target.cwd === null) { return NOOP; } @@ -231,10 +266,10 @@ export function createGitBranchManager(config: GitBranchManagerConfig) { let teardown: () => void; if (client) { - void load(target, client, watchLoadOptions); + loadInBackground(target, client, watchLoadOptions); teardown = NOOP; } else if (config.subscribeClientChanges) { - let currentClient: GitBranchClient | null = null; + let currentClient: VcsRefClient | null = null; const sync = () => { const resolved = config.getClient(target.environmentId!); if (!resolved) { @@ -246,7 +281,7 @@ export function createGitBranchManager(config: GitBranchManagerConfig) { } currentClient = resolved; - void load(target, resolved, watchLoadOptions); + loadInBackground(target, resolved, watchLoadOptions); }; const unsubscribe = config.subscribeClientChanges(sync); @@ -257,7 +292,7 @@ export function createGitBranchManager(config: GitBranchManagerConfig) { if (!resolved) { return NOOP; } - void load(target, resolved, watchLoadOptions); + loadInBackground(target, resolved, watchLoadOptions); teardown = NOOP; } @@ -280,17 +315,17 @@ export function createGitBranchManager(config: GitBranchManagerConfig) { watched.delete(targetKey); } - function invalidate(target?: GitBranchTarget): void { + function invalidate(target?: VcsRefTarget): void { if (target) { - const targetKey = getGitBranchTargetKey(target); + const targetKey = getVcsRefTargetKey(target); if (targetKey !== null) { - setState(targetKey, EMPTY_GIT_BRANCH_STATE); + setState(targetKey, EMPTY_VCS_REF_STATE); } return; } - for (const key of knownGitBranchKeys) { - setState(key, EMPTY_GIT_BRANCH_STATE); + for (const key of knownVcsRefKeys) { + setState(key, EMPTY_VCS_REF_STATE); } } @@ -299,6 +334,8 @@ export function createGitBranchManager(config: GitBranchManagerConfig) { entry.teardown(); } watched.clear(); + inFlight.clear(); + loadVersions.clear(); invalidate(); }