Compare commits
5
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
f8b6e5b330 | ||
|
|
744f74442a | ||
|
|
23467b7b1f | ||
|
|
022d3d2f3e | ||
|
|
3bb72fe119 |
No files matched your search
@@ -1,6 +1,8 @@
|
|||||||
import type { GitBranch } from "@t3tools/contracts";
|
import { useAtomRefresh, useAtomSet, useAtomValue } from "@effect/atom-react";
|
||||||
import { useQuery, useQueryClient } from "@tanstack/react-query";
|
import { type GitBranch } from "@t3tools/contracts";
|
||||||
import { useVirtualizer } from "@tanstack/react-virtual";
|
import { useVirtualizer } from "@tanstack/react-virtual";
|
||||||
|
import * as Option from "effect/Option";
|
||||||
|
import { AsyncResult } from "effect/unstable/reactivity";
|
||||||
import { ChevronDownIcon } from "lucide-react";
|
import { ChevronDownIcon } from "lucide-react";
|
||||||
import {
|
import {
|
||||||
type CSSProperties,
|
type CSSProperties,
|
||||||
@@ -14,14 +16,14 @@ import {
|
|||||||
useTransition,
|
useTransition,
|
||||||
} from "react";
|
} from "react";
|
||||||
|
|
||||||
import {
|
|
||||||
gitBranchesQueryOptions,
|
|
||||||
gitQueryKeys,
|
|
||||||
gitStatusQueryOptions,
|
|
||||||
invalidateGitQueries,
|
|
||||||
} from "../lib/gitReactQuery";
|
|
||||||
import { readNativeApi } from "../nativeApi";
|
|
||||||
import { parsePullRequestReference } from "../pullRequestReference";
|
import { parsePullRequestReference } from "../pullRequestReference";
|
||||||
|
import { REACTIVITY_KEYS } from "../rpc/client";
|
||||||
|
import {
|
||||||
|
gitBranchesAtom,
|
||||||
|
gitCheckoutMutationAtom,
|
||||||
|
gitCreateBranchMutationAtom,
|
||||||
|
gitStatusAtom,
|
||||||
|
} from "../rpc/gitAtoms";
|
||||||
import {
|
import {
|
||||||
dedupeRemoteBranchesWithLocalMatches,
|
dedupeRemoteBranchesWithLocalMatches,
|
||||||
deriveLocalBranchNameFromRemoteRef,
|
deriveLocalBranchNameFromRemoteRef,
|
||||||
@@ -84,19 +86,23 @@ export function BranchToolbarBranchSelector({
|
|||||||
onCheckoutPullRequestRequest,
|
onCheckoutPullRequestRequest,
|
||||||
onComposerFocusRequest,
|
onComposerFocusRequest,
|
||||||
}: BranchToolbarBranchSelectorProps) {
|
}: BranchToolbarBranchSelectorProps) {
|
||||||
const queryClient = useQueryClient();
|
|
||||||
const [isBranchMenuOpen, setIsBranchMenuOpen] = useState(false);
|
const [isBranchMenuOpen, setIsBranchMenuOpen] = useState(false);
|
||||||
const [branchQuery, setBranchQuery] = useState("");
|
const [branchQuery, setBranchQuery] = useState("");
|
||||||
const deferredBranchQuery = useDeferredValue(branchQuery);
|
const deferredBranchQuery = useDeferredValue(branchQuery);
|
||||||
|
const branchesResult = useAtomValue(gitBranchesAtom(branchCwd));
|
||||||
const branchesQuery = useQuery(gitBranchesQueryOptions(branchCwd));
|
const branchStatusResult = useAtomValue(gitStatusAtom(branchCwd));
|
||||||
const branchStatusQuery = useQuery(gitStatusQueryOptions(branchCwd));
|
const refreshBranches = useAtomRefresh(gitBranchesAtom(branchCwd));
|
||||||
|
const refreshBranchStatus = useAtomRefresh(gitStatusAtom(branchCwd));
|
||||||
|
const checkoutBranch = useAtomSet(gitCheckoutMutationAtom, { mode: "promise" });
|
||||||
|
const createGitBranch = useAtomSet(gitCreateBranchMutationAtom, { mode: "promise" });
|
||||||
|
const branchesData = Option.getOrUndefined(AsyncResult.value(branchesResult));
|
||||||
|
const branchStatus = Option.getOrUndefined(AsyncResult.value(branchStatusResult));
|
||||||
const branches = useMemo(
|
const branches = useMemo(
|
||||||
() => dedupeRemoteBranchesWithLocalMatches(branchesQuery.data?.branches ?? []),
|
() => dedupeRemoteBranchesWithLocalMatches(branchesData?.branches ?? []),
|
||||||
[branchesQuery.data?.branches],
|
[branchesData?.branches],
|
||||||
);
|
);
|
||||||
const currentGitBranch =
|
const currentGitBranch =
|
||||||
branchStatusQuery.data?.branch ?? branches.find((branch) => branch.current)?.name ?? null;
|
branchStatus?.branch ?? branches.find((branch) => branch.current)?.name ?? null;
|
||||||
const canonicalActiveBranch = resolveBranchToolbarValue({
|
const canonicalActiveBranch = resolveBranchToolbarValue({
|
||||||
envMode: effectiveEnvMode,
|
envMode: effectiveEnvMode,
|
||||||
activeWorktreePath,
|
activeWorktreePath,
|
||||||
@@ -155,18 +161,18 @@ export function BranchToolbarBranchSelector({
|
|||||||
(_currentBranch: string | null, optimisticBranch: string | null) => optimisticBranch,
|
(_currentBranch: string | null, optimisticBranch: string | null) => optimisticBranch,
|
||||||
);
|
);
|
||||||
const [isBranchActionPending, startBranchActionTransition] = useTransition();
|
const [isBranchActionPending, startBranchActionTransition] = useTransition();
|
||||||
|
const isBranchesLoading =
|
||||||
|
branches.length === 0 && (AsyncResult.isInitial(branchesResult) || branchesResult.waiting);
|
||||||
const shouldVirtualizeBranchList = filteredBranchPickerItems.length > 40;
|
const shouldVirtualizeBranchList = filteredBranchPickerItems.length > 40;
|
||||||
|
|
||||||
const runBranchAction = (action: () => Promise<void>) => {
|
const runBranchAction = (action: () => Promise<void>) => {
|
||||||
startBranchActionTransition(async () => {
|
startBranchActionTransition(async () => {
|
||||||
await action().catch(() => undefined);
|
await action().catch(() => undefined);
|
||||||
await invalidateGitQueries(queryClient).catch(() => undefined);
|
|
||||||
});
|
});
|
||||||
};
|
};
|
||||||
|
|
||||||
const selectBranch = (branch: GitBranch) => {
|
const selectBranch = (branch: GitBranch) => {
|
||||||
const api = readNativeApi();
|
if (!branchCwd || isBranchActionPending) return;
|
||||||
if (!api || !branchCwd || isBranchActionPending) return;
|
|
||||||
|
|
||||||
// In new-worktree mode, selecting a branch sets the base branch.
|
// In new-worktree mode, selecting a branch sets the base branch.
|
||||||
if (isSelectingWorktreeBase) {
|
if (isSelectingWorktreeBase) {
|
||||||
@@ -200,8 +206,13 @@ export function BranchToolbarBranchSelector({
|
|||||||
runBranchAction(async () => {
|
runBranchAction(async () => {
|
||||||
setOptimisticBranch(selectedBranchName);
|
setOptimisticBranch(selectedBranchName);
|
||||||
try {
|
try {
|
||||||
await api.git.checkout({ cwd: selectionTarget.checkoutCwd, branch: branch.name });
|
await checkoutBranch({
|
||||||
await invalidateGitQueries(queryClient);
|
payload: {
|
||||||
|
cwd: selectionTarget.checkoutCwd,
|
||||||
|
branch: branch.name,
|
||||||
|
},
|
||||||
|
reactivityKeys: [REACTIVITY_KEYS.git(selectionTarget.checkoutCwd)],
|
||||||
|
});
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
toastManager.add({
|
toastManager.add({
|
||||||
type: "error",
|
type: "error",
|
||||||
@@ -211,23 +222,14 @@ export function BranchToolbarBranchSelector({
|
|||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
let nextBranchName = selectedBranchName;
|
setOptimisticBranch(selectedBranchName);
|
||||||
if (branch.isRemote) {
|
onSetThreadBranch(selectedBranchName, selectionTarget.nextWorktreePath);
|
||||||
const status = await api.git.status({ cwd: branchCwd }).catch(() => null);
|
|
||||||
if (status?.branch) {
|
|
||||||
nextBranchName = status.branch;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
setOptimisticBranch(nextBranchName);
|
|
||||||
onSetThreadBranch(nextBranchName, selectionTarget.nextWorktreePath);
|
|
||||||
});
|
});
|
||||||
};
|
};
|
||||||
|
|
||||||
const createBranch = (rawName: string) => {
|
const createBranch = (rawName: string) => {
|
||||||
const name = rawName.trim();
|
const name = rawName.trim();
|
||||||
const api = readNativeApi();
|
if (!branchCwd || !name || isBranchActionPending) return;
|
||||||
if (!api || !branchCwd || !name || isBranchActionPending) return;
|
|
||||||
|
|
||||||
setIsBranchMenuOpen(false);
|
setIsBranchMenuOpen(false);
|
||||||
onComposerFocusRequest?.();
|
onComposerFocusRequest?.();
|
||||||
@@ -236,9 +238,14 @@ export function BranchToolbarBranchSelector({
|
|||||||
setOptimisticBranch(name);
|
setOptimisticBranch(name);
|
||||||
|
|
||||||
try {
|
try {
|
||||||
await api.git.createBranch({ cwd: branchCwd, branch: name });
|
await createGitBranch({
|
||||||
|
payload: { cwd: branchCwd, branch: name },
|
||||||
|
});
|
||||||
try {
|
try {
|
||||||
await api.git.checkout({ cwd: branchCwd, branch: name });
|
await checkoutBranch({
|
||||||
|
payload: { cwd: branchCwd, branch: name },
|
||||||
|
reactivityKeys: [REACTIVITY_KEYS.git(branchCwd)],
|
||||||
|
});
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
toastManager.add({
|
toastManager.add({
|
||||||
type: "error",
|
type: "error",
|
||||||
@@ -287,11 +294,12 @@ export function BranchToolbarBranchSelector({
|
|||||||
setBranchQuery("");
|
setBranchQuery("");
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
void queryClient.invalidateQueries({
|
if (branchCwd) {
|
||||||
queryKey: gitQueryKeys.branches(branchCwd),
|
refreshBranches();
|
||||||
});
|
refreshBranchStatus();
|
||||||
|
}
|
||||||
},
|
},
|
||||||
[branchCwd, queryClient],
|
[branchCwd, refreshBranchStatus, refreshBranches],
|
||||||
);
|
);
|
||||||
|
|
||||||
const branchListScrollElementRef = useRef<HTMLDivElement | null>(null);
|
const branchListScrollElementRef = useRef<HTMLDivElement | null>(null);
|
||||||
@@ -425,7 +433,7 @@ export function BranchToolbarBranchSelector({
|
|||||||
<ComboboxTrigger
|
<ComboboxTrigger
|
||||||
render={<Button variant="ghost" size="xs" />}
|
render={<Button variant="ghost" size="xs" />}
|
||||||
className="text-muted-foreground/70 hover:text-foreground/80"
|
className="text-muted-foreground/70 hover:text-foreground/80"
|
||||||
disabled={(branchesQuery.isLoading && branches.length === 0) || isBranchActionPending}
|
disabled={isBranchesLoading || isBranchActionPending}
|
||||||
>
|
>
|
||||||
<span className="max-w-[240px] truncate">{triggerLabel}</span>
|
<span className="max-w-[240px] truncate">{triggerLabel}</span>
|
||||||
<ChevronDownIcon />
|
<ChevronDownIcon />
|
||||||
|
|||||||
@@ -32,6 +32,7 @@ import {
|
|||||||
import { isMacPlatform } from "../lib/utils";
|
import { isMacPlatform } from "../lib/utils";
|
||||||
import { __resetNativeApiForTests } from "../nativeApi";
|
import { __resetNativeApiForTests } from "../nativeApi";
|
||||||
import { getRouter } from "../router";
|
import { getRouter } from "../router";
|
||||||
|
import { resetAppAtomRegistryForTests } from "../rpc/atomRegistry";
|
||||||
import { useStore } from "../store";
|
import { useStore } from "../store";
|
||||||
import { BrowserWsRpcHarness, type NormalizedWsRpcRequestBody } from "../../test/wsRpcHarness";
|
import { BrowserWsRpcHarness, type NormalizedWsRpcRequestBody } from "../../test/wsRpcHarness";
|
||||||
import { estimateTimelineMessageHeight } from "./timelineHeight";
|
import { estimateTimelineMessageHeight } from "./timelineHeight";
|
||||||
@@ -1121,6 +1122,7 @@ describe("ChatView timeline estimator parity (full app)", () => {
|
|||||||
},
|
},
|
||||||
});
|
});
|
||||||
__resetNativeApiForTests();
|
__resetNativeApiForTests();
|
||||||
|
resetAppAtomRegistryForTests();
|
||||||
await setViewport(DEFAULT_VIEWPORT);
|
await setViewport(DEFAULT_VIEWPORT);
|
||||||
localStorage.clear();
|
localStorage.clear();
|
||||||
document.body.innerHTML = "";
|
document.body.innerHTML = "";
|
||||||
@@ -1143,6 +1145,7 @@ describe("ChatView timeline estimator parity (full app)", () => {
|
|||||||
afterEach(() => {
|
afterEach(() => {
|
||||||
customWsRpcResolver = null;
|
customWsRpcResolver = null;
|
||||||
document.body.innerHTML = "";
|
document.body.innerHTML = "";
|
||||||
|
resetAppAtomRegistryForTests();
|
||||||
});
|
});
|
||||||
|
|
||||||
it.each(TEXT_VIEWPORT_MATRIX)(
|
it.each(TEXT_VIEWPORT_MATRIX)(
|
||||||
|
|||||||
@@ -1,3 +1,4 @@
|
|||||||
|
import { useAtomSet, useAtomValue } from "@effect/atom-react";
|
||||||
import {
|
import {
|
||||||
type ApprovalRequestId,
|
type ApprovalRequestId,
|
||||||
DEFAULT_MODEL_BY_PROVIDER,
|
DEFAULT_MODEL_BY_PROVIDER,
|
||||||
@@ -21,12 +22,13 @@ import {
|
|||||||
TerminalOpenInput,
|
TerminalOpenInput,
|
||||||
} from "@t3tools/contracts";
|
} from "@t3tools/contracts";
|
||||||
import { applyClaudePromptEffortPrefix, normalizeModelSlug } from "@t3tools/shared/model";
|
import { applyClaudePromptEffortPrefix, normalizeModelSlug } from "@t3tools/shared/model";
|
||||||
|
import * as Option from "effect/Option";
|
||||||
import { truncate } from "@t3tools/shared/String";
|
import { truncate } from "@t3tools/shared/String";
|
||||||
import { useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState } from "react";
|
import { useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState } from "react";
|
||||||
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
|
import { useQuery } from "@tanstack/react-query";
|
||||||
import { useDebouncedValue } from "@tanstack/react-pacer";
|
import { useDebouncedValue } from "@tanstack/react-pacer";
|
||||||
import { useNavigate, useSearch } from "@tanstack/react-router";
|
import { useNavigate, useSearch } from "@tanstack/react-router";
|
||||||
import { gitBranchesQueryOptions, gitCreateWorktreeMutationOptions } from "~/lib/gitReactQuery";
|
import { AsyncResult } from "effect/unstable/reactivity";
|
||||||
import { projectSearchEntriesQueryOptions } from "~/lib/projectReactQuery";
|
import { projectSearchEntriesQueryOptions } from "~/lib/projectReactQuery";
|
||||||
import { isElectron } from "../env";
|
import { isElectron } from "../env";
|
||||||
import { parseDiffRouteSearch, stripDiffSearchParams } from "../diffRouteSearch";
|
import { parseDiffRouteSearch, stripDiffSearchParams } from "../diffRouteSearch";
|
||||||
@@ -106,6 +108,8 @@ import { Separator } from "./ui/separator";
|
|||||||
import { cn, randomUUID } from "~/lib/utils";
|
import { cn, randomUUID } from "~/lib/utils";
|
||||||
import { Tooltip, TooltipPopup, TooltipTrigger } from "./ui/tooltip";
|
import { Tooltip, TooltipPopup, TooltipTrigger } from "./ui/tooltip";
|
||||||
import { toastManager } from "./ui/toast";
|
import { toastManager } from "./ui/toast";
|
||||||
|
import { gitBranchesAtom, gitCreateWorktreeMutationAtom } from "~/rpc/gitAtoms";
|
||||||
|
import { REACTIVITY_KEYS } from "~/rpc/client";
|
||||||
import { decodeProjectScriptKeybindingRule } from "~/lib/projectScriptKeybindings";
|
import { decodeProjectScriptKeybindingRule } from "~/lib/projectScriptKeybindings";
|
||||||
import { type NewProjectScriptInput } from "./ProjectScriptsControl";
|
import { type NewProjectScriptInput } from "./ProjectScriptsControl";
|
||||||
import {
|
import {
|
||||||
@@ -423,8 +427,7 @@ export default function ChatView({ threadId }: ChatViewProps) {
|
|||||||
select: (params) => parseDiffRouteSearch(params),
|
select: (params) => parseDiffRouteSearch(params),
|
||||||
});
|
});
|
||||||
const { resolvedTheme } = useTheme();
|
const { resolvedTheme } = useTheme();
|
||||||
const queryClient = useQueryClient();
|
const createWorktree = useAtomSet(gitCreateWorktreeMutationAtom, { mode: "promise" });
|
||||||
const createWorktreeMutation = useMutation(gitCreateWorktreeMutationOptions({ queryClient }));
|
|
||||||
const composerDraft = useComposerThreadDraft(threadId);
|
const composerDraft = useComposerThreadDraft(threadId);
|
||||||
const prompt = composerDraft.prompt;
|
const prompt = composerDraft.prompt;
|
||||||
const composerImages = composerDraft.images;
|
const composerImages = composerDraft.images;
|
||||||
@@ -1201,7 +1204,8 @@ export default function ChatView({ threadId }: ChatViewProps) {
|
|||||||
(debouncerState) => ({ isPending: debouncerState.isPending }),
|
(debouncerState) => ({ isPending: debouncerState.isPending }),
|
||||||
);
|
);
|
||||||
const effectivePathQuery = pathTriggerQuery.length > 0 ? debouncedPathQuery : "";
|
const effectivePathQuery = pathTriggerQuery.length > 0 ? debouncedPathQuery : "";
|
||||||
const branchesQuery = useQuery(gitBranchesQueryOptions(gitCwd));
|
const branchesResult = useAtomValue(gitBranchesAtom(gitCwd));
|
||||||
|
const branches = Option.getOrUndefined(AsyncResult.value(branchesResult));
|
||||||
const keybindings = useServerKeybindings();
|
const keybindings = useServerKeybindings();
|
||||||
const availableEditors = useServerAvailableEditors();
|
const availableEditors = useServerAvailableEditors();
|
||||||
const modelOptionsByProvider = useMemo(
|
const modelOptionsByProvider = useMemo(
|
||||||
@@ -1338,7 +1342,7 @@ export default function ChatView({ threadId }: ChatViewProps) {
|
|||||||
});
|
});
|
||||||
}, [activeProjectCwd, activeThreadWorktreePath]);
|
}, [activeProjectCwd, activeThreadWorktreePath]);
|
||||||
// Default true while loading to avoid toolbar flicker.
|
// Default true while loading to avoid toolbar flicker.
|
||||||
const isGitRepo = branchesQuery.data?.isRepo ?? true;
|
const isGitRepo = branches?.isRepo ?? true;
|
||||||
const terminalShortcutLabelOptions = useMemo(
|
const terminalShortcutLabelOptions = useMemo(
|
||||||
() => ({
|
() => ({
|
||||||
context: {
|
context: {
|
||||||
@@ -2787,10 +2791,17 @@ export default function ChatView({ threadId }: ChatViewProps) {
|
|||||||
if (baseBranchForWorktree) {
|
if (baseBranchForWorktree) {
|
||||||
beginLocalDispatch({ preparingWorktree: true });
|
beginLocalDispatch({ preparingWorktree: true });
|
||||||
const newBranch = buildTemporaryWorktreeBranchName();
|
const newBranch = buildTemporaryWorktreeBranchName();
|
||||||
const result = await createWorktreeMutation.mutateAsync({
|
const result = await createWorktree({
|
||||||
cwd: activeProject.cwd,
|
payload: {
|
||||||
branch: baseBranchForWorktree,
|
cwd: activeProject.cwd,
|
||||||
newBranch,
|
branch: baseBranchForWorktree,
|
||||||
|
path: null,
|
||||||
|
newBranch,
|
||||||
|
},
|
||||||
|
reactivityKeys: [
|
||||||
|
REACTIVITY_KEYS.git(activeProject.cwd),
|
||||||
|
REACTIVITY_KEYS.project(activeProject.cwd),
|
||||||
|
],
|
||||||
});
|
});
|
||||||
nextThreadBranch = result.worktree.branch;
|
nextThreadBranch = result.worktree.branch;
|
||||||
nextThreadWorktreePath = result.worktree.path;
|
nextThreadWorktreePath = result.worktree.path;
|
||||||
|
|||||||
@@ -1,8 +1,11 @@
|
|||||||
|
import { useAtomValue } from "@effect/atom-react";
|
||||||
import { parsePatchFiles } from "@pierre/diffs";
|
import { parsePatchFiles } from "@pierre/diffs";
|
||||||
import { FileDiff, type FileDiffMetadata, Virtualizer } from "@pierre/diffs/react";
|
import { FileDiff, type FileDiffMetadata, Virtualizer } from "@pierre/diffs/react";
|
||||||
import { useQuery } from "@tanstack/react-query";
|
import { useQuery } from "@tanstack/react-query";
|
||||||
import { useNavigate, useParams, useSearch } from "@tanstack/react-router";
|
import { useNavigate, useParams, useSearch } from "@tanstack/react-router";
|
||||||
import { ThreadId, type TurnId } from "@t3tools/contracts";
|
import { ThreadId, type TurnId } from "@t3tools/contracts";
|
||||||
|
import * as Option from "effect/Option";
|
||||||
|
import { AsyncResult } from "effect/unstable/reactivity";
|
||||||
import {
|
import {
|
||||||
ChevronLeftIcon,
|
ChevronLeftIcon,
|
||||||
ChevronRightIcon,
|
ChevronRightIcon,
|
||||||
@@ -19,10 +22,10 @@ import {
|
|||||||
useState,
|
useState,
|
||||||
} from "react";
|
} from "react";
|
||||||
import { openInPreferredEditor } from "../editorPreferences";
|
import { openInPreferredEditor } from "../editorPreferences";
|
||||||
import { gitBranchesQueryOptions } from "~/lib/gitReactQuery";
|
|
||||||
import { checkpointDiffQueryOptions } from "~/lib/providerReactQuery";
|
import { checkpointDiffQueryOptions } from "~/lib/providerReactQuery";
|
||||||
import { cn } from "~/lib/utils";
|
import { cn } from "~/lib/utils";
|
||||||
import { readNativeApi } from "../nativeApi";
|
import { readNativeApi } from "../nativeApi";
|
||||||
|
import { gitBranchesAtom } from "../rpc/gitAtoms";
|
||||||
import { resolvePathLinkTarget } from "../terminal-links";
|
import { resolvePathLinkTarget } from "../terminal-links";
|
||||||
import { parseDiffRouteSearch, stripDiffSearchParams } from "../diffRouteSearch";
|
import { parseDiffRouteSearch, stripDiffSearchParams } from "../diffRouteSearch";
|
||||||
import { useTheme } from "../hooks/useTheme";
|
import { useTheme } from "../hooks/useTheme";
|
||||||
@@ -189,8 +192,9 @@ export default function DiffPanel({ mode = "inline" }: DiffPanelProps) {
|
|||||||
activeProjectId ? store.projects.find((project) => project.id === activeProjectId) : undefined,
|
activeProjectId ? store.projects.find((project) => project.id === activeProjectId) : undefined,
|
||||||
);
|
);
|
||||||
const activeCwd = activeThread?.worktreePath ?? activeProject?.cwd;
|
const activeCwd = activeThread?.worktreePath ?? activeProject?.cwd;
|
||||||
const gitBranchesQuery = useQuery(gitBranchesQueryOptions(activeCwd ?? null));
|
const gitBranchesResult = useAtomValue(gitBranchesAtom(activeCwd ?? null));
|
||||||
const isGitRepo = gitBranchesQuery.data?.isRepo ?? true;
|
const gitBranches = Option.getOrUndefined(AsyncResult.value(gitBranchesResult));
|
||||||
|
const isGitRepo = gitBranches?.isRepo ?? true;
|
||||||
const { turnDiffSummaries, inferredCheckpointTurnCountByTurnId } =
|
const { turnDiffSummaries, inferredCheckpointTurnCountByTurnId } =
|
||||||
useTurnDiffSummaries(activeThread);
|
useTurnDiffSummaries(activeThread);
|
||||||
const orderedTurnDiffSummaries = useMemo(
|
const orderedTurnDiffSummaries = useMemo(
|
||||||
|
|||||||
@@ -1,10 +1,13 @@
|
|||||||
|
import { useAtomRefresh, useAtomSet, useAtomValue } from "@effect/atom-react";
|
||||||
import type {
|
import type {
|
||||||
GitActionProgressEvent,
|
GitRunStackedActionInput,
|
||||||
GitStackedAction,
|
GitStackedAction,
|
||||||
GitStatusResult,
|
GitStatusResult,
|
||||||
ThreadId,
|
ThreadId,
|
||||||
} from "@t3tools/contracts";
|
} from "@t3tools/contracts";
|
||||||
import { useIsMutating, useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
|
import { Cause } from "effect";
|
||||||
|
import * as Option from "effect/Option";
|
||||||
|
import { AsyncResult } from "effect/unstable/reactivity";
|
||||||
import { useCallback, useEffect, useEffectEvent, useMemo, useRef, useState } from "react";
|
import { useCallback, useEffect, useEffectEvent, useMemo, useRef, useState } from "react";
|
||||||
import { ChevronDownIcon, CloudUploadIcon, GitCommitIcon, InfoIcon } from "lucide-react";
|
import { ChevronDownIcon, CloudUploadIcon, GitCommitIcon, InfoIcon } from "lucide-react";
|
||||||
import { GitHubIcon } from "./Icons";
|
import { GitHubIcon } from "./Icons";
|
||||||
@@ -38,18 +41,18 @@ import { ScrollArea } from "~/components/ui/scroll-area";
|
|||||||
import { Textarea } from "~/components/ui/textarea";
|
import { Textarea } from "~/components/ui/textarea";
|
||||||
import { toastManager } from "~/components/ui/toast";
|
import { toastManager } from "~/components/ui/toast";
|
||||||
import { openInPreferredEditor } from "~/editorPreferences";
|
import { openInPreferredEditor } from "~/editorPreferences";
|
||||||
import {
|
|
||||||
gitBranchesQueryOptions,
|
|
||||||
gitInitMutationOptions,
|
|
||||||
gitMutationKeys,
|
|
||||||
gitPullMutationOptions,
|
|
||||||
gitRunStackedActionMutationOptions,
|
|
||||||
gitStatusQueryOptions,
|
|
||||||
invalidateGitQueries,
|
|
||||||
} from "~/lib/gitReactQuery";
|
|
||||||
import { randomUUID } from "~/lib/utils";
|
import { randomUUID } from "~/lib/utils";
|
||||||
import { resolvePathLinkTarget } from "~/terminal-links";
|
import { resolvePathLinkTarget } from "~/terminal-links";
|
||||||
import { readNativeApi } from "~/nativeApi";
|
import { readNativeApi } from "~/nativeApi";
|
||||||
|
import {
|
||||||
|
gitBranchesAtom,
|
||||||
|
gitInitMutationAtom,
|
||||||
|
gitPullMutationAtom,
|
||||||
|
gitRunStackedActionMutationAtom,
|
||||||
|
gitRunStackedActionProgressAtom,
|
||||||
|
gitStatusAtom,
|
||||||
|
} from "~/rpc/gitAtoms";
|
||||||
|
import { REACTIVITY_KEYS } from "~/rpc/client";
|
||||||
|
|
||||||
interface GitActionsControlProps {
|
interface GitActionsControlProps {
|
||||||
gitCwd: string | null;
|
gitCwd: string | null;
|
||||||
@@ -112,6 +115,13 @@ function resolveProgressDescription(progress: ActiveGitActionProgress): string |
|
|||||||
return formatElapsedDescription(progress.hookStartedAtMs ?? progress.phaseStartedAtMs);
|
return formatElapsedDescription(progress.hookStartedAtMs ?? progress.phaseStartedAtMs);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
function toError(error: unknown): Error {
|
||||||
|
if (error instanceof Error) {
|
||||||
|
return error;
|
||||||
|
}
|
||||||
|
return new Error(typeof error === "string" ? error : "Unknown error");
|
||||||
|
}
|
||||||
|
|
||||||
function getMenuActionDisabledReason({
|
function getMenuActionDisabledReason({
|
||||||
item,
|
item,
|
||||||
gitStatus,
|
gitStatus,
|
||||||
@@ -208,7 +218,6 @@ export default function GitActionsControl({ gitCwd, activeThreadId }: GitActions
|
|||||||
() => (activeThreadId ? { threadId: activeThreadId } : undefined),
|
() => (activeThreadId ? { threadId: activeThreadId } : undefined),
|
||||||
[activeThreadId],
|
[activeThreadId],
|
||||||
);
|
);
|
||||||
const queryClient = useQueryClient();
|
|
||||||
const [isCommitDialogOpen, setIsCommitDialogOpen] = useState(false);
|
const [isCommitDialogOpen, setIsCommitDialogOpen] = useState(false);
|
||||||
const [dialogCommitMessage, setDialogCommitMessage] = useState("");
|
const [dialogCommitMessage, setDialogCommitMessage] = useState("");
|
||||||
const [excludedFiles, setExcludedFiles] = useState<ReadonlySet<string>>(new Set());
|
const [excludedFiles, setExcludedFiles] = useState<ReadonlySet<string>>(new Set());
|
||||||
@@ -231,9 +240,22 @@ export default function GitActionsControl({ gitCwd, activeThreadId }: GitActions
|
|||||||
});
|
});
|
||||||
}, [threadToastData]);
|
}, [threadToastData]);
|
||||||
|
|
||||||
const { data: gitStatus = null, error: gitStatusError } = useQuery(gitStatusQueryOptions(gitCwd));
|
const gitStatusResult = useAtomValue(gitStatusAtom(gitCwd));
|
||||||
|
const branchesResult = useAtomValue(gitBranchesAtom(gitCwd));
|
||||||
const { data: branchList = null } = useQuery(gitBranchesQueryOptions(gitCwd));
|
const refreshGitStatus = useAtomRefresh(gitStatusAtom(gitCwd));
|
||||||
|
const refreshGitBranches = useAtomRefresh(gitBranchesAtom(gitCwd));
|
||||||
|
const initGit = useAtomSet(gitInitMutationAtom, { mode: "promise" });
|
||||||
|
const pullGit = useAtomSet(gitPullMutationAtom, { mode: "promise" });
|
||||||
|
const runStackedAction = useAtomSet(gitRunStackedActionMutationAtom, { mode: "promise" });
|
||||||
|
const runStackedActionResult = useAtomValue(gitRunStackedActionMutationAtom);
|
||||||
|
const stackedActionProgressEvent = useAtomValue(gitRunStackedActionProgressAtom);
|
||||||
|
const [isInitPending, setIsInitPending] = useState(false);
|
||||||
|
const [isPullRunning, setIsPullRunning] = useState(false);
|
||||||
|
const gitStatus = Option.getOrNull(AsyncResult.value(gitStatusResult));
|
||||||
|
const gitStatusError = Option.getOrNull(
|
||||||
|
Option.map(AsyncResult.cause(gitStatusResult), (cause) => toError(Cause.squash(cause))),
|
||||||
|
);
|
||||||
|
const branchList = Option.getOrNull(AsyncResult.value(branchesResult));
|
||||||
// Default to true while loading so we don't flash init controls.
|
// Default to true while loading so we don't flash init controls.
|
||||||
const isRepo = branchList?.isRepo ?? true;
|
const isRepo = branchList?.isRepo ?? true;
|
||||||
const hasOriginRemote = branchList?.hasOriginRemote ?? false;
|
const hasOriginRemote = branchList?.hasOriginRemote ?? false;
|
||||||
@@ -242,9 +264,10 @@ export default function GitActionsControl({ gitCwd, activeThreadId }: GitActions
|
|||||||
!!gitStatus?.branch && !!currentBranch && gitStatus.branch !== currentBranch;
|
!!gitStatus?.branch && !!currentBranch && gitStatus.branch !== currentBranch;
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
if (!isGitStatusOutOfSync) return;
|
if (!isGitStatusOutOfSync || !gitCwd) return;
|
||||||
void invalidateGitQueries(queryClient);
|
refreshGitStatus();
|
||||||
}, [isGitStatusOutOfSync, queryClient]);
|
refreshGitBranches();
|
||||||
|
}, [gitCwd, isGitStatusOutOfSync, refreshGitBranches, refreshGitStatus]);
|
||||||
|
|
||||||
const gitStatusForActions = isGitStatusOutOfSync ? null : gitStatus;
|
const gitStatusForActions = isGitStatusOutOfSync ? null : gitStatus;
|
||||||
|
|
||||||
@@ -252,21 +275,40 @@ export default function GitActionsControl({ gitCwd, activeThreadId }: GitActions
|
|||||||
const selectedFiles = allFiles.filter((f) => !excludedFiles.has(f.path));
|
const selectedFiles = allFiles.filter((f) => !excludedFiles.has(f.path));
|
||||||
const allSelected = excludedFiles.size === 0;
|
const allSelected = excludedFiles.size === 0;
|
||||||
const noneSelected = selectedFiles.length === 0;
|
const noneSelected = selectedFiles.length === 0;
|
||||||
|
const isRunStackedActionRunning = runStackedActionResult.waiting;
|
||||||
const initMutation = useMutation(gitInitMutationOptions({ cwd: gitCwd, queryClient }));
|
|
||||||
|
|
||||||
const runImmediateGitActionMutation = useMutation(
|
|
||||||
gitRunStackedActionMutationOptions({
|
|
||||||
cwd: gitCwd,
|
|
||||||
queryClient,
|
|
||||||
}),
|
|
||||||
);
|
|
||||||
const pullMutation = useMutation(gitPullMutationOptions({ cwd: gitCwd, queryClient }));
|
|
||||||
|
|
||||||
const isRunStackedActionRunning =
|
|
||||||
useIsMutating({ mutationKey: gitMutationKeys.runStackedAction(gitCwd) }) > 0;
|
|
||||||
const isPullRunning = useIsMutating({ mutationKey: gitMutationKeys.pull(gitCwd) }) > 0;
|
|
||||||
const isGitActionRunning = isRunStackedActionRunning || isPullRunning;
|
const isGitActionRunning = isRunStackedActionRunning || isPullRunning;
|
||||||
|
const runImmediateGitAction = useCallback(
|
||||||
|
(input: GitRunStackedActionInput) => runStackedAction(input),
|
||||||
|
[runStackedAction],
|
||||||
|
);
|
||||||
|
const pullCurrentBranch = useCallback(
|
||||||
|
async (cwd: string) => {
|
||||||
|
setIsPullRunning(true);
|
||||||
|
try {
|
||||||
|
return await pullGit({
|
||||||
|
payload: { cwd },
|
||||||
|
reactivityKeys: [REACTIVITY_KEYS.git(cwd)],
|
||||||
|
});
|
||||||
|
} finally {
|
||||||
|
setIsPullRunning(false);
|
||||||
|
}
|
||||||
|
},
|
||||||
|
[pullGit],
|
||||||
|
);
|
||||||
|
const initializeGit = useCallback(
|
||||||
|
async (cwd: string) => {
|
||||||
|
setIsInitPending(true);
|
||||||
|
try {
|
||||||
|
await initGit({
|
||||||
|
payload: { cwd },
|
||||||
|
reactivityKeys: [REACTIVITY_KEYS.git(cwd)],
|
||||||
|
});
|
||||||
|
} finally {
|
||||||
|
setIsInitPending(false);
|
||||||
|
}
|
||||||
|
},
|
||||||
|
[initGit],
|
||||||
|
);
|
||||||
const isDefaultBranch = useMemo(() => {
|
const isDefaultBranch = useMemo(() => {
|
||||||
const branchName = gitStatusForActions?.branch;
|
const branchName = gitStatusForActions?.branch;
|
||||||
if (!branchName) return false;
|
if (!branchName) return false;
|
||||||
@@ -307,6 +349,59 @@ export default function GitActionsControl({ gitCwd, activeThreadId }: GitActions
|
|||||||
};
|
};
|
||||||
}, [updateActiveProgressToast]);
|
}, [updateActiveProgressToast]);
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
const event = stackedActionProgressEvent;
|
||||||
|
const progress = activeGitActionProgressRef.current;
|
||||||
|
if (!event || !progress) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (gitCwd && event.cwd !== gitCwd) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (progress.actionId !== event.actionId) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
const now = Date.now();
|
||||||
|
switch (event.kind) {
|
||||||
|
case "action_started":
|
||||||
|
progress.phaseStartedAtMs = now;
|
||||||
|
progress.hookStartedAtMs = null;
|
||||||
|
progress.hookName = null;
|
||||||
|
progress.lastOutputLine = null;
|
||||||
|
break;
|
||||||
|
case "phase_started":
|
||||||
|
progress.title = event.label;
|
||||||
|
progress.currentPhaseLabel = event.label;
|
||||||
|
progress.phaseStartedAtMs = now;
|
||||||
|
progress.hookStartedAtMs = null;
|
||||||
|
progress.hookName = null;
|
||||||
|
progress.lastOutputLine = null;
|
||||||
|
break;
|
||||||
|
case "hook_started":
|
||||||
|
progress.title = `Running ${event.hookName}...`;
|
||||||
|
progress.hookName = event.hookName;
|
||||||
|
progress.hookStartedAtMs = now;
|
||||||
|
progress.lastOutputLine = null;
|
||||||
|
break;
|
||||||
|
case "hook_output":
|
||||||
|
progress.lastOutputLine = event.text;
|
||||||
|
break;
|
||||||
|
case "hook_finished":
|
||||||
|
progress.title = progress.currentPhaseLabel ?? "Committing...";
|
||||||
|
progress.hookName = null;
|
||||||
|
progress.hookStartedAtMs = null;
|
||||||
|
progress.lastOutputLine = null;
|
||||||
|
break;
|
||||||
|
case "action_finished":
|
||||||
|
return;
|
||||||
|
case "action_failed":
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
updateActiveProgressToast();
|
||||||
|
}, [gitCwd, stackedActionProgressEvent, updateActiveProgressToast]);
|
||||||
|
|
||||||
const openExistingPr = useCallback(async () => {
|
const openExistingPr = useCallback(async () => {
|
||||||
const api = readNativeApi();
|
const api = readNativeApi();
|
||||||
if (!api) {
|
if (!api) {
|
||||||
@@ -415,69 +510,17 @@ export default function GitActionsControl({ gitCwd, activeThreadId }: GitActions
|
|||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
const applyProgressEvent = (event: GitActionProgressEvent) => {
|
if (!gitCwd) {
|
||||||
const progress = activeGitActionProgressRef.current;
|
return;
|
||||||
if (!progress) {
|
}
|
||||||
return;
|
|
||||||
}
|
|
||||||
if (gitCwd && event.cwd !== gitCwd) {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
if (progress.actionId !== event.actionId) {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
const now = Date.now();
|
const promise = runImmediateGitAction({
|
||||||
switch (event.kind) {
|
|
||||||
case "action_started":
|
|
||||||
progress.phaseStartedAtMs = now;
|
|
||||||
progress.hookStartedAtMs = null;
|
|
||||||
progress.hookName = null;
|
|
||||||
progress.lastOutputLine = null;
|
|
||||||
break;
|
|
||||||
case "phase_started":
|
|
||||||
progress.title = event.label;
|
|
||||||
progress.currentPhaseLabel = event.label;
|
|
||||||
progress.phaseStartedAtMs = now;
|
|
||||||
progress.hookStartedAtMs = null;
|
|
||||||
progress.hookName = null;
|
|
||||||
progress.lastOutputLine = null;
|
|
||||||
break;
|
|
||||||
case "hook_started":
|
|
||||||
progress.title = `Running ${event.hookName}...`;
|
|
||||||
progress.hookName = event.hookName;
|
|
||||||
progress.hookStartedAtMs = now;
|
|
||||||
progress.lastOutputLine = null;
|
|
||||||
break;
|
|
||||||
case "hook_output":
|
|
||||||
progress.lastOutputLine = event.text;
|
|
||||||
break;
|
|
||||||
case "hook_finished":
|
|
||||||
progress.title = progress.currentPhaseLabel ?? "Committing...";
|
|
||||||
progress.hookName = null;
|
|
||||||
progress.hookStartedAtMs = null;
|
|
||||||
progress.lastOutputLine = null;
|
|
||||||
break;
|
|
||||||
case "action_finished":
|
|
||||||
// Let the resolved mutation update the toast so we keep the
|
|
||||||
// elapsed description visible until the final success state renders.
|
|
||||||
return;
|
|
||||||
case "action_failed":
|
|
||||||
// Let the rejected mutation publish the error toast to avoid a
|
|
||||||
// transient intermediate state before the final failure message.
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
updateActiveProgressToast();
|
|
||||||
};
|
|
||||||
|
|
||||||
const promise = runImmediateGitActionMutation.mutateAsync({
|
|
||||||
actionId,
|
actionId,
|
||||||
|
cwd: gitCwd,
|
||||||
action,
|
action,
|
||||||
...(commitMessage ? { commitMessage } : {}),
|
...(commitMessage ? { commitMessage } : {}),
|
||||||
...(featureBranch ? { featureBranch } : {}),
|
...(featureBranch ? { featureBranch } : {}),
|
||||||
...(filePaths ? { filePaths } : {}),
|
...(filePaths ? { filePaths } : {}),
|
||||||
onProgress: applyProgressEvent,
|
|
||||||
});
|
});
|
||||||
|
|
||||||
try {
|
try {
|
||||||
@@ -624,7 +667,10 @@ export default function GitActionsControl({ gitCwd, activeThreadId }: GitActions
|
|||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
if (quickAction.kind === "run_pull") {
|
if (quickAction.kind === "run_pull") {
|
||||||
const promise = pullMutation.mutateAsync();
|
if (!gitCwd) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
const promise = pullCurrentBranch(gitCwd);
|
||||||
toastManager.promise(promise, {
|
toastManager.promise(promise, {
|
||||||
loading: { title: "Pulling...", data: threadToastData },
|
loading: { title: "Pulling...", data: threadToastData },
|
||||||
success: (result) => ({
|
success: (result) => ({
|
||||||
@@ -656,7 +702,7 @@ export default function GitActionsControl({ gitCwd, activeThreadId }: GitActions
|
|||||||
if (quickAction.action) {
|
if (quickAction.action) {
|
||||||
void runGitActionWithToast({ action: quickAction.action });
|
void runGitActionWithToast({ action: quickAction.action });
|
||||||
}
|
}
|
||||||
}, [openExistingPr, pullMutation, quickAction, threadToastData]);
|
}, [gitCwd, openExistingPr, pullCurrentBranch, quickAction, threadToastData]);
|
||||||
|
|
||||||
const openDialogForMenuItem = useCallback(
|
const openDialogForMenuItem = useCallback(
|
||||||
(item: GitActionMenuItem) => {
|
(item: GitActionMenuItem) => {
|
||||||
@@ -733,10 +779,15 @@ export default function GitActionsControl({ gitCwd, activeThreadId }: GitActions
|
|||||||
<Button
|
<Button
|
||||||
variant="outline"
|
variant="outline"
|
||||||
size="xs"
|
size="xs"
|
||||||
disabled={initMutation.isPending}
|
disabled={isInitPending}
|
||||||
onClick={() => initMutation.mutate()}
|
onClick={() => {
|
||||||
|
if (!gitCwd) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
void initializeGit(gitCwd).catch(() => undefined);
|
||||||
|
}}
|
||||||
>
|
>
|
||||||
{initMutation.isPending ? "Initializing..." : "Initialize Git"}
|
{isInitPending ? "Initializing..." : "Initialize Git"}
|
||||||
</Button>
|
</Button>
|
||||||
) : (
|
) : (
|
||||||
<Group aria-label="Git actions" className="shrink-0">
|
<Group aria-label="Git actions" className="shrink-0">
|
||||||
@@ -778,7 +829,10 @@ export default function GitActionsControl({ gitCwd, activeThreadId }: GitActions
|
|||||||
<GroupSeparator className="hidden @3xl/header-actions:block" />
|
<GroupSeparator className="hidden @3xl/header-actions:block" />
|
||||||
<Menu
|
<Menu
|
||||||
onOpenChange={(open) => {
|
onOpenChange={(open) => {
|
||||||
if (open) void invalidateGitQueries(queryClient);
|
if (open && gitCwd) {
|
||||||
|
refreshGitStatus();
|
||||||
|
refreshGitBranches();
|
||||||
|
}
|
||||||
}}
|
}}
|
||||||
>
|
>
|
||||||
<MenuTrigger
|
<MenuTrigger
|
||||||
|
|||||||
@@ -1,14 +1,13 @@
|
|||||||
import type { GitResolvePullRequestResult } from "@t3tools/contracts";
|
import { useAtomSet, useAtomValue } from "@effect/atom-react";
|
||||||
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
|
|
||||||
import { useDebouncedValue } from "@tanstack/react-pacer";
|
import { useDebouncedValue } from "@tanstack/react-pacer";
|
||||||
|
import { Cause, Option } from "effect";
|
||||||
|
import { AsyncResult, Atom } from "effect/unstable/reactivity";
|
||||||
import { useCallback, useEffect, useMemo, useRef, useState } from "react";
|
import { useCallback, useEffect, useMemo, useRef, useState } from "react";
|
||||||
|
|
||||||
import {
|
|
||||||
gitPreparePullRequestThreadMutationOptions,
|
|
||||||
gitResolvePullRequestQueryOptions,
|
|
||||||
} from "~/lib/gitReactQuery";
|
|
||||||
import { cn } from "~/lib/utils";
|
import { cn } from "~/lib/utils";
|
||||||
import { parsePullRequestReference } from "~/pullRequestReference";
|
import { parsePullRequestReference } from "~/pullRequestReference";
|
||||||
|
import { gitResolvePullRequestAtom, gitPreparePullRequestThreadMutationAtom } from "~/rpc/gitAtoms";
|
||||||
|
import { REACTIVITY_KEYS } from "~/rpc/client";
|
||||||
import { Button } from "./ui/button";
|
import { Button } from "./ui/button";
|
||||||
import {
|
import {
|
||||||
Dialog,
|
Dialog,
|
||||||
@@ -30,6 +29,10 @@ interface PullRequestThreadDialogProps {
|
|||||||
onPrepared: (input: { branch: string; worktreePath: string | null }) => Promise<void> | void;
|
onPrepared: (input: { branch: string; worktreePath: string | null }) => Promise<void> | void;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
function toErrorMessage(error: unknown, fallback: string): string {
|
||||||
|
return error instanceof Error ? error.message : fallback;
|
||||||
|
}
|
||||||
|
|
||||||
export function PullRequestThreadDialog({
|
export function PullRequestThreadDialog({
|
||||||
open,
|
open,
|
||||||
cwd,
|
cwd,
|
||||||
@@ -37,23 +40,28 @@ export function PullRequestThreadDialog({
|
|||||||
onOpenChange,
|
onOpenChange,
|
||||||
onPrepared,
|
onPrepared,
|
||||||
}: PullRequestThreadDialogProps) {
|
}: PullRequestThreadDialogProps) {
|
||||||
const queryClient = useQueryClient();
|
|
||||||
const referenceInputRef = useRef<HTMLInputElement>(null);
|
const referenceInputRef = useRef<HTMLInputElement>(null);
|
||||||
const [reference, setReference] = useState(initialReference ?? "");
|
const [reference, setReference] = useState(initialReference ?? "");
|
||||||
const [referenceDirty, setReferenceDirty] = useState(false);
|
const [referenceDirty, setReferenceDirty] = useState(false);
|
||||||
const [preparingMode, setPreparingMode] = useState<"local" | "worktree" | null>(null);
|
const [preparingMode, setPreparingMode] = useState<"local" | "worktree" | null>(null);
|
||||||
|
const [prepareFollowupErrorMessage, setPrepareFollowupErrorMessage] = useState<string | null>(
|
||||||
|
null,
|
||||||
|
);
|
||||||
const [debouncedReference, referenceDebouncer] = useDebouncedValue(
|
const [debouncedReference, referenceDebouncer] = useDebouncedValue(
|
||||||
reference,
|
reference,
|
||||||
{ wait: 450 },
|
{ wait: 450 },
|
||||||
(debouncerState) => ({ isPending: debouncerState.isPending }),
|
(debouncerState) => ({ isPending: debouncerState.isPending }),
|
||||||
);
|
);
|
||||||
|
const resetPreparePullRequestThread = useAtomSet(gitPreparePullRequestThreadMutationAtom);
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
if (!open) return;
|
if (!open) return;
|
||||||
setReference(initialReference ?? "");
|
setReference(initialReference ?? "");
|
||||||
setReferenceDirty(false);
|
setReferenceDirty(false);
|
||||||
setPreparingMode(null);
|
setPreparingMode(null);
|
||||||
}, [initialReference, open]);
|
setPrepareFollowupErrorMessage(null);
|
||||||
|
resetPreparePullRequestThread(Atom.Reset);
|
||||||
|
}, [initialReference, open, resetPreparePullRequestThread]);
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
if (!open) return;
|
if (!open) return;
|
||||||
@@ -68,41 +76,35 @@ export function PullRequestThreadDialog({
|
|||||||
|
|
||||||
const parsedReference = parsePullRequestReference(reference);
|
const parsedReference = parsePullRequestReference(reference);
|
||||||
const parsedDebouncedReference = parsePullRequestReference(debouncedReference);
|
const parsedDebouncedReference = parsePullRequestReference(debouncedReference);
|
||||||
const resolvePullRequestQuery = useQuery(
|
const resolvePullRequestResult = useAtomValue(
|
||||||
gitResolvePullRequestQueryOptions({
|
gitResolvePullRequestAtom({
|
||||||
cwd,
|
cwd: open ? cwd : null,
|
||||||
reference: open ? parsedDebouncedReference : null,
|
reference: open ? parsedDebouncedReference : null,
|
||||||
}),
|
}),
|
||||||
);
|
);
|
||||||
const cachedPullRequest = useMemo(() => {
|
const preparePullRequestThread = useAtomSet(gitPreparePullRequestThreadMutationAtom, {
|
||||||
if (!cwd || !parsedReference) {
|
mode: "promise",
|
||||||
return null;
|
});
|
||||||
}
|
const preparePullRequestThreadResult = useAtomValue(gitPreparePullRequestThreadMutationAtom);
|
||||||
const cached = queryClient.getQueryData<GitResolvePullRequestResult>([
|
const resolvePullRequestData = Option.getOrUndefined(AsyncResult.value(resolvePullRequestResult));
|
||||||
"git",
|
const resolvePullRequestError = Option.getOrNull(
|
||||||
"pull-request",
|
Option.map(AsyncResult.cause(resolvePullRequestResult), (cause) => Cause.squash(cause)),
|
||||||
cwd,
|
|
||||||
parsedReference,
|
|
||||||
]);
|
|
||||||
return cached?.pullRequest ?? null;
|
|
||||||
}, [cwd, parsedReference, queryClient]);
|
|
||||||
const preparePullRequestThreadMutation = useMutation(
|
|
||||||
gitPreparePullRequestThreadMutationOptions({ cwd, queryClient }),
|
|
||||||
);
|
);
|
||||||
|
const isPreparingPullRequestThread = preparingMode !== null;
|
||||||
|
|
||||||
const liveResolvedPullRequest =
|
const liveResolvedPullRequest =
|
||||||
parsedReference !== null && parsedReference === parsedDebouncedReference
|
parsedReference !== null && parsedReference === parsedDebouncedReference
|
||||||
? (resolvePullRequestQuery.data?.pullRequest ?? null)
|
? (resolvePullRequestData?.pullRequest ?? null)
|
||||||
: null;
|
: null;
|
||||||
const resolvedPullRequest = liveResolvedPullRequest ?? cachedPullRequest;
|
const resolvedPullRequest = liveResolvedPullRequest;
|
||||||
const isResolving =
|
const isResolving =
|
||||||
open &&
|
open &&
|
||||||
parsedReference !== null &&
|
parsedReference !== null &&
|
||||||
resolvedPullRequest === null &&
|
resolvedPullRequest === null &&
|
||||||
(referenceDebouncer.state.isPending ||
|
(referenceDebouncer.state.isPending ||
|
||||||
parsedReference !== parsedDebouncedReference ||
|
parsedReference !== parsedDebouncedReference ||
|
||||||
resolvePullRequestQuery.isPending ||
|
AsyncResult.isInitial(resolvePullRequestResult) ||
|
||||||
resolvePullRequestQuery.isFetching);
|
resolvePullRequestResult.waiting);
|
||||||
const statusTone = useMemo(() => {
|
const statusTone = useMemo(() => {
|
||||||
switch (resolvedPullRequest?.state) {
|
switch (resolvedPullRequest?.state) {
|
||||||
case "merged":
|
case "merged":
|
||||||
@@ -115,6 +117,11 @@ export function PullRequestThreadDialog({
|
|||||||
return "text-muted-foreground";
|
return "text-muted-foreground";
|
||||||
}
|
}
|
||||||
}, [resolvedPullRequest?.state]);
|
}, [resolvedPullRequest?.state]);
|
||||||
|
const preparePullRequestThreadErrorMessage = AsyncResult.match(preparePullRequestThreadResult, {
|
||||||
|
onInitial: () => null,
|
||||||
|
onSuccess: () => null,
|
||||||
|
onFailure: (error) => Cause.pretty(error.cause),
|
||||||
|
});
|
||||||
|
|
||||||
const handleConfirm = useCallback(
|
const handleConfirm = useCallback(
|
||||||
async (mode: "local" | "worktree") => {
|
async (mode: "local" | "worktree") => {
|
||||||
@@ -125,29 +132,36 @@ export function PullRequestThreadDialog({
|
|||||||
if (!parsedReference || !resolvedPullRequest || !cwd) {
|
if (!parsedReference || !resolvedPullRequest || !cwd) {
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
setPrepareFollowupErrorMessage(null);
|
||||||
setPreparingMode(mode);
|
setPreparingMode(mode);
|
||||||
try {
|
try {
|
||||||
const result = await preparePullRequestThreadMutation.mutateAsync({
|
const result = await preparePullRequestThread({
|
||||||
reference: parsedReference,
|
payload: {
|
||||||
mode,
|
cwd,
|
||||||
|
reference: parsedReference,
|
||||||
|
mode,
|
||||||
|
},
|
||||||
|
reactivityKeys: [REACTIVITY_KEYS.git(cwd)],
|
||||||
});
|
});
|
||||||
await onPrepared({
|
|
||||||
branch: result.branch,
|
try {
|
||||||
worktreePath: result.worktreePath,
|
await onPrepared({
|
||||||
});
|
branch: result.branch,
|
||||||
onOpenChange(false);
|
worktreePath: result.worktreePath,
|
||||||
|
});
|
||||||
|
onOpenChange(false);
|
||||||
|
} catch (error) {
|
||||||
|
setPrepareFollowupErrorMessage(
|
||||||
|
toErrorMessage(error, "Failed to prepare pull request thread."),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
} catch {
|
||||||
|
return;
|
||||||
} finally {
|
} finally {
|
||||||
setPreparingMode(null);
|
setPreparingMode(null);
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
[
|
[cwd, onOpenChange, onPrepared, parsedReference, preparePullRequestThread, resolvedPullRequest],
|
||||||
cwd,
|
|
||||||
onOpenChange,
|
|
||||||
onPrepared,
|
|
||||||
parsedReference,
|
|
||||||
preparePullRequestThreadMutation,
|
|
||||||
resolvedPullRequest,
|
|
||||||
],
|
|
||||||
);
|
);
|
||||||
|
|
||||||
const validationMessage = !referenceDirty
|
const validationMessage = !referenceDirty
|
||||||
@@ -159,21 +173,17 @@ export function PullRequestThreadDialog({
|
|||||||
: null;
|
: null;
|
||||||
const errorMessage =
|
const errorMessage =
|
||||||
validationMessage ??
|
validationMessage ??
|
||||||
(resolvedPullRequest === null && resolvePullRequestQuery.isError
|
(resolvedPullRequest === null && AsyncResult.isFailure(resolvePullRequestResult)
|
||||||
? resolvePullRequestQuery.error instanceof Error
|
? resolvePullRequestError instanceof Error
|
||||||
? resolvePullRequestQuery.error.message
|
? resolvePullRequestError.message
|
||||||
: "Failed to resolve pull request."
|
: "Failed to resolve pull request."
|
||||||
: preparePullRequestThreadMutation.error instanceof Error
|
: (prepareFollowupErrorMessage ?? preparePullRequestThreadErrorMessage));
|
||||||
? preparePullRequestThreadMutation.error.message
|
|
||||||
: preparePullRequestThreadMutation.error
|
|
||||||
? "Failed to prepare pull request thread."
|
|
||||||
: null);
|
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<Dialog
|
<Dialog
|
||||||
open={open}
|
open={open}
|
||||||
onOpenChange={(nextOpen) => {
|
onOpenChange={(nextOpen) => {
|
||||||
if (!preparePullRequestThreadMutation.isPending) {
|
if (!isPreparingPullRequestThread) {
|
||||||
onOpenChange(nextOpen);
|
onOpenChange(nextOpen);
|
||||||
}
|
}
|
||||||
}}
|
}}
|
||||||
@@ -202,7 +212,7 @@ export function PullRequestThreadDialog({
|
|||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
event.preventDefault();
|
event.preventDefault();
|
||||||
if (!isResolving && !preparePullRequestThreadMutation.isPending) {
|
if (!isResolving && !isPreparingPullRequestThread) {
|
||||||
void handleConfirm("local");
|
void handleConfirm("local");
|
||||||
}
|
}
|
||||||
}}
|
}}
|
||||||
@@ -241,7 +251,7 @@ export function PullRequestThreadDialog({
|
|||||||
variant="outline"
|
variant="outline"
|
||||||
size="sm"
|
size="sm"
|
||||||
onClick={() => onOpenChange(false)}
|
onClick={() => onOpenChange(false)}
|
||||||
disabled={preparePullRequestThreadMutation.isPending}
|
disabled={isPreparingPullRequestThread}
|
||||||
>
|
>
|
||||||
Cancel
|
Cancel
|
||||||
</Button>
|
</Button>
|
||||||
@@ -252,12 +262,7 @@ export function PullRequestThreadDialog({
|
|||||||
onClick={() => {
|
onClick={() => {
|
||||||
void handleConfirm("local");
|
void handleConfirm("local");
|
||||||
}}
|
}}
|
||||||
disabled={
|
disabled={!cwd || !resolvedPullRequest || isResolving || isPreparingPullRequestThread}
|
||||||
!cwd ||
|
|
||||||
!resolvedPullRequest ||
|
|
||||||
isResolving ||
|
|
||||||
preparePullRequestThreadMutation.isPending
|
|
||||||
}
|
|
||||||
>
|
>
|
||||||
{preparingMode === "local" ? "Preparing local..." : "Local"}
|
{preparingMode === "local" ? "Preparing local..." : "Local"}
|
||||||
</Button>
|
</Button>
|
||||||
@@ -267,12 +272,7 @@ export function PullRequestThreadDialog({
|
|||||||
onClick={() => {
|
onClick={() => {
|
||||||
void handleConfirm("worktree");
|
void handleConfirm("worktree");
|
||||||
}}
|
}}
|
||||||
disabled={
|
disabled={!cwd || !resolvedPullRequest || isResolving || isPreparingPullRequestThread}
|
||||||
!cwd ||
|
|
||||||
!resolvedPullRequest ||
|
|
||||||
isResolving ||
|
|
||||||
preparePullRequestThreadMutation.isPending
|
|
||||||
}
|
|
||||||
>
|
>
|
||||||
{preparingMode === "worktree" ? "Preparing worktree..." : "Worktree"}
|
{preparingMode === "worktree" ? "Preparing worktree..." : "Worktree"}
|
||||||
</Button>
|
</Button>
|
||||||
|
|||||||
@@ -12,6 +12,8 @@ import {
|
|||||||
} from "lucide-react";
|
} from "lucide-react";
|
||||||
import { ProjectFavicon } from "./ProjectFavicon";
|
import { ProjectFavicon } from "./ProjectFavicon";
|
||||||
import { autoAnimate } from "@formkit/auto-animate";
|
import { autoAnimate } from "@formkit/auto-animate";
|
||||||
|
import { Option } from "effect";
|
||||||
|
import { AsyncResult } from "effect/unstable/reactivity";
|
||||||
import {
|
import {
|
||||||
useCallback,
|
useCallback,
|
||||||
useEffect,
|
useEffect,
|
||||||
@@ -44,7 +46,6 @@ import {
|
|||||||
ThreadId,
|
ThreadId,
|
||||||
type GitStatusResult,
|
type GitStatusResult,
|
||||||
} from "@t3tools/contracts";
|
} from "@t3tools/contracts";
|
||||||
import { useQueries } from "@tanstack/react-query";
|
|
||||||
import { useLocation, useNavigate, useParams } from "@tanstack/react-router";
|
import { useLocation, useNavigate, useParams } from "@tanstack/react-router";
|
||||||
import {
|
import {
|
||||||
type SidebarProjectSortOrder,
|
type SidebarProjectSortOrder,
|
||||||
@@ -65,8 +66,8 @@ import {
|
|||||||
threadTraversalDirectionFromCommand,
|
threadTraversalDirectionFromCommand,
|
||||||
} from "../keybindings";
|
} from "../keybindings";
|
||||||
import { derivePendingApprovals, derivePendingUserInputs } from "../session-logic";
|
import { derivePendingApprovals, derivePendingUserInputs } from "../session-logic";
|
||||||
import { gitStatusQueryOptions } from "../lib/gitReactQuery";
|
|
||||||
import { readNativeApi } from "../nativeApi";
|
import { readNativeApi } from "../nativeApi";
|
||||||
|
import { useGitStatuses } from "../rpc/gitAtoms";
|
||||||
import { useComposerDraftStore } from "../composerDraftStore";
|
import { useComposerDraftStore } from "../composerDraftStore";
|
||||||
import { useHandleNewThread } from "../hooks/useHandleNewThread";
|
import { useHandleNewThread } from "../hooks/useHandleNewThread";
|
||||||
|
|
||||||
@@ -556,19 +557,15 @@ export default function Sidebar() {
|
|||||||
],
|
],
|
||||||
[threadGitTargets],
|
[threadGitTargets],
|
||||||
);
|
);
|
||||||
const threadGitStatusQueries = useQueries({
|
const threadGitStatusResults = useGitStatuses(threadGitStatusCwds);
|
||||||
queries: threadGitStatusCwds.map((cwd) => ({
|
|
||||||
...gitStatusQueryOptions(cwd),
|
|
||||||
staleTime: 30_000,
|
|
||||||
refetchInterval: 60_000,
|
|
||||||
})),
|
|
||||||
});
|
|
||||||
const prByThreadId = useMemo(() => {
|
const prByThreadId = useMemo(() => {
|
||||||
const statusByCwd = new Map<string, GitStatusResult>();
|
const statusByCwd = new Map<string, GitStatusResult>();
|
||||||
for (let index = 0; index < threadGitStatusCwds.length; index += 1) {
|
for (let index = 0; index < threadGitStatusCwds.length; index += 1) {
|
||||||
const cwd = threadGitStatusCwds[index];
|
const cwd = threadGitStatusCwds[index];
|
||||||
if (!cwd) continue;
|
if (!cwd) continue;
|
||||||
const status = threadGitStatusQueries[index]?.data;
|
const status = threadGitStatusResults[index]
|
||||||
|
? Option.getOrUndefined(AsyncResult.value(threadGitStatusResults[index]!))
|
||||||
|
: undefined;
|
||||||
if (status) {
|
if (status) {
|
||||||
statusByCwd.set(cwd, status);
|
statusByCwd.set(cwd, status);
|
||||||
}
|
}
|
||||||
@@ -582,7 +579,7 @@ export default function Sidebar() {
|
|||||||
map.set(target.threadId, branchMatches ? (status?.pr ?? null) : null);
|
map.set(target.threadId, branchMatches ? (status?.pr ?? null) : null);
|
||||||
}
|
}
|
||||||
return map;
|
return map;
|
||||||
}, [threadGitStatusCwds, threadGitStatusQueries, threadGitTargets]);
|
}, [threadGitStatusCwds, threadGitStatusResults, threadGitTargets]);
|
||||||
|
|
||||||
const openPrLink = useCallback((event: React.MouseEvent<HTMLElement>, prUrl: string) => {
|
const openPrLink = useCallback((event: React.MouseEvent<HTMLElement>, prUrl: string) => {
|
||||||
event.preventDefault();
|
event.preventDefault();
|
||||||
|
|||||||
@@ -1,14 +1,15 @@
|
|||||||
|
import { useAtomSet } from "@effect/atom-react";
|
||||||
import { ThreadId } from "@t3tools/contracts";
|
import { ThreadId } from "@t3tools/contracts";
|
||||||
import { useMutation, useQueryClient } from "@tanstack/react-query";
|
|
||||||
import { useNavigate, useParams } from "@tanstack/react-router";
|
import { useNavigate, useParams } from "@tanstack/react-router";
|
||||||
import { useCallback } from "react";
|
import { useCallback } from "react";
|
||||||
|
|
||||||
import { getFallbackThreadIdAfterDelete } from "../components/Sidebar.logic";
|
import { getFallbackThreadIdAfterDelete } from "../components/Sidebar.logic";
|
||||||
import { useComposerDraftStore } from "../composerDraftStore";
|
import { useComposerDraftStore } from "../composerDraftStore";
|
||||||
import { useHandleNewThread } from "./useHandleNewThread";
|
import { useHandleNewThread } from "./useHandleNewThread";
|
||||||
import { gitRemoveWorktreeMutationOptions } from "../lib/gitReactQuery";
|
|
||||||
import { newCommandId } from "../lib/utils";
|
import { newCommandId } from "../lib/utils";
|
||||||
import { readNativeApi } from "../nativeApi";
|
import { readNativeApi } from "../nativeApi";
|
||||||
|
import { gitRemoveWorktreeMutationAtom } from "../rpc/gitAtoms";
|
||||||
|
import { REACTIVITY_KEYS } from "../rpc/client";
|
||||||
import { useStore } from "../store";
|
import { useStore } from "../store";
|
||||||
import { useTerminalStateStore } from "../terminalStateStore";
|
import { useTerminalStateStore } from "../terminalStateStore";
|
||||||
import { formatWorktreePathForDisplay, getOrphanedWorktreePathForThread } from "../worktreeCleanup";
|
import { formatWorktreePathForDisplay, getOrphanedWorktreePathForThread } from "../worktreeCleanup";
|
||||||
@@ -28,8 +29,7 @@ export function useThreadActions() {
|
|||||||
});
|
});
|
||||||
const navigate = useNavigate();
|
const navigate = useNavigate();
|
||||||
const { handleNewThread } = useHandleNewThread();
|
const { handleNewThread } = useHandleNewThread();
|
||||||
const queryClient = useQueryClient();
|
const removeWorktree = useAtomSet(gitRemoveWorktreeMutationAtom, { mode: "promise" });
|
||||||
const removeWorktreeMutation = useMutation(gitRemoveWorktreeMutationOptions({ queryClient }));
|
|
||||||
|
|
||||||
const archiveThread = useCallback(
|
const archiveThread = useCallback(
|
||||||
async (threadId: ThreadId) => {
|
async (threadId: ThreadId) => {
|
||||||
@@ -144,10 +144,16 @@ export function useThreadActions() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
try {
|
try {
|
||||||
await removeWorktreeMutation.mutateAsync({
|
await removeWorktree({
|
||||||
cwd: threadProject.cwd,
|
payload: {
|
||||||
path: orphanedWorktreePath,
|
cwd: threadProject.cwd,
|
||||||
force: true,
|
path: orphanedWorktreePath,
|
||||||
|
force: true,
|
||||||
|
},
|
||||||
|
reactivityKeys: [
|
||||||
|
REACTIVITY_KEYS.git(threadProject.cwd),
|
||||||
|
REACTIVITY_KEYS.project(threadProject.cwd),
|
||||||
|
],
|
||||||
});
|
});
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
const message = error instanceof Error ? error.message : "Unknown error removing worktree.";
|
const message = error instanceof Error ? error.message : "Unknown error removing worktree.";
|
||||||
@@ -170,7 +176,7 @@ export function useThreadActions() {
|
|||||||
clearTerminalState,
|
clearTerminalState,
|
||||||
appSettings.sidebarThreadSortOrder,
|
appSettings.sidebarThreadSortOrder,
|
||||||
navigate,
|
navigate,
|
||||||
removeWorktreeMutation,
|
removeWorktree,
|
||||||
routeThreadId,
|
routeThreadId,
|
||||||
],
|
],
|
||||||
);
|
);
|
||||||
|
|||||||
@@ -1,51 +0,0 @@
|
|||||||
import { QueryClient } from "@tanstack/react-query";
|
|
||||||
import { describe, expect, it } from "vitest";
|
|
||||||
import {
|
|
||||||
gitMutationKeys,
|
|
||||||
gitPreparePullRequestThreadMutationOptions,
|
|
||||||
gitPullMutationOptions,
|
|
||||||
gitRunStackedActionMutationOptions,
|
|
||||||
} from "./gitReactQuery";
|
|
||||||
|
|
||||||
describe("gitMutationKeys", () => {
|
|
||||||
it("scopes stacked action keys by cwd", () => {
|
|
||||||
expect(gitMutationKeys.runStackedAction("/repo/a")).not.toEqual(
|
|
||||||
gitMutationKeys.runStackedAction("/repo/b"),
|
|
||||||
);
|
|
||||||
});
|
|
||||||
|
|
||||||
it("scopes pull keys by cwd", () => {
|
|
||||||
expect(gitMutationKeys.pull("/repo/a")).not.toEqual(gitMutationKeys.pull("/repo/b"));
|
|
||||||
});
|
|
||||||
|
|
||||||
it("scopes pull request thread preparation keys by cwd", () => {
|
|
||||||
expect(gitMutationKeys.preparePullRequestThread("/repo/a")).not.toEqual(
|
|
||||||
gitMutationKeys.preparePullRequestThread("/repo/b"),
|
|
||||||
);
|
|
||||||
});
|
|
||||||
});
|
|
||||||
|
|
||||||
describe("git mutation options", () => {
|
|
||||||
const queryClient = new QueryClient();
|
|
||||||
|
|
||||||
it("attaches cwd-scoped mutation key for runStackedAction", () => {
|
|
||||||
const options = gitRunStackedActionMutationOptions({
|
|
||||||
cwd: "/repo/a",
|
|
||||||
queryClient,
|
|
||||||
});
|
|
||||||
expect(options.mutationKey).toEqual(gitMutationKeys.runStackedAction("/repo/a"));
|
|
||||||
});
|
|
||||||
|
|
||||||
it("attaches cwd-scoped mutation key for pull", () => {
|
|
||||||
const options = gitPullMutationOptions({ cwd: "/repo/a", queryClient });
|
|
||||||
expect(options.mutationKey).toEqual(gitMutationKeys.pull("/repo/a"));
|
|
||||||
});
|
|
||||||
|
|
||||||
it("attaches cwd-scoped mutation key for preparePullRequestThread", () => {
|
|
||||||
const options = gitPreparePullRequestThreadMutationOptions({
|
|
||||||
cwd: "/repo/a",
|
|
||||||
queryClient,
|
|
||||||
});
|
|
||||||
expect(options.mutationKey).toEqual(gitMutationKeys.preparePullRequestThread("/repo/a"));
|
|
||||||
});
|
|
||||||
});
|
|
||||||
@@ -1,224 +0,0 @@
|
|||||||
import { type GitActionProgressEvent, type GitStackedAction } from "@t3tools/contracts";
|
|
||||||
import { mutationOptions, queryOptions, type QueryClient } from "@tanstack/react-query";
|
|
||||||
import { ensureNativeApi } from "../nativeApi";
|
|
||||||
import { getWsRpcClient } from "../wsRpcClient";
|
|
||||||
|
|
||||||
const GIT_STATUS_STALE_TIME_MS = 5_000;
|
|
||||||
const GIT_STATUS_REFETCH_INTERVAL_MS = 15_000;
|
|
||||||
const GIT_BRANCHES_STALE_TIME_MS = 15_000;
|
|
||||||
const GIT_BRANCHES_REFETCH_INTERVAL_MS = 60_000;
|
|
||||||
|
|
||||||
export const gitQueryKeys = {
|
|
||||||
all: ["git"] as const,
|
|
||||||
status: (cwd: string | null) => ["git", "status", cwd] as const,
|
|
||||||
branches: (cwd: string | null) => ["git", "branches", cwd] as const,
|
|
||||||
};
|
|
||||||
|
|
||||||
export const gitMutationKeys = {
|
|
||||||
init: (cwd: string | null) => ["git", "mutation", "init", cwd] as const,
|
|
||||||
checkout: (cwd: string | null) => ["git", "mutation", "checkout", cwd] as const,
|
|
||||||
runStackedAction: (cwd: string | null) => ["git", "mutation", "run-stacked-action", cwd] as const,
|
|
||||||
pull: (cwd: string | null) => ["git", "mutation", "pull", cwd] as const,
|
|
||||||
preparePullRequestThread: (cwd: string | null) =>
|
|
||||||
["git", "mutation", "prepare-pull-request-thread", cwd] as const,
|
|
||||||
};
|
|
||||||
|
|
||||||
export function invalidateGitQueries(queryClient: QueryClient) {
|
|
||||||
return queryClient.invalidateQueries({ queryKey: gitQueryKeys.all });
|
|
||||||
}
|
|
||||||
|
|
||||||
export function gitStatusQueryOptions(cwd: string | null) {
|
|
||||||
return queryOptions({
|
|
||||||
queryKey: gitQueryKeys.status(cwd),
|
|
||||||
queryFn: async () => {
|
|
||||||
const api = ensureNativeApi();
|
|
||||||
if (!cwd) throw new Error("Git status is unavailable.");
|
|
||||||
return api.git.status({ cwd });
|
|
||||||
},
|
|
||||||
enabled: cwd !== null,
|
|
||||||
staleTime: GIT_STATUS_STALE_TIME_MS,
|
|
||||||
refetchOnWindowFocus: "always",
|
|
||||||
refetchOnReconnect: "always",
|
|
||||||
refetchInterval: GIT_STATUS_REFETCH_INTERVAL_MS,
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
export function gitBranchesQueryOptions(cwd: string | null) {
|
|
||||||
return queryOptions({
|
|
||||||
queryKey: gitQueryKeys.branches(cwd),
|
|
||||||
queryFn: async () => {
|
|
||||||
const api = ensureNativeApi();
|
|
||||||
if (!cwd) throw new Error("Git branches are unavailable.");
|
|
||||||
return api.git.listBranches({ cwd });
|
|
||||||
},
|
|
||||||
enabled: cwd !== null,
|
|
||||||
staleTime: GIT_BRANCHES_STALE_TIME_MS,
|
|
||||||
refetchOnWindowFocus: true,
|
|
||||||
refetchOnReconnect: true,
|
|
||||||
refetchInterval: GIT_BRANCHES_REFETCH_INTERVAL_MS,
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
export function gitResolvePullRequestQueryOptions(input: {
|
|
||||||
cwd: string | null;
|
|
||||||
reference: string | null;
|
|
||||||
}) {
|
|
||||||
return queryOptions({
|
|
||||||
queryKey: ["git", "pull-request", input.cwd, input.reference] as const,
|
|
||||||
queryFn: async () => {
|
|
||||||
const api = ensureNativeApi();
|
|
||||||
if (!input.cwd || !input.reference) {
|
|
||||||
throw new Error("Pull request lookup is unavailable.");
|
|
||||||
}
|
|
||||||
return api.git.resolvePullRequest({ cwd: input.cwd, reference: input.reference });
|
|
||||||
},
|
|
||||||
enabled: input.cwd !== null && input.reference !== null,
|
|
||||||
staleTime: 30_000,
|
|
||||||
refetchOnWindowFocus: false,
|
|
||||||
refetchOnReconnect: false,
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
export function gitInitMutationOptions(input: { cwd: string | null; queryClient: QueryClient }) {
|
|
||||||
return mutationOptions({
|
|
||||||
mutationKey: gitMutationKeys.init(input.cwd),
|
|
||||||
mutationFn: async () => {
|
|
||||||
const api = ensureNativeApi();
|
|
||||||
if (!input.cwd) throw new Error("Git init is unavailable.");
|
|
||||||
return api.git.init({ cwd: input.cwd });
|
|
||||||
},
|
|
||||||
onSuccess: async () => {
|
|
||||||
await invalidateGitQueries(input.queryClient);
|
|
||||||
},
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
export function gitCheckoutMutationOptions(input: {
|
|
||||||
cwd: string | null;
|
|
||||||
queryClient: QueryClient;
|
|
||||||
}) {
|
|
||||||
return mutationOptions({
|
|
||||||
mutationKey: gitMutationKeys.checkout(input.cwd),
|
|
||||||
mutationFn: async (branch: string) => {
|
|
||||||
const api = ensureNativeApi();
|
|
||||||
if (!input.cwd) throw new Error("Git checkout is unavailable.");
|
|
||||||
return api.git.checkout({ cwd: input.cwd, branch });
|
|
||||||
},
|
|
||||||
onSuccess: async () => {
|
|
||||||
await invalidateGitQueries(input.queryClient);
|
|
||||||
},
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
export function gitRunStackedActionMutationOptions(input: {
|
|
||||||
cwd: string | null;
|
|
||||||
queryClient: QueryClient;
|
|
||||||
}) {
|
|
||||||
return mutationOptions({
|
|
||||||
mutationKey: gitMutationKeys.runStackedAction(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) throw new Error("Git action is unavailable.");
|
|
||||||
return getWsRpcClient().git.runStackedAction(
|
|
||||||
{
|
|
||||||
actionId,
|
|
||||||
cwd: input.cwd,
|
|
||||||
action,
|
|
||||||
...(commitMessage ? { commitMessage } : {}),
|
|
||||||
...(featureBranch ? { featureBranch } : {}),
|
|
||||||
...(filePaths ? { filePaths } : {}),
|
|
||||||
},
|
|
||||||
...(onProgress ? [{ onProgress }] : []),
|
|
||||||
);
|
|
||||||
},
|
|
||||||
onSettled: async () => {
|
|
||||||
await invalidateGitQueries(input.queryClient);
|
|
||||||
},
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
export function gitPullMutationOptions(input: { cwd: string | null; queryClient: QueryClient }) {
|
|
||||||
return mutationOptions({
|
|
||||||
mutationKey: gitMutationKeys.pull(input.cwd),
|
|
||||||
mutationFn: async () => {
|
|
||||||
const api = ensureNativeApi();
|
|
||||||
if (!input.cwd) throw new Error("Git pull is unavailable.");
|
|
||||||
return api.git.pull({ cwd: input.cwd });
|
|
||||||
},
|
|
||||||
onSettled: async () => {
|
|
||||||
await invalidateGitQueries(input.queryClient);
|
|
||||||
},
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
export function gitCreateWorktreeMutationOptions(input: { queryClient: QueryClient }) {
|
|
||||||
return mutationOptions({
|
|
||||||
mutationFn: async ({
|
|
||||||
cwd,
|
|
||||||
branch,
|
|
||||||
newBranch,
|
|
||||||
path,
|
|
||||||
}: {
|
|
||||||
cwd: string;
|
|
||||||
branch: string;
|
|
||||||
newBranch: string;
|
|
||||||
path?: string | null;
|
|
||||||
}) => {
|
|
||||||
const api = ensureNativeApi();
|
|
||||||
if (!cwd) throw new Error("Git worktree creation is unavailable.");
|
|
||||||
return api.git.createWorktree({ cwd, branch, newBranch, path: path ?? null });
|
|
||||||
},
|
|
||||||
mutationKey: ["git", "mutation", "create-worktree"] as const,
|
|
||||||
onSettled: async () => {
|
|
||||||
await invalidateGitQueries(input.queryClient);
|
|
||||||
},
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
export function gitRemoveWorktreeMutationOptions(input: { queryClient: QueryClient }) {
|
|
||||||
return mutationOptions({
|
|
||||||
mutationFn: async ({ cwd, path, force }: { cwd: string; path: string; force?: boolean }) => {
|
|
||||||
const api = ensureNativeApi();
|
|
||||||
if (!cwd) throw new Error("Git worktree removal is unavailable.");
|
|
||||||
return api.git.removeWorktree({ cwd, path, force });
|
|
||||||
},
|
|
||||||
mutationKey: ["git", "mutation", "remove-worktree"] as const,
|
|
||||||
onSettled: async () => {
|
|
||||||
await invalidateGitQueries(input.queryClient);
|
|
||||||
},
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
export function gitPreparePullRequestThreadMutationOptions(input: {
|
|
||||||
cwd: string | null;
|
|
||||||
queryClient: QueryClient;
|
|
||||||
}) {
|
|
||||||
return mutationOptions({
|
|
||||||
mutationFn: async ({ reference, mode }: { reference: string; mode: "local" | "worktree" }) => {
|
|
||||||
const api = ensureNativeApi();
|
|
||||||
if (!input.cwd) throw new Error("Pull request thread preparation is unavailable.");
|
|
||||||
return api.git.preparePullRequestThread({
|
|
||||||
cwd: input.cwd,
|
|
||||||
reference,
|
|
||||||
mode,
|
|
||||||
});
|
|
||||||
},
|
|
||||||
mutationKey: gitMutationKeys.preparePullRequestThread(input.cwd),
|
|
||||||
onSettled: async () => {
|
|
||||||
await invalidateGitQueries(input.queryClient);
|
|
||||||
},
|
|
||||||
});
|
|
||||||
}
|
|
||||||
@@ -2,7 +2,7 @@ import { DEFAULT_SERVER_SETTINGS, WS_METHODS } from "@t3tools/contracts";
|
|||||||
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
||||||
import { AsyncResult, AtomRegistry } from "effect/unstable/reactivity";
|
import { AsyncResult, AtomRegistry } from "effect/unstable/reactivity";
|
||||||
|
|
||||||
import { __resetWsRpcAtomClientForTests, runRpc, WsRpcAtomClient } from "./client";
|
import { WsRpcAtomClient } from "./client";
|
||||||
|
|
||||||
type WsEventType = "open" | "message" | "close" | "error";
|
type WsEventType = "open" | "message" | "close" | "error";
|
||||||
type WsEvent = { code?: number; data?: unknown; reason?: string; type?: string };
|
type WsEvent = { code?: number; data?: unknown; reason?: string; type?: string };
|
||||||
@@ -110,62 +110,11 @@ beforeEach(() => {
|
|||||||
});
|
});
|
||||||
|
|
||||||
afterEach(() => {
|
afterEach(() => {
|
||||||
__resetWsRpcAtomClientForTests();
|
|
||||||
globalThis.WebSocket = originalWebSocket;
|
globalThis.WebSocket = originalWebSocket;
|
||||||
vi.restoreAllMocks();
|
vi.restoreAllMocks();
|
||||||
});
|
});
|
||||||
|
|
||||||
describe("WsRpcAtomClient", () => {
|
describe("WsRpcAtomClient", () => {
|
||||||
it("runs unary requests through the AtomRpc service", async () => {
|
|
||||||
const expectedSettings = {
|
|
||||||
...DEFAULT_SERVER_SETTINGS,
|
|
||||||
enableAssistantStreaming: true,
|
|
||||||
defaultThreadEnvMode: "worktree" as const,
|
|
||||||
textGenerationModelSelection: {
|
|
||||||
provider: "codex" as const,
|
|
||||||
model: "gpt-5.4",
|
|
||||||
},
|
|
||||||
providers: {
|
|
||||||
codex: {
|
|
||||||
...DEFAULT_SERVER_SETTINGS.providers.codex,
|
|
||||||
homePath: "/tmp/codex-home",
|
|
||||||
},
|
|
||||||
claudeAgent: {
|
|
||||||
...DEFAULT_SERVER_SETTINGS.providers.claudeAgent,
|
|
||||||
enabled: false,
|
|
||||||
},
|
|
||||||
},
|
|
||||||
};
|
|
||||||
const requestPromise = runRpc((client) => client(WS_METHODS.serverGetSettings, {}));
|
|
||||||
|
|
||||||
await waitFor(() => {
|
|
||||||
expect(sockets).toHaveLength(1);
|
|
||||||
});
|
|
||||||
|
|
||||||
const socket = getSocket();
|
|
||||||
socket.open();
|
|
||||||
|
|
||||||
await waitFor(() => {
|
|
||||||
expect(socket.sent).toHaveLength(1);
|
|
||||||
});
|
|
||||||
|
|
||||||
const requestMessage = JSON.parse(socket.sent[0] ?? "{}") as { id: string; tag: string };
|
|
||||||
expect(requestMessage.tag).toBe(WS_METHODS.serverGetSettings);
|
|
||||||
|
|
||||||
socket.serverMessage(
|
|
||||||
JSON.stringify({
|
|
||||||
_tag: "Exit",
|
|
||||||
requestId: requestMessage.id,
|
|
||||||
exit: {
|
|
||||||
_tag: "Success",
|
|
||||||
value: expectedSettings,
|
|
||||||
},
|
|
||||||
}),
|
|
||||||
);
|
|
||||||
|
|
||||||
await expect(requestPromise).resolves.toEqual(expectedSettings);
|
|
||||||
});
|
|
||||||
|
|
||||||
it("exposes atom-backed query state for unary RPC methods", async () => {
|
it("exposes atom-backed query state for unary RPC methods", async () => {
|
||||||
const expectedSettings = {
|
const expectedSettings = {
|
||||||
...DEFAULT_SERVER_SETTINGS,
|
...DEFAULT_SERVER_SETTINGS,
|
||||||
|
|||||||
+22
-24
@@ -1,33 +1,31 @@
|
|||||||
import { WsRpcGroup } from "@t3tools/contracts";
|
import { WsRpcGroup } from "@t3tools/contracts";
|
||||||
import { Effect, Layer, ManagedRuntime } from "effect";
|
import { Layer } from "effect";
|
||||||
import { AtomRpc } from "effect/unstable/reactivity";
|
import { AtomRpc } from "effect/unstable/reactivity";
|
||||||
|
|
||||||
import { createWsRpcProtocolLayer } from "./protocol";
|
import { createWsRpcProtocolLayer } from "./protocol";
|
||||||
|
|
||||||
|
import { Atom } from "effect/unstable/reactivity";
|
||||||
|
import { Duration } from "effect";
|
||||||
|
|
||||||
|
export const REACTIVITY_KEYS = {
|
||||||
|
git: (cwd: string) => `git:${cwd}` as const,
|
||||||
|
project: (cwd: string) => `project:${cwd}` as const,
|
||||||
|
} as const;
|
||||||
|
|
||||||
|
export const refreshIntervalSignalAtom = Atom.family((interval: Duration.Duration) =>
|
||||||
|
Atom.readable((get) => {
|
||||||
|
let count = 0;
|
||||||
|
const intervalId = window.setInterval(() => {
|
||||||
|
get.setSelf(++count);
|
||||||
|
}, Duration.toMillis(interval));
|
||||||
|
get.addFinalizer(() => {
|
||||||
|
window.clearInterval(intervalId);
|
||||||
|
});
|
||||||
|
return count;
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
|
||||||
export class WsRpcAtomClient extends AtomRpc.Service<WsRpcAtomClient>()("WsRpcAtomClient", {
|
export class WsRpcAtomClient extends AtomRpc.Service<WsRpcAtomClient>()("WsRpcAtomClient", {
|
||||||
group: WsRpcGroup,
|
group: WsRpcGroup,
|
||||||
protocol: Layer.suspend(() => createWsRpcProtocolLayer()),
|
protocol: Layer.suspend(() => createWsRpcProtocolLayer()),
|
||||||
}) {}
|
}) {}
|
||||||
|
|
||||||
let sharedRuntime: ManagedRuntime.ManagedRuntime<WsRpcAtomClient, never> | null = null;
|
|
||||||
|
|
||||||
function getRuntime() {
|
|
||||||
if (sharedRuntime !== null) {
|
|
||||||
return sharedRuntime;
|
|
||||||
}
|
|
||||||
|
|
||||||
sharedRuntime = ManagedRuntime.make(WsRpcAtomClient.layer);
|
|
||||||
return sharedRuntime;
|
|
||||||
}
|
|
||||||
|
|
||||||
export function runRpc<TSuccess, TError = never>(
|
|
||||||
execute: (client: typeof WsRpcAtomClient.Service) => Effect.Effect<TSuccess, TError, never>,
|
|
||||||
): Promise<TSuccess> {
|
|
||||||
return getRuntime().runPromise(WsRpcAtomClient.use(execute));
|
|
||||||
}
|
|
||||||
|
|
||||||
export async function __resetWsRpcAtomClientForTests() {
|
|
||||||
const runtime = sharedRuntime;
|
|
||||||
sharedRuntime = null;
|
|
||||||
await runtime?.dispose();
|
|
||||||
}
|
|
||||||
@@ -0,0 +1,170 @@
|
|||||||
|
import {
|
||||||
|
type GitActionProgressEvent,
|
||||||
|
type GitListBranchesResult,
|
||||||
|
type GitResolvePullRequestResult,
|
||||||
|
type GitRunStackedActionInput,
|
||||||
|
type GitRunStackedActionResult,
|
||||||
|
type GitStatusResult,
|
||||||
|
WS_METHODS,
|
||||||
|
} from "@t3tools/contracts";
|
||||||
|
import { Duration, Effect, Stream } from "effect";
|
||||||
|
import { AsyncResult, Atom, Reactivity } from "effect/unstable/reactivity";
|
||||||
|
|
||||||
|
import { refreshIntervalSignalAtom, WsRpcAtomClient } from "./client";
|
||||||
|
import { REACTIVITY_KEYS } from "./client";
|
||||||
|
import { useMemo } from "react";
|
||||||
|
import { useAtomValue } from "@effect/atom-react";
|
||||||
|
|
||||||
|
const GIT_ACTION_RESULT_MISSING_ERROR = {
|
||||||
|
_tag: "GitActionResultMissing",
|
||||||
|
message: "Git action stream completed without a final result.",
|
||||||
|
} as const;
|
||||||
|
export const gitRunStackedActionProgressAtom = Atom.make<GitActionProgressEvent | null>(null).pipe(
|
||||||
|
Atom.keepAlive,
|
||||||
|
Atom.withLabel("git-run-stacked-action-progress"),
|
||||||
|
);
|
||||||
|
|
||||||
|
const gitStatusQueryAtom = Atom.family((cwd: string) =>
|
||||||
|
WsRpcAtomClient.query(
|
||||||
|
WS_METHODS.gitStatus,
|
||||||
|
{ cwd },
|
||||||
|
{
|
||||||
|
timeToLive: "5 minutes",
|
||||||
|
reactivityKeys: [REACTIVITY_KEYS.git(cwd)],
|
||||||
|
},
|
||||||
|
),
|
||||||
|
);
|
||||||
|
|
||||||
|
export const gitStatusAtom = Atom.family((cwd: string | null) =>
|
||||||
|
Atom.readable(
|
||||||
|
(get): AsyncResult.AsyncResult<GitStatusResult, unknown> => {
|
||||||
|
if (cwd === null) {
|
||||||
|
return AsyncResult.initial();
|
||||||
|
}
|
||||||
|
return get(gitStatusQueryAtom(cwd));
|
||||||
|
},
|
||||||
|
(refresh) => {
|
||||||
|
if (cwd !== null) {
|
||||||
|
refresh(gitStatusQueryAtom(cwd));
|
||||||
|
}
|
||||||
|
},
|
||||||
|
),
|
||||||
|
);
|
||||||
|
|
||||||
|
const gitBranchesQueryAtom = Atom.family((cwd: string) =>
|
||||||
|
WsRpcAtomClient.query(
|
||||||
|
WS_METHODS.gitListBranches,
|
||||||
|
{ cwd },
|
||||||
|
{
|
||||||
|
timeToLive: "5 minutes",
|
||||||
|
reactivityKeys: [REACTIVITY_KEYS.git(cwd)],
|
||||||
|
},
|
||||||
|
),
|
||||||
|
);
|
||||||
|
|
||||||
|
export const gitBranchesAtom = Atom.family((cwd: string | null) =>
|
||||||
|
Atom.readable(
|
||||||
|
(get): AsyncResult.AsyncResult<GitListBranchesResult, unknown> => {
|
||||||
|
if (cwd === null) {
|
||||||
|
return AsyncResult.initial();
|
||||||
|
}
|
||||||
|
return get(gitBranchesQueryAtom(cwd));
|
||||||
|
},
|
||||||
|
(refresh) => {
|
||||||
|
if (cwd !== null) {
|
||||||
|
refresh(gitBranchesQueryAtom(cwd));
|
||||||
|
}
|
||||||
|
},
|
||||||
|
),
|
||||||
|
);
|
||||||
|
|
||||||
|
export const gitCheckoutMutationAtom = WsRpcAtomClient.mutation(WS_METHODS.gitCheckout);
|
||||||
|
|
||||||
|
export const gitCreateBranchMutationAtom = WsRpcAtomClient.mutation(WS_METHODS.gitCreateBranch);
|
||||||
|
|
||||||
|
export const gitCreateWorktreeMutationAtom = WsRpcAtomClient.mutation(WS_METHODS.gitCreateWorktree);
|
||||||
|
|
||||||
|
export const gitInitMutationAtom = WsRpcAtomClient.mutation(WS_METHODS.gitInit);
|
||||||
|
|
||||||
|
export const gitPreparePullRequestThreadMutationAtom = WsRpcAtomClient.mutation(
|
||||||
|
WS_METHODS.gitPreparePullRequestThread,
|
||||||
|
);
|
||||||
|
|
||||||
|
export const gitPullMutationAtom = WsRpcAtomClient.mutation(WS_METHODS.gitPull);
|
||||||
|
|
||||||
|
export const gitRemoveWorktreeMutationAtom = WsRpcAtomClient.mutation(WS_METHODS.gitRemoveWorktree);
|
||||||
|
|
||||||
|
export const gitRunStackedActionMutationAtom = WsRpcAtomClient.runtime
|
||||||
|
.fn<GitRunStackedActionInput>()(
|
||||||
|
Effect.fn(
|
||||||
|
function* (input, get) {
|
||||||
|
get.set(gitRunStackedActionProgressAtom, null);
|
||||||
|
const client = yield* WsRpcAtomClient;
|
||||||
|
return yield* client(WS_METHODS.gitRunStackedAction, input).pipe(
|
||||||
|
Stream.runFoldEffect(
|
||||||
|
() => null as GitRunStackedActionResult | null,
|
||||||
|
(result, event) =>
|
||||||
|
Effect.sync(() => {
|
||||||
|
get.set(gitRunStackedActionProgressAtom, event);
|
||||||
|
return event.kind === "action_finished" ? event.result : result;
|
||||||
|
}),
|
||||||
|
),
|
||||||
|
Effect.flatMap((result) =>
|
||||||
|
result !== null ? Effect.succeed(result) : Effect.fail(GIT_ACTION_RESULT_MISSING_ERROR),
|
||||||
|
),
|
||||||
|
);
|
||||||
|
},
|
||||||
|
(effect, input) =>
|
||||||
|
Effect.ensuring(effect, Reactivity.invalidate([REACTIVITY_KEYS.git(input.cwd)])),
|
||||||
|
),
|
||||||
|
)
|
||||||
|
.pipe(Atom.withLabel("git-run-stacked-action"));
|
||||||
|
|
||||||
|
const gitResolvePullRequestQueryAtom = Atom.family(
|
||||||
|
(key: { readonly cwd: string; readonly reference: string }) =>
|
||||||
|
WsRpcAtomClient.query(WS_METHODS.gitResolvePullRequest, key, {
|
||||||
|
timeToLive: "30 minutes",
|
||||||
|
reactivityKeys: [REACTIVITY_KEYS.git(key.cwd)],
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
|
||||||
|
export const gitResolvePullRequestAtom = Atom.family(
|
||||||
|
(input: { readonly cwd: string | null; readonly reference: string | null }) =>
|
||||||
|
Atom.readable(
|
||||||
|
(get): AsyncResult.AsyncResult<GitResolvePullRequestResult, unknown> => {
|
||||||
|
if (input.cwd === null || input.reference === null) {
|
||||||
|
return AsyncResult.initial();
|
||||||
|
}
|
||||||
|
return get(
|
||||||
|
gitResolvePullRequestQueryAtom({
|
||||||
|
cwd: input.cwd,
|
||||||
|
reference: input.reference,
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
},
|
||||||
|
(refresh) => {
|
||||||
|
if (input.cwd !== null && input.reference !== null) {
|
||||||
|
refresh(
|
||||||
|
gitResolvePullRequestQueryAtom({
|
||||||
|
cwd: input.cwd,
|
||||||
|
reference: input.reference,
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
},
|
||||||
|
),
|
||||||
|
);
|
||||||
|
|
||||||
|
export function useGitStatuses(
|
||||||
|
cwds: ReadonlyArray<string>,
|
||||||
|
): ReadonlyArray<AsyncResult.AsyncResult<GitStatusResult, unknown>> {
|
||||||
|
const atoms = useMemo(() => {
|
||||||
|
const refreshInterval = refreshIntervalSignalAtom(Duration.seconds(60));
|
||||||
|
return cwds.map((cwd) => gitStatusAtom(cwd).pipe(Atom.makeRefreshOnSignal(refreshInterval)));
|
||||||
|
}, [cwds]);
|
||||||
|
const statusesAtom = useMemo(
|
||||||
|
() => Atom.readable((get) => atoms.map((atom) => get(atom))),
|
||||||
|
[atoms],
|
||||||
|
);
|
||||||
|
return useAtomValue(statusesAtom);
|
||||||
|
}
|
||||||
@@ -55,7 +55,6 @@ const rpcClientMock = {
|
|||||||
git: {
|
git: {
|
||||||
pull: vi.fn(),
|
pull: vi.fn(),
|
||||||
status: vi.fn(),
|
status: vi.fn(),
|
||||||
runStackedAction: vi.fn(),
|
|
||||||
listBranches: vi.fn(),
|
listBranches: vi.fn(),
|
||||||
createWorktree: vi.fn(),
|
createWorktree: vi.fn(),
|
||||||
removeWorktree: vi.fn(),
|
removeWorktree: vi.fn(),
|
||||||
|
|||||||
@@ -1,7 +1,4 @@
|
|||||||
import {
|
import {
|
||||||
type GitActionProgressEvent,
|
|
||||||
type GitRunStackedActionInput,
|
|
||||||
type GitRunStackedActionResult,
|
|
||||||
type NativeApi,
|
type NativeApi,
|
||||||
ORCHESTRATION_WS_METHODS,
|
ORCHESTRATION_WS_METHODS,
|
||||||
type ServerSettingsPatch,
|
type ServerSettingsPatch,
|
||||||
@@ -31,10 +28,6 @@ type RpcStreamMethod<TTag extends RpcTag> =
|
|||||||
? (listener: (event: TEvent) => void) => () => void
|
? (listener: (event: TEvent) => void) => () => void
|
||||||
: never;
|
: never;
|
||||||
|
|
||||||
interface GitRunStackedActionOptions {
|
|
||||||
readonly onProgress?: (event: GitActionProgressEvent) => void;
|
|
||||||
}
|
|
||||||
|
|
||||||
export interface WsRpcClient {
|
export interface WsRpcClient {
|
||||||
readonly dispose: () => Promise<void>;
|
readonly dispose: () => Promise<void>;
|
||||||
readonly terminal: {
|
readonly terminal: {
|
||||||
@@ -59,10 +52,6 @@ export interface WsRpcClient {
|
|||||||
readonly git: {
|
readonly git: {
|
||||||
readonly pull: RpcUnaryMethod<typeof WS_METHODS.gitPull>;
|
readonly pull: RpcUnaryMethod<typeof WS_METHODS.gitPull>;
|
||||||
readonly status: RpcUnaryMethod<typeof WS_METHODS.gitStatus>;
|
readonly status: RpcUnaryMethod<typeof WS_METHODS.gitStatus>;
|
||||||
readonly runStackedAction: (
|
|
||||||
input: GitRunStackedActionInput,
|
|
||||||
options?: GitRunStackedActionOptions,
|
|
||||||
) => Promise<GitRunStackedActionResult>;
|
|
||||||
readonly listBranches: RpcUnaryMethod<typeof WS_METHODS.gitListBranches>;
|
readonly listBranches: RpcUnaryMethod<typeof WS_METHODS.gitListBranches>;
|
||||||
readonly createWorktree: RpcUnaryMethod<typeof WS_METHODS.gitCreateWorktree>;
|
readonly createWorktree: RpcUnaryMethod<typeof WS_METHODS.gitCreateWorktree>;
|
||||||
readonly removeWorktree: RpcUnaryMethod<typeof WS_METHODS.gitRemoveWorktree>;
|
readonly removeWorktree: RpcUnaryMethod<typeof WS_METHODS.gitRemoveWorktree>;
|
||||||
@@ -136,25 +125,6 @@ export function createWsRpcClient(transport = new WsTransport()): WsRpcClient {
|
|||||||
git: {
|
git: {
|
||||||
pull: (input) => transport.request((client) => client[WS_METHODS.gitPull](input)),
|
pull: (input) => transport.request((client) => client[WS_METHODS.gitPull](input)),
|
||||||
status: (input) => transport.request((client) => client[WS_METHODS.gitStatus](input)),
|
status: (input) => transport.request((client) => client[WS_METHODS.gitStatus](input)),
|
||||||
runStackedAction: async (input, options) => {
|
|
||||||
let result: GitRunStackedActionResult | null = null;
|
|
||||||
|
|
||||||
await transport.requestStream(
|
|
||||||
(client) => client[WS_METHODS.gitRunStackedAction](input),
|
|
||||||
(event) => {
|
|
||||||
options?.onProgress?.(event);
|
|
||||||
if (event.kind === "action_finished") {
|
|
||||||
result = event.result;
|
|
||||||
}
|
|
||||||
},
|
|
||||||
);
|
|
||||||
|
|
||||||
if (result) {
|
|
||||||
return result;
|
|
||||||
}
|
|
||||||
|
|
||||||
throw new Error("Git action stream completed without a final result.");
|
|
||||||
},
|
|
||||||
listBranches: (input) =>
|
listBranches: (input) =>
|
||||||
transport.request((client) => client[WS_METHODS.gitListBranches](input)),
|
transport.request((client) => client[WS_METHODS.gitListBranches](input)),
|
||||||
createWorktree: (input) =>
|
createWorktree: (input) =>
|
||||||
|
|||||||
Reference in new issue
Block a user