deeper in atom

This commit is contained in:
Julius Marminge committed 2026-04-01 00:23:27 -07:00
1 parent 744f74442a
commit f8b6e5b330
15 files changed
+512 -618

No files matched your search

@@ -1,6 +1,8 @@
import type { GitBranch } from "@t3tools/contracts";
import { useQuery, useQueryClient } from "@tanstack/react-query";
import { useAtomRefresh, useAtomSet, useAtomValue } from "@effect/atom-react";
import { type GitBranch } from "@t3tools/contracts";
import { useVirtualizer } from "@tanstack/react-virtual";
import * as Option from "effect/Option";
import { AsyncResult } from "effect/unstable/reactivity";
import { ChevronDownIcon } from "lucide-react";
import {
type CSSProperties,
@@ -14,14 +16,14 @@ import {
useTransition,
} from "react";
import {
gitBranchesQueryOptions,
gitQueryKeys,
gitStatusQueryOptions,
invalidateGitQueries,
} from "../lib/gitReactQuery";
import { readNativeApi } from "../nativeApi";
import { parsePullRequestReference } from "../pullRequestReference";
import { REACTIVITY_KEYS } from "../rpc/client";
import {
gitBranchesAtom,
gitCheckoutMutationAtom,
gitCreateBranchMutationAtom,
gitStatusAtom,
} from "../rpc/gitAtoms";
import {
dedupeRemoteBranchesWithLocalMatches,
deriveLocalBranchNameFromRemoteRef,
@@ -84,19 +86,23 @@ export function BranchToolbarBranchSelector({
onCheckoutPullRequestRequest,
onComposerFocusRequest,
}: BranchToolbarBranchSelectorProps) {
const queryClient = useQueryClient();
const [isBranchMenuOpen, setIsBranchMenuOpen] = useState(false);
const [branchQuery, setBranchQuery] = useState("");
const deferredBranchQuery = useDeferredValue(branchQuery);
const branchesQuery = useQuery(gitBranchesQueryOptions(branchCwd));
const branchStatusQuery = useQuery(gitStatusQueryOptions(branchCwd));
const branchesResult = useAtomValue(gitBranchesAtom(branchCwd));
const branchStatusResult = useAtomValue(gitStatusAtom(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(
() => dedupeRemoteBranchesWithLocalMatches(branchesQuery.data?.branches ?? []),
[branchesQuery.data?.branches],
() => dedupeRemoteBranchesWithLocalMatches(branchesData?.branches ?? []),
[branchesData?.branches],
);
const currentGitBranch =
branchStatusQuery.data?.branch ?? branches.find((branch) => branch.current)?.name ?? null;
branchStatus?.branch ?? branches.find((branch) => branch.current)?.name ?? null;
const canonicalActiveBranch = resolveBranchToolbarValue({
envMode: effectiveEnvMode,
activeWorktreePath,
@@ -155,18 +161,18 @@ export function BranchToolbarBranchSelector({
(_currentBranch: string | null, optimisticBranch: string | null) => optimisticBranch,
);
const [isBranchActionPending, startBranchActionTransition] = useTransition();
const isBranchesLoading =
branches.length === 0 && (AsyncResult.isInitial(branchesResult) || branchesResult.waiting);
const shouldVirtualizeBranchList = filteredBranchPickerItems.length > 40;
const runBranchAction = (action: () => Promise<void>) => {
startBranchActionTransition(async () => {
await action().catch(() => undefined);
await invalidateGitQueries(queryClient).catch(() => undefined);
});
};
const selectBranch = (branch: GitBranch) => {
const api = readNativeApi();
if (!api || !branchCwd || isBranchActionPending) return;
if (!branchCwd || isBranchActionPending) return;
// In new-worktree mode, selecting a branch sets the base branch.
if (isSelectingWorktreeBase) {
@@ -200,8 +206,13 @@ export function BranchToolbarBranchSelector({
runBranchAction(async () => {
setOptimisticBranch(selectedBranchName);
try {
await api.git.checkout({ cwd: selectionTarget.checkoutCwd, branch: branch.name });
await invalidateGitQueries(queryClient);
await checkoutBranch({
payload: {
cwd: selectionTarget.checkoutCwd,
branch: branch.name,
},
reactivityKeys: [REACTIVITY_KEYS.git(selectionTarget.checkoutCwd)],
});
} catch (error) {
toastManager.add({
type: "error",
@@ -211,23 +222,14 @@ export function BranchToolbarBranchSelector({
return;
}
let nextBranchName = selectedBranchName;
if (branch.isRemote) {
const status = await api.git.status({ cwd: branchCwd }).catch(() => null);
if (status?.branch) {
nextBranchName = status.branch;
}
}
setOptimisticBranch(nextBranchName);
onSetThreadBranch(nextBranchName, selectionTarget.nextWorktreePath);
setOptimisticBranch(selectedBranchName);
onSetThreadBranch(selectedBranchName, selectionTarget.nextWorktreePath);
});
};
const createBranch = (rawName: string) => {
const name = rawName.trim();
const api = readNativeApi();
if (!api || !branchCwd || !name || isBranchActionPending) return;
if (!branchCwd || !name || isBranchActionPending) return;
setIsBranchMenuOpen(false);
onComposerFocusRequest?.();
@@ -236,9 +238,14 @@ export function BranchToolbarBranchSelector({
setOptimisticBranch(name);
try {
await api.git.createBranch({ cwd: branchCwd, branch: name });
await createGitBranch({
payload: { cwd: branchCwd, branch: name },
});
try {
await api.git.checkout({ cwd: branchCwd, branch: name });
await checkoutBranch({
payload: { cwd: branchCwd, branch: name },
reactivityKeys: [REACTIVITY_KEYS.git(branchCwd)],
});
} catch (error) {
toastManager.add({
type: "error",
@@ -287,11 +294,12 @@ export function BranchToolbarBranchSelector({
setBranchQuery("");
return;
}
void queryClient.invalidateQueries({
queryKey: gitQueryKeys.branches(branchCwd),
});
if (branchCwd) {
refreshBranches();
refreshBranchStatus();
}
},
[branchCwd, queryClient],
[branchCwd, refreshBranchStatus, refreshBranches],
);
const branchListScrollElementRef = useRef<HTMLDivElement | null>(null);
@@ -425,7 +433,7 @@ export function BranchToolbarBranchSelector({
<ComboboxTrigger
render={<Button variant="ghost" size="xs" />}
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>
<ChevronDownIcon />
@@ -32,6 +32,7 @@ import {
import { isMacPlatform } from "../lib/utils";
import { __resetNativeApiForTests } from "../nativeApi";
import { getRouter } from "../router";
import { resetAppAtomRegistryForTests } from "../rpc/atomRegistry";
import { useStore } from "../store";
import { BrowserWsRpcHarness, type NormalizedWsRpcRequestBody } from "../../test/wsRpcHarness";
import { estimateTimelineMessageHeight } from "./timelineHeight";
@@ -1121,6 +1122,7 @@ describe("ChatView timeline estimator parity (full app)", () => {
},
});
__resetNativeApiForTests();
resetAppAtomRegistryForTests();
await setViewport(DEFAULT_VIEWPORT);
localStorage.clear();
document.body.innerHTML = "";
@@ -1143,6 +1145,7 @@ describe("ChatView timeline estimator parity (full app)", () => {
afterEach(() => {
customWsRpcResolver = null;
document.body.innerHTML = "";
resetAppAtomRegistryForTests();
});
it.each(TEXT_VIEWPORT_MATRIX)(
+21 -10
View File
@@ -1,3 +1,4 @@
import { useAtomSet, useAtomValue } from "@effect/atom-react";
import {
type ApprovalRequestId,
DEFAULT_MODEL_BY_PROVIDER,
@@ -21,12 +22,13 @@ import {
TerminalOpenInput,
} from "@t3tools/contracts";
import { applyClaudePromptEffortPrefix, normalizeModelSlug } from "@t3tools/shared/model";
import * as Option from "effect/Option";
import { truncate } from "@t3tools/shared/String";
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 { useNavigate, useSearch } from "@tanstack/react-router";
import { gitBranchesQueryOptions, gitCreateWorktreeMutationOptions } from "~/lib/gitReactQuery";
import { AsyncResult } from "effect/unstable/reactivity";
import { projectSearchEntriesQueryOptions } from "~/lib/projectReactQuery";
import { isElectron } from "../env";
import { parseDiffRouteSearch, stripDiffSearchParams } from "../diffRouteSearch";
@@ -106,6 +108,8 @@ import { Separator } from "./ui/separator";
import { cn, randomUUID } from "~/lib/utils";
import { Tooltip, TooltipPopup, TooltipTrigger } from "./ui/tooltip";
import { toastManager } from "./ui/toast";
import { gitBranchesAtom, gitCreateWorktreeMutationAtom } from "~/rpc/gitAtoms";
import { REACTIVITY_KEYS } from "~/rpc/client";
import { decodeProjectScriptKeybindingRule } from "~/lib/projectScriptKeybindings";
import { type NewProjectScriptInput } from "./ProjectScriptsControl";
import {
@@ -423,8 +427,7 @@ export default function ChatView({ threadId }: ChatViewProps) {
select: (params) => parseDiffRouteSearch(params),
});
const { resolvedTheme } = useTheme();
const queryClient = useQueryClient();
const createWorktreeMutation = useMutation(gitCreateWorktreeMutationOptions({ queryClient }));
const createWorktree = useAtomSet(gitCreateWorktreeMutationAtom, { mode: "promise" });
const composerDraft = useComposerThreadDraft(threadId);
const prompt = composerDraft.prompt;
const composerImages = composerDraft.images;
@@ -1201,7 +1204,8 @@ export default function ChatView({ threadId }: ChatViewProps) {
(debouncerState) => ({ isPending: debouncerState.isPending }),
);
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 availableEditors = useServerAvailableEditors();
const modelOptionsByProvider = useMemo(
@@ -1338,7 +1342,7 @@ export default function ChatView({ threadId }: ChatViewProps) {
});
}, [activeProjectCwd, activeThreadWorktreePath]);
// Default true while loading to avoid toolbar flicker.
const isGitRepo = branchesQuery.data?.isRepo ?? true;
const isGitRepo = branches?.isRepo ?? true;
const terminalShortcutLabelOptions = useMemo(
() => ({
context: {
@@ -2787,10 +2791,17 @@ export default function ChatView({ threadId }: ChatViewProps) {
if (baseBranchForWorktree) {
beginLocalDispatch({ preparingWorktree: true });
const newBranch = buildTemporaryWorktreeBranchName();
const result = await createWorktreeMutation.mutateAsync({
cwd: activeProject.cwd,
branch: baseBranchForWorktree,
newBranch,
const result = await createWorktree({
payload: {
cwd: activeProject.cwd,
branch: baseBranchForWorktree,
path: null,
newBranch,
},
reactivityKeys: [
REACTIVITY_KEYS.git(activeProject.cwd),
REACTIVITY_KEYS.project(activeProject.cwd),
],
});
nextThreadBranch = result.worktree.branch;
nextThreadWorktreePath = result.worktree.path;
+7 -3
View File
@@ -1,8 +1,11 @@
import { useAtomValue } from "@effect/atom-react";
import { parsePatchFiles } from "@pierre/diffs";
import { FileDiff, type FileDiffMetadata, Virtualizer } from "@pierre/diffs/react";
import { useQuery } from "@tanstack/react-query";
import { useNavigate, useParams, useSearch } from "@tanstack/react-router";
import { ThreadId, type TurnId } from "@t3tools/contracts";
import * as Option from "effect/Option";
import { AsyncResult } from "effect/unstable/reactivity";
import {
ChevronLeftIcon,
ChevronRightIcon,
@@ -19,10 +22,10 @@ import {
useState,
} from "react";
import { openInPreferredEditor } from "../editorPreferences";
import { gitBranchesQueryOptions } from "~/lib/gitReactQuery";
import { checkpointDiffQueryOptions } from "~/lib/providerReactQuery";
import { cn } from "~/lib/utils";
import { readNativeApi } from "../nativeApi";
import { gitBranchesAtom } from "../rpc/gitAtoms";
import { resolvePathLinkTarget } from "../terminal-links";
import { parseDiffRouteSearch, stripDiffSearchParams } from "../diffRouteSearch";
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,
);
const activeCwd = activeThread?.worktreePath ?? activeProject?.cwd;
const gitBranchesQuery = useQuery(gitBranchesQueryOptions(activeCwd ?? null));
const isGitRepo = gitBranchesQuery.data?.isRepo ?? true;
const gitBranchesResult = useAtomValue(gitBranchesAtom(activeCwd ?? null));
const gitBranches = Option.getOrUndefined(AsyncResult.value(gitBranchesResult));
const isGitRepo = gitBranches?.isRepo ?? true;
const { turnDiffSummaries, inferredCheckpointTurnCountByTurnId } =
useTurnDiffSummaries(activeThread);
const orderedTurnDiffSummaries = useMemo(
+149 -95
View File
@@ -1,10 +1,13 @@
import { useAtomRefresh, useAtomSet, useAtomValue } from "@effect/atom-react";
import type {
GitActionProgressEvent,
GitRunStackedActionInput,
GitStackedAction,
GitStatusResult,
ThreadId,
} 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 { ChevronDownIcon, CloudUploadIcon, GitCommitIcon, InfoIcon } from "lucide-react";
import { GitHubIcon } from "./Icons";
@@ -38,18 +41,18 @@ import { ScrollArea } from "~/components/ui/scroll-area";
import { Textarea } from "~/components/ui/textarea";
import { toastManager } from "~/components/ui/toast";
import { openInPreferredEditor } from "~/editorPreferences";
import {
gitBranchesQueryOptions,
gitInitMutationOptions,
gitMutationKeys,
gitPullMutationOptions,
gitRunStackedActionMutationOptions,
gitStatusQueryOptions,
invalidateGitQueries,
} from "~/lib/gitReactQuery";
import { randomUUID } from "~/lib/utils";
import { resolvePathLinkTarget } from "~/terminal-links";
import { readNativeApi } from "~/nativeApi";
import {
gitBranchesAtom,
gitInitMutationAtom,
gitPullMutationAtom,
gitRunStackedActionMutationAtom,
gitRunStackedActionProgressAtom,
gitStatusAtom,
} from "~/rpc/gitAtoms";
import { REACTIVITY_KEYS } from "~/rpc/client";
interface GitActionsControlProps {
gitCwd: string | null;
@@ -112,6 +115,13 @@ function resolveProgressDescription(progress: ActiveGitActionProgress): string |
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({
item,
gitStatus,
@@ -208,7 +218,6 @@ export default function GitActionsControl({ gitCwd, activeThreadId }: GitActions
() => (activeThreadId ? { threadId: activeThreadId } : undefined),
[activeThreadId],
);
const queryClient = useQueryClient();
const [isCommitDialogOpen, setIsCommitDialogOpen] = useState(false);
const [dialogCommitMessage, setDialogCommitMessage] = useState("");
const [excludedFiles, setExcludedFiles] = useState<ReadonlySet<string>>(new Set());
@@ -231,9 +240,22 @@ export default function GitActionsControl({ gitCwd, activeThreadId }: GitActions
});
}, [threadToastData]);
const { data: gitStatus = null, error: gitStatusError } = useQuery(gitStatusQueryOptions(gitCwd));
const { data: branchList = null } = useQuery(gitBranchesQueryOptions(gitCwd));
const gitStatusResult = useAtomValue(gitStatusAtom(gitCwd));
const branchesResult = useAtomValue(gitBranchesAtom(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.
const isRepo = branchList?.isRepo ?? true;
const hasOriginRemote = branchList?.hasOriginRemote ?? false;
@@ -242,9 +264,10 @@ export default function GitActionsControl({ gitCwd, activeThreadId }: GitActions
!!gitStatus?.branch && !!currentBranch && gitStatus.branch !== currentBranch;
useEffect(() => {
if (!isGitStatusOutOfSync) return;
void invalidateGitQueries(queryClient);
}, [isGitStatusOutOfSync, queryClient]);
if (!isGitStatusOutOfSync || !gitCwd) return;
refreshGitStatus();
refreshGitBranches();
}, [gitCwd, isGitStatusOutOfSync, refreshGitBranches, refreshGitStatus]);
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 allSelected = excludedFiles.size === 0;
const noneSelected = selectedFiles.length === 0;
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 isRunStackedActionRunning = runStackedActionResult.waiting;
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 branchName = gitStatusForActions?.branch;
if (!branchName) return false;
@@ -307,6 +349,59 @@ export default function GitActionsControl({ gitCwd, activeThreadId }: GitActions
};
}, [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 api = readNativeApi();
if (!api) {
@@ -415,69 +510,17 @@ export default function GitActionsControl({ gitCwd, activeThreadId }: GitActions
});
}
const applyProgressEvent = (event: GitActionProgressEvent) => {
const progress = activeGitActionProgressRef.current;
if (!progress) {
return;
}
if (gitCwd && event.cwd !== gitCwd) {
return;
}
if (progress.actionId !== event.actionId) {
return;
}
if (!gitCwd) {
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":
// 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({
const promise = runImmediateGitAction({
actionId,
cwd: gitCwd,
action,
...(commitMessage ? { commitMessage } : {}),
...(featureBranch ? { featureBranch } : {}),
...(filePaths ? { filePaths } : {}),
onProgress: applyProgressEvent,
});
try {
@@ -624,7 +667,10 @@ export default function GitActionsControl({ gitCwd, activeThreadId }: GitActions
return;
}
if (quickAction.kind === "run_pull") {
const promise = pullMutation.mutateAsync();
if (!gitCwd) {
return;
}
const promise = pullCurrentBranch(gitCwd);
toastManager.promise(promise, {
loading: { title: "Pulling...", data: threadToastData },
success: (result) => ({
@@ -656,7 +702,7 @@ export default function GitActionsControl({ gitCwd, activeThreadId }: GitActions
if (quickAction.action) {
void runGitActionWithToast({ action: quickAction.action });
}
}, [openExistingPr, pullMutation, quickAction, threadToastData]);
}, [gitCwd, openExistingPr, pullCurrentBranch, quickAction, threadToastData]);
const openDialogForMenuItem = useCallback(
(item: GitActionMenuItem) => {
@@ -733,10 +779,15 @@ export default function GitActionsControl({ gitCwd, activeThreadId }: GitActions
<Button
variant="outline"
size="xs"
disabled={initMutation.isPending}
onClick={() => initMutation.mutate()}
disabled={isInitPending}
onClick={() => {
if (!gitCwd) {
return;
}
void initializeGit(gitCwd).catch(() => undefined);
}}
>
{initMutation.isPending ? "Initializing..." : "Initialize Git"}
{isInitPending ? "Initializing..." : "Initialize Git"}
</Button>
) : (
<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" />
<Menu
onOpenChange={(open) => {
if (open) void invalidateGitQueries(queryClient);
if (open && gitCwd) {
refreshGitStatus();
refreshGitBranches();
}
}}
>
<MenuTrigger
@@ -1,14 +1,13 @@
import type { GitResolvePullRequestResult } from "@t3tools/contracts";
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
import { useAtomSet, useAtomValue } from "@effect/atom-react";
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 {
gitPreparePullRequestThreadMutationOptions,
gitResolvePullRequestQueryOptions,
} from "~/lib/gitReactQuery";
import { cn } from "~/lib/utils";
import { parsePullRequestReference } from "~/pullRequestReference";
import { gitResolvePullRequestAtom, gitPreparePullRequestThreadMutationAtom } from "~/rpc/gitAtoms";
import { REACTIVITY_KEYS } from "~/rpc/client";
import { Button } from "./ui/button";
import {
Dialog,
@@ -30,6 +29,10 @@ interface PullRequestThreadDialogProps {
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({
open,
cwd,
@@ -37,23 +40,28 @@ export function PullRequestThreadDialog({
onOpenChange,
onPrepared,
}: PullRequestThreadDialogProps) {
const queryClient = useQueryClient();
const referenceInputRef = useRef<HTMLInputElement>(null);
const [reference, setReference] = useState(initialReference ?? "");
const [referenceDirty, setReferenceDirty] = useState(false);
const [preparingMode, setPreparingMode] = useState<"local" | "worktree" | null>(null);
const [prepareFollowupErrorMessage, setPrepareFollowupErrorMessage] = useState<string | null>(
null,
);
const [debouncedReference, referenceDebouncer] = useDebouncedValue(
reference,
{ wait: 450 },
(debouncerState) => ({ isPending: debouncerState.isPending }),
);
const resetPreparePullRequestThread = useAtomSet(gitPreparePullRequestThreadMutationAtom);
useEffect(() => {
if (!open) return;
setReference(initialReference ?? "");
setReferenceDirty(false);
setPreparingMode(null);
}, [initialReference, open]);
setPrepareFollowupErrorMessage(null);
resetPreparePullRequestThread(Atom.Reset);
}, [initialReference, open, resetPreparePullRequestThread]);
useEffect(() => {
if (!open) return;
@@ -68,41 +76,35 @@ export function PullRequestThreadDialog({
const parsedReference = parsePullRequestReference(reference);
const parsedDebouncedReference = parsePullRequestReference(debouncedReference);
const resolvePullRequestQuery = useQuery(
gitResolvePullRequestQueryOptions({
cwd,
const resolvePullRequestResult = useAtomValue(
gitResolvePullRequestAtom({
cwd: open ? cwd : null,
reference: open ? parsedDebouncedReference : null,
}),
);
const cachedPullRequest = useMemo(() => {
if (!cwd || !parsedReference) {
return null;
}
const cached = queryClient.getQueryData<GitResolvePullRequestResult>([
"git",
"pull-request",
cwd,
parsedReference,
]);
return cached?.pullRequest ?? null;
}, [cwd, parsedReference, queryClient]);
const preparePullRequestThreadMutation = useMutation(
gitPreparePullRequestThreadMutationOptions({ cwd, queryClient }),
const preparePullRequestThread = useAtomSet(gitPreparePullRequestThreadMutationAtom, {
mode: "promise",
});
const preparePullRequestThreadResult = useAtomValue(gitPreparePullRequestThreadMutationAtom);
const resolvePullRequestData = Option.getOrUndefined(AsyncResult.value(resolvePullRequestResult));
const resolvePullRequestError = Option.getOrNull(
Option.map(AsyncResult.cause(resolvePullRequestResult), (cause) => Cause.squash(cause)),
);
const isPreparingPullRequestThread = preparingMode !== null;
const liveResolvedPullRequest =
parsedReference !== null && parsedReference === parsedDebouncedReference
? (resolvePullRequestQuery.data?.pullRequest ?? null)
? (resolvePullRequestData?.pullRequest ?? null)
: null;
const resolvedPullRequest = liveResolvedPullRequest ?? cachedPullRequest;
const resolvedPullRequest = liveResolvedPullRequest;
const isResolving =
open &&
parsedReference !== null &&
resolvedPullRequest === null &&
(referenceDebouncer.state.isPending ||
parsedReference !== parsedDebouncedReference ||
resolvePullRequestQuery.isPending ||
resolvePullRequestQuery.isFetching);
AsyncResult.isInitial(resolvePullRequestResult) ||
resolvePullRequestResult.waiting);
const statusTone = useMemo(() => {
switch (resolvedPullRequest?.state) {
case "merged":
@@ -115,6 +117,11 @@ export function PullRequestThreadDialog({
return "text-muted-foreground";
}
}, [resolvedPullRequest?.state]);
const preparePullRequestThreadErrorMessage = AsyncResult.match(preparePullRequestThreadResult, {
onInitial: () => null,
onSuccess: () => null,
onFailure: (error) => Cause.pretty(error.cause),
});
const handleConfirm = useCallback(
async (mode: "local" | "worktree") => {
@@ -125,29 +132,36 @@ export function PullRequestThreadDialog({
if (!parsedReference || !resolvedPullRequest || !cwd) {
return;
}
setPrepareFollowupErrorMessage(null);
setPreparingMode(mode);
try {
const result = await preparePullRequestThreadMutation.mutateAsync({
reference: parsedReference,
mode,
const result = await preparePullRequestThread({
payload: {
cwd,
reference: parsedReference,
mode,
},
reactivityKeys: [REACTIVITY_KEYS.git(cwd)],
});
await onPrepared({
branch: result.branch,
worktreePath: result.worktreePath,
});
onOpenChange(false);
try {
await onPrepared({
branch: result.branch,
worktreePath: result.worktreePath,
});
onOpenChange(false);
} catch (error) {
setPrepareFollowupErrorMessage(
toErrorMessage(error, "Failed to prepare pull request thread."),
);
}
} catch {
return;
} finally {
setPreparingMode(null);
}
},
[
cwd,
onOpenChange,
onPrepared,
parsedReference,
preparePullRequestThreadMutation,
resolvedPullRequest,
],
[cwd, onOpenChange, onPrepared, parsedReference, preparePullRequestThread, resolvedPullRequest],
);
const validationMessage = !referenceDirty
@@ -159,21 +173,17 @@ export function PullRequestThreadDialog({
: null;
const errorMessage =
validationMessage ??
(resolvedPullRequest === null && resolvePullRequestQuery.isError
? resolvePullRequestQuery.error instanceof Error
? resolvePullRequestQuery.error.message
(resolvedPullRequest === null && AsyncResult.isFailure(resolvePullRequestResult)
? resolvePullRequestError instanceof Error
? resolvePullRequestError.message
: "Failed to resolve pull request."
: preparePullRequestThreadMutation.error instanceof Error
? preparePullRequestThreadMutation.error.message
: preparePullRequestThreadMutation.error
? "Failed to prepare pull request thread."
: null);
: (prepareFollowupErrorMessage ?? preparePullRequestThreadErrorMessage));
return (
<Dialog
open={open}
onOpenChange={(nextOpen) => {
if (!preparePullRequestThreadMutation.isPending) {
if (!isPreparingPullRequestThread) {
onOpenChange(nextOpen);
}
}}
@@ -202,7 +212,7 @@ export function PullRequestThreadDialog({
return;
}
event.preventDefault();
if (!isResolving && !preparePullRequestThreadMutation.isPending) {
if (!isResolving && !isPreparingPullRequestThread) {
void handleConfirm("local");
}
}}
@@ -241,7 +251,7 @@ export function PullRequestThreadDialog({
variant="outline"
size="sm"
onClick={() => onOpenChange(false)}
disabled={preparePullRequestThreadMutation.isPending}
disabled={isPreparingPullRequestThread}
>
Cancel
</Button>
@@ -252,12 +262,7 @@ export function PullRequestThreadDialog({
onClick={() => {
void handleConfirm("local");
}}
disabled={
!cwd ||
!resolvedPullRequest ||
isResolving ||
preparePullRequestThreadMutation.isPending
}
disabled={!cwd || !resolvedPullRequest || isResolving || isPreparingPullRequestThread}
>
{preparingMode === "local" ? "Preparing local..." : "Local"}
</Button>
@@ -267,12 +272,7 @@ export function PullRequestThreadDialog({
onClick={() => {
void handleConfirm("worktree");
}}
disabled={
!cwd ||
!resolvedPullRequest ||
isResolving ||
preparePullRequestThreadMutation.isPending
}
disabled={!cwd || !resolvedPullRequest || isResolving || isPreparingPullRequestThread}
>
{preparingMode === "worktree" ? "Preparing worktree..." : "Worktree"}
</Button>
+8 -11
View File
@@ -12,6 +12,8 @@ import {
} from "lucide-react";
import { ProjectFavicon } from "./ProjectFavicon";
import { autoAnimate } from "@formkit/auto-animate";
import { Option } from "effect";
import { AsyncResult } from "effect/unstable/reactivity";
import {
useCallback,
useEffect,
@@ -44,7 +46,6 @@ import {
ThreadId,
type GitStatusResult,
} from "@t3tools/contracts";
import { useQueries } from "@tanstack/react-query";
import { useLocation, useNavigate, useParams } from "@tanstack/react-router";
import {
type SidebarProjectSortOrder,
@@ -65,8 +66,8 @@ import {
threadTraversalDirectionFromCommand,
} from "../keybindings";
import { derivePendingApprovals, derivePendingUserInputs } from "../session-logic";
import { gitStatusQueryOptions } from "../lib/gitReactQuery";
import { readNativeApi } from "../nativeApi";
import { useGitStatuses } from "../rpc/gitAtoms";
import { useComposerDraftStore } from "../composerDraftStore";
import { useHandleNewThread } from "../hooks/useHandleNewThread";
@@ -556,19 +557,15 @@ export default function Sidebar() {
],
[threadGitTargets],
);
const threadGitStatusQueries = useQueries({
queries: threadGitStatusCwds.map((cwd) => ({
...gitStatusQueryOptions(cwd),
staleTime: 30_000,
refetchInterval: 60_000,
})),
});
const threadGitStatusResults = useGitStatuses(threadGitStatusCwds);
const prByThreadId = useMemo(() => {
const statusByCwd = new Map<string, GitStatusResult>();
for (let index = 0; index < threadGitStatusCwds.length; index += 1) {
const cwd = threadGitStatusCwds[index];
if (!cwd) continue;
const status = threadGitStatusQueries[index]?.data;
const status = threadGitStatusResults[index]
? Option.getOrUndefined(AsyncResult.value(threadGitStatusResults[index]!))
: undefined;
if (status) {
statusByCwd.set(cwd, status);
}
@@ -582,7 +579,7 @@ export default function Sidebar() {
map.set(target.threadId, branchMatches ? (status?.pr ?? null) : null);
}
return map;
}, [threadGitStatusCwds, threadGitStatusQueries, threadGitTargets]);
}, [threadGitStatusCwds, threadGitStatusResults, threadGitTargets]);
const openPrLink = useCallback((event: React.MouseEvent<HTMLElement>, prUrl: string) => {
event.preventDefault();