Rename branch state to VCS refs
- Switch mobile and client-runtime state to the generic VcsRef API - Preserve background refreshes with client change handling and errors
This commit is contained in:
1 parent
54964f57ae
commit
c0a2f00f50
8 files changed
+222
-113
No files matched your search
@@ -15,20 +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, type GitBranch } 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;
|
||||
@@ -38,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) {
|
||||
@@ -72,7 +72,7 @@ type NewTaskFlowContextValue = {
|
||||
readonly submitting: boolean;
|
||||
readonly branchQuery: string;
|
||||
readonly branchesLoading: boolean;
|
||||
readonly availableBranches: ReadonlyArray<GitBranch>;
|
||||
readonly availableBranches: ReadonlyArray<VcsRef>;
|
||||
readonly runtimeMode: RuntimeMode;
|
||||
readonly interactionMode: ProviderInteractionMode;
|
||||
readonly effort: ClaudeAgentEffort;
|
||||
@@ -88,13 +88,13 @@ type NewTaskFlowContextValue = {
|
||||
readonly selectedModel: ModelSelection | null;
|
||||
readonly selectedModelOption: ModelOption | null;
|
||||
readonly providerGroups: ReadonlyArray<ProviderGroup>;
|
||||
readonly filteredBranches: ReadonlyArray<GitBranch>;
|
||||
readonly filteredBranches: ReadonlyArray<VcsRef>;
|
||||
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<DraftComposerImageAttachment>) => void;
|
||||
readonly appendAttachments: (attachments: ReadonlyArray<DraftComposerImageAttachment>) => void;
|
||||
@@ -305,7 +305,7 @@ 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(
|
||||
() =>
|
||||
@@ -341,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,
|
||||
@@ -356,7 +356,7 @@ 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,
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import { useCallback } from "react";
|
||||
|
||||
import { EnvironmentScopedProjectShell, type GitBranch } from "@t3tools/client-runtime";
|
||||
import { EnvironmentScopedProjectShell, type VcsRef } from "@t3tools/client-runtime";
|
||||
import {
|
||||
CommandId,
|
||||
DEFAULT_PROVIDER_INTERACTION_MODE,
|
||||
@@ -18,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,
|
||||
@@ -185,14 +185,14 @@ export function useProjectActions() {
|
||||
);
|
||||
|
||||
const onListProjectBranches = useCallback(
|
||||
async (project: EnvironmentScopedProjectShell): Promise<ReadonlyArray<GitBranch>> => {
|
||||
async (project: EnvironmentScopedProjectShell): Promise<ReadonlyArray<VcsRef>> => {
|
||||
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.vcs,
|
||||
{ limit: 100 },
|
||||
@@ -231,7 +231,7 @@ export function useProjectActions() {
|
||||
newRefName: sanitizeFeatureBranchName(nextWorktree.newBranch),
|
||||
path: null,
|
||||
});
|
||||
gitBranchManager.invalidate({
|
||||
vcsRefManager.invalidate({
|
||||
environmentId: project.environmentId,
|
||||
cwd: project.workspaceRoot,
|
||||
query: null,
|
||||
|
||||
@@ -3,7 +3,7 @@ import { useCallback, useEffect } from "react";
|
||||
import {
|
||||
EnvironmentScopedProjectShell,
|
||||
EnvironmentScopedThreadShell,
|
||||
type GitBranch,
|
||||
type VcsRef,
|
||||
type GitActionRequestInput,
|
||||
} from "@t3tools/client-runtime";
|
||||
import { CommandId, type GitRunStackedActionResult } from "@t3tools/contracts";
|
||||
@@ -16,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";
|
||||
@@ -126,7 +126,7 @@ export function useSelectedThreadGitActions() {
|
||||
[selectedThread, selectedThreadCwd, selectedThreadProject],
|
||||
);
|
||||
|
||||
const refreshSelectedThreadBranches = useCallback(async (): Promise<ReadonlyArray<GitBranch>> => {
|
||||
const refreshSelectedThreadBranches = useCallback(async (): Promise<ReadonlyArray<VcsRef>> => {
|
||||
if (!selectedThread || !selectedThreadProject || !selectedThreadGitRootCwd) {
|
||||
return [];
|
||||
}
|
||||
@@ -137,7 +137,7 @@ export function useSelectedThreadGitActions() {
|
||||
}
|
||||
|
||||
try {
|
||||
const result = await gitBranchManager.load(
|
||||
const result = await vcsRefManager.load(
|
||||
{ environmentId: selectedThread.environmentId, cwd: selectedThreadGitRootCwd, query: null },
|
||||
client.vcs,
|
||||
{ limit: 100 },
|
||||
@@ -169,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,
|
||||
|
||||
@@ -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?.refs ?? []).filter(
|
||||
|
||||
@@ -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;
|
||||
}
|
||||
@@ -10,7 +10,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";
|
||||
|
||||
+88
-16
@@ -3,11 +3,11 @@ 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();
|
||||
|
||||
@@ -40,7 +40,7 @@ const SECOND_PAGE: VcsListRefsResult = {
|
||||
};
|
||||
|
||||
function createMockClient() {
|
||||
const listRefs = vi.fn(async (input: Parameters<GitBranchClient["listRefs"]>[0]) => {
|
||||
const listRefs = vi.fn(async (input: Parameters<VcsRefClient["listRefs"]>[0]) => {
|
||||
if (input.query === "feature") {
|
||||
return {
|
||||
...FIRST_PAGE,
|
||||
@@ -58,19 +58,29 @@ function createMockClient() {
|
||||
});
|
||||
|
||||
return {
|
||||
client: { listRefs } satisfies GitBranchClient,
|
||||
client: { listRefs } satisfies VcsRefClient,
|
||||
listRefs,
|
||||
};
|
||||
}
|
||||
|
||||
describe("createGitBranchManager", () => {
|
||||
function deferred<T>() {
|
||||
let resolve!: (value: T) => void;
|
||||
let reject!: (error: unknown) => void;
|
||||
const promise = new Promise<T>((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,
|
||||
});
|
||||
@@ -94,7 +104,7 @@ describe("createGitBranchManager", () => {
|
||||
|
||||
it("loads the next page and appends branches", async () => {
|
||||
const mock = createMockClient();
|
||||
const manager = createGitBranchManager({
|
||||
const manager = createVcsRefManager({
|
||||
getRegistry: () => atomRegistry,
|
||||
getClient: () => mock.client,
|
||||
});
|
||||
@@ -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,
|
||||
});
|
||||
@@ -134,12 +144,12 @@ describe("createGitBranchManager", () => {
|
||||
});
|
||||
|
||||
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<VcsListRefsResult>();
|
||||
const secondLoad = deferred<VcsListRefsResult>();
|
||||
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);
|
||||
});
|
||||
});
|
||||
+95
-59
@@ -2,59 +2,56 @@ import type {
|
||||
EnvironmentId,
|
||||
VcsListRefsInput,
|
||||
VcsListRefsResult,
|
||||
VcsRef,
|
||||
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 {
|
||||
export interface VcsRefState {
|
||||
readonly data: VcsListRefsResult | null;
|
||||
readonly isPending: boolean;
|
||||
readonly error: string | null;
|
||||
}
|
||||
|
||||
export type GitBranch = VcsRef;
|
||||
export type GitBranchClient = Pick<WsRpcClient["vcs"], "listRefs">;
|
||||
export type VcsRef = ContractVcsRef;
|
||||
export type VcsRefClient = Pick<WsRpcClient["vcs"], "listRefs">;
|
||||
|
||||
export const EMPTY_GIT_BRANCH_STATE = Object.freeze<GitBranchState>({
|
||||
export const EMPTY_VCS_REF_STATE = Object.freeze<VcsRefState>({
|
||||
data: null,
|
||||
isPending: false,
|
||||
error: null,
|
||||
});
|
||||
|
||||
const INITIAL_GIT_BRANCH_STATE = Object.freeze<GitBranchState>({
|
||||
const INITIAL_VCS_REF_STATE = Object.freeze<VcsRefState>({
|
||||
data: null,
|
||||
isPending: true,
|
||||
error: null,
|
||||
});
|
||||
|
||||
const knownGitBranchKeys = new Set<string>();
|
||||
const knownVcsRefKeys = new Set<string>();
|
||||
|
||||
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;
|
||||
}
|
||||
@@ -63,10 +60,10 @@ 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(
|
||||
function mergeRefs(
|
||||
previous: ReadonlyArray<VcsRef>,
|
||||
next: ReadonlyArray<VcsRef>,
|
||||
): ReadonlyArray<VcsRef> {
|
||||
@@ -80,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 {
|
||||
@@ -94,31 +92,46 @@ interface WatchedEntry {
|
||||
|
||||
const NOOP: () => void = () => undefined;
|
||||
|
||||
export function createGitBranchManager(config: GitBranchManagerConfig) {
|
||||
const inFlight = new Map<string, Promise<VcsListRefsResult | null>>();
|
||||
export function createVcsRefManager(config: VcsRefManagerConfig) {
|
||||
const inFlight = new Map<
|
||||
string,
|
||||
{
|
||||
readonly client: VcsRefClient;
|
||||
readonly promise: Promise<VcsListRefsResult | null>;
|
||||
}
|
||||
>();
|
||||
const loadVersions = new Map<string, number>();
|
||||
const watched = new Map<string, WatchedEntry>();
|
||||
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 },
|
||||
);
|
||||
}
|
||||
|
||||
@@ -131,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,
|
||||
@@ -140,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<VcsListRefsResult | null> {
|
||||
const targetKey = getGitBranchTargetKey(target);
|
||||
const targetKey = getVcsRefTargetKey(target);
|
||||
if (targetKey === null || target.environmentId === null || target.cwd === null) {
|
||||
return null;
|
||||
}
|
||||
@@ -160,11 +173,12 @@ 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: VcsListRefsInput = {
|
||||
@@ -180,29 +194,49 @@ export function createGitBranchManager(config: GitBranchManagerConfig) {
|
||||
options?.append && current
|
||||
? {
|
||||
...result,
|
||||
refs: mergeBranches(current.refs, result.refs),
|
||||
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<VcsListRefsResult | null> {
|
||||
const current = getSnapshot(target).data;
|
||||
@@ -217,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;
|
||||
}
|
||||
@@ -232,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) {
|
||||
@@ -247,7 +281,7 @@ export function createGitBranchManager(config: GitBranchManagerConfig) {
|
||||
}
|
||||
|
||||
currentClient = resolved;
|
||||
void load(target, resolved, watchLoadOptions);
|
||||
loadInBackground(target, resolved, watchLoadOptions);
|
||||
};
|
||||
|
||||
const unsubscribe = config.subscribeClientChanges(sync);
|
||||
@@ -258,7 +292,7 @@ export function createGitBranchManager(config: GitBranchManagerConfig) {
|
||||
if (!resolved) {
|
||||
return NOOP;
|
||||
}
|
||||
void load(target, resolved, watchLoadOptions);
|
||||
loadInBackground(target, resolved, watchLoadOptions);
|
||||
teardown = NOOP;
|
||||
}
|
||||
|
||||
@@ -281,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);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -300,6 +334,8 @@ export function createGitBranchManager(config: GitBranchManagerConfig) {
|
||||
entry.teardown();
|
||||
}
|
||||
watched.clear();
|
||||
inFlight.clear();
|
||||
loadVersions.clear();
|
||||
invalidate();
|
||||
}
|
||||
|
||||
Reference in new issue
Block a user