Skip to content
TypeScript

refactor(mobile): branch picker owns its search and checkout guard (#25067)

Julius Marminge4db2ffc8d933
diff --git a/apps/mobile/src/features/threads/NewTaskContextPickerScreens.tsx b/apps/mobile/src/features/threads/NewTaskContextPickerScreens.tsx
index 8a56f3c1606..04c9a4bf4c9 100644
--- a/apps/mobile/src/features/threads/NewTaskContextPickerScreens.tsx
+++ b/apps/mobile/src/features/threads/NewTaskContextPickerScreens.tsx
@@ -20,7 +20,8 @@ import {
} from "@t3tools/client-runtime/state/runtime";
import * as Haptics from "expo-haptics";
import { useNavigation } from "@react-navigation/native";
-import { useEffect, useRef, useState, type ReactNode } from "react";
+import { useRef, useState, type ReactNode } from "react";
+import { sanitizeNewRefName } from "@t3tools/shared/git";
import { Platform, Pressable, ScrollView, View } from "react-native";
import { useSafeAreaInsets } from "react-native-safe-area-context";
@@ -42,6 +43,9 @@ import {
import { useNativeMailSearchToolbar } from "../../native/use-native-mail-search-toolbar";
import { branchBadgeLabel, useNewTaskFlow } from "./new-task-flow-provider";
import { checkoutNewTaskBranch } from "./checkout-new-task-branch";
+import { filterNewTaskBranches } from "./new-task-context-presentation";
+import { useDebouncedValue, usePaginatedBranches } from "../../state/queries";
+import { setPendingConnectionError } from "../../state/use-remote-environment-registry";
import { useEnvironmentPresentation } from "../../state/presentation";
import { useRemoteConnections } from "../../state/use-remote-environment-registry";
@@ -52,6 +56,8 @@ import {
} from "../connection/ConnectionDiagnosisDetails";
import { environmentStatusText } from "../connection/environmentStatusText";
+const BRANCH_SEARCH_DEBOUNCE_MS = 150;
+
function EnvironmentPickerRow(props: {
environmentId: EnvironmentId;
title: string;
@@ -240,26 +246,22 @@ export function NewTaskBranchPickerRouteScreen() {
const switchRef = useAtomCommand(vcsEnvironment.switchRef, { reportFailure: false });
const [switchingBranchName, setSwitchingBranchName] = useState<string | null>(null);
const selectingBranchNameRef = useRef<string | null>(null);
- const allowSelectionNavigationRef = useRef(false);
- const mountedRef = useRef(true);
-
- useEffect(() => {
- mountedRef.current = true;
- return () => {
- mountedRef.current = false;
- flow.setBranchQuery("");
- };
- }, [flow.setBranchQuery]);
-
- useEffect(
- () =>
- navigation.addListener("beforeRemove", (event) => {
- if (selectingBranchNameRef.current !== null && !allowSelectionNavigationRef.current) {
- event.preventDefault();
- }
- }),
- [navigation],
- );
+ const [branchQuery, setBranchQuery] = useState("");
+ const branchSearchQuery = sanitizeNewRefName(branchQuery);
+ const debouncedBranchQuery = useDebouncedValue(branchSearchQuery, BRANCH_SEARCH_DEBOUNCE_MS);
+ const branchState = usePaginatedBranches({
+ environmentId: flow.selectedProject?.environmentId ?? null,
+ cwd: flow.selectedProject?.workspaceRoot || null,
+ query: debouncedBranchQuery,
+ });
+ const branchesLoading =
+ branchSearchQuery !== debouncedBranchQuery ||
+ (branchState.isPending && branchState.data === null);
+ const refreshBranches = () => {
+ if (!flow.selectedProject) return;
+ setPendingConnectionError(null);
+ branchState.refresh();
+ };
const selectBranch = async (branch: VcsRef) => {
const needsCheckout = shouldCheckoutNewTaskBranch({
@@ -279,17 +281,22 @@ export function NewTaskBranchPickerRouteScreen() {
return;
}
setSwitchingBranchName(branch.name);
+ // The guard belongs to this checkout: back actions are refused while it is
+ // in flight, and our own goBack runs after it is lifted.
+ const releaseRemovalGuard = navigation.addListener("beforeRemove", (event) => {
+ event.preventDefault();
+ });
const result = await checkoutNewTaskBranch({
branch,
project,
workspaceMode: flow.workspaceMode,
readRefs,
switchRef,
- });
- if (mountedRef.current) setSwitchingBranchName(null);
+ }).finally(releaseRemovalGuard);
+ setSwitchingBranchName(null);
if (result._tag === "Failure") {
selectingBranchNameRef.current = null;
- if (mountedRef.current && navigation.isFocused() && !isAtomCommandInterrupted(result)) {
+ if (navigation.isFocused() && !isAtomCommandInterrupted(result)) {
const error = squashAtomCommandFailure(result);
Dialog.alert(
"Could not switch branch",
@@ -301,15 +308,11 @@ export function NewTaskBranchPickerRouteScreen() {
// Checkout already changed Git; persist the draft selection even if the sheet dismissed mid-command.
flow.selectBranch(result.value);
- if (!mountedRef.current || !navigation.isFocused()) {
+ if (!navigation.isFocused()) {
selectingBranchNameRef.current = null;
return;
}
- flow.setBranchQuery("");
- // beforeRemove blocks dismissal while a switch is in flight; this one is ours.
- allowSelectionNavigationRef.current = true;
navigation.goBack();
- allowSelectionNavigationRef.current = false;
selectingBranchNameRef.current = null;
};
@@ -317,21 +320,21 @@ export function NewTaskBranchPickerRouteScreen() {
<BranchPickerScreen
title={flow.workspaceMode === "worktree" ? "Base branch" : "Branch"}
project={flow.selectedProject}
- branches={flow.filteredBranches}
+ branches={filterNewTaskBranches(branchState.refs, branchQuery)}
selectedBranchName={
flow.selectedBranchName ??
flow.availableBranches.find((branch) => branch.current)?.name ??
flow.availableBranches.find((branch) => branch.isDefault)?.name ??
null
}
- query={flow.branchQuery}
- onQueryChange={flow.setBranchQuery}
- loading={flow.branchesLoading}
- error={flow.branchesError}
- refreshing={flow.branchesFetchingNextPage}
- hasMore={flow.hasMoreBranches}
- onRefresh={flow.loadBranches}
- onLoadMore={flow.loadMoreBranches}
+ query={branchQuery}
+ onQueryChange={setBranchQuery}
+ loading={branchesLoading}
+ error={branchState.error}
+ refreshing={branchState.isFetchingNextPage}
+ hasMore={branchState.data?.nextCursor !== null && branchState.data?.nextCursor !== undefined}
+ onRefresh={refreshBranches}
+ onLoadMore={branchState.loadNext}
selectionDisabled={switchingBranchName !== null}
onSelect={selectBranch}
worktree={
diff --git a/apps/mobile/src/features/threads/new-task-flow-provider.tsx b/apps/mobile/src/features/threads/new-task-flow-provider.tsx
index 7218e89f50c..e961f9e4dfa 100644
--- a/apps/mobile/src/features/threads/new-task-flow-provider.tsx
+++ b/apps/mobile/src/features/threads/new-task-flow-provider.tsx
@@ -24,7 +24,6 @@ import {
T3_PROJECT_FILE_NAME,
ThreadId,
} from "@t3tools/contracts";
-import { sanitizeNewRefName } from "@t3tools/shared/git";
import { threadContextsOutsideEnvironment } from "@t3tools/shared/composerContextReferences";
import { resolveNewThreadEnvMode, resolveProjectSettings } from "@t3tools/shared/projectSettings";
import { parseT3ProjectFile } from "@t3tools/shared/t3ProjectFile";
@@ -80,7 +79,7 @@ import {
rememberModelOptions,
withRememberedModelOptions,
} from "../../state/use-model-option-memory";
-import { useBranches, useDebouncedValue, usePaginatedBranches } from "../../state/queries";
+import { useBranches, usePaginatedBranches } from "../../state/queries";
import { vcsEnvironment } from "../../state/vcs";
import {
flattenQueuedThreadMessages,
@@ -117,7 +116,6 @@ import {
} from "../../state/legacy-plan-mode";
import { useLegacyPlanModeState } from "./use-legacy-plan-mode-enabled";
import {
- filterNewTaskBranches,
resolveNewTaskBranchWorktreePath,
resolveNewTaskLocalWorkspaceSelection,
resolveNewTaskWorkspaceSelection,
@@ -128,8 +126,6 @@ import { useOlderSettledCount } from "../../state/olderSettledShelf";
type WorkspaceMode = "local" | "worktree";
-const BRANCH_SEARCH_DEBOUNCE_MS = 150;
-
function pendingTaskDraftKey(messageId: string): string {
return `pending-task:${messageId}`;
}
@@ -182,11 +178,7 @@ type NewTaskFlowContextValue = {
readonly prompt: string;
readonly attachments: ReadonlyArray<DraftComposerAttachment>;
readonly submitting: boolean;
- readonly branchQuery: string;
readonly branchesLoading: boolean;
- readonly branchesError: string | null;
- readonly branchesFetchingNextPage: boolean;
- readonly hasMoreBranches: boolean;
readonly availableBranches: ReadonlyArray<VcsRef>;
readonly currentCheckoutBranchName: string | null;
readonly runtimeMode: RuntimeMode;
@@ -204,7 +196,6 @@ type NewTaskFlowContextValue = {
readonly selectedModelOption: ModelOption | null;
readonly selectedProviderStatus: ServerProvider | null;
readonly providerGroups: ReadonlyArray<ProviderGroup>;
- readonly filteredBranches: ReadonlyArray<VcsRef>;
readonly reset: () => void;
readonly setProject: (project: EnvironmentProject) => void;
/** Returns false if the existing draft is gone, allowing fallback to a fresh draft. */
@@ -238,9 +229,7 @@ type NewTaskFlowContextValue = {
readonly removeAttachment: (imageId: string) => void;
readonly clearAttachments: () => void;
readonly setSubmitting: (value: boolean) => void;
- readonly setBranchQuery: (value: string) => void;
readonly loadBranches: () => void;
- readonly loadMoreBranches: () => void;
readonly setRuntimeMode: (value: RuntimeMode) => void;
readonly setInteractionMode: (value: ProviderInteractionMode) => void;
readonly setSelectedModelOptions: (
@@ -287,7 +276,6 @@ export function NewTaskFlowProvider(
const [selectedProjectKey, setSelectedProjectKey] = useState<string | null>(null);
const [activeDraftKey, setActiveDraftKey] = useState<string | null>(null);
const [submitting, setSubmitting] = useState(false);
- const [branchQuery, setBranchQuery] = useState("");
const [expandedProvider, setExpandedProvider] = useState<string | null>(null);
const [editingPendingTask, setEditingPendingTask] = useState<QueuedThreadMessage | null>(null);
const pendingLocalBranchSyncDraftKeysRef = useRef(new Set<string>());
@@ -300,7 +288,6 @@ export function NewTaskFlowProvider(
setSelectedProjectKey(null);
setActiveDraftKey(null);
setSubmitting(false);
- setBranchQuery("");
setExpandedProvider(null);
pendingLocalBranchSyncDraftKeysRef.current.clear();
const editing = editingPendingTaskRef.current;
@@ -684,28 +671,17 @@ export function NewTaskFlowProvider(
}
replaceComposerDraftAttachments(selectedProjectDraftKey, []);
};
- const branchSearchQuery = sanitizeNewRefName(branchQuery);
- const debouncedBranchQuery = useDebouncedValue(branchSearchQuery, BRANCH_SEARCH_DEBOUNCE_MS);
- const branchTarget = {
+ const branchState = usePaginatedBranches({
environmentId: selectedProject?.environmentId ?? null,
cwd: selectedProject?.workspaceRoot || null,
- query: debouncedBranchQuery,
- };
- const branchState = usePaginatedBranches(branchTarget);
- const branchSearchIsDebouncing = branchSearchQuery !== debouncedBranchQuery;
- const branchesLoading =
- branchSearchIsDebouncing || (branchState.isPending && branchState.data === null);
- const branchesFetchingNextPage = branchState.isFetchingNextPage;
- const hasMoreBranches =
- branchState.data?.nextCursor !== null && branchState.data?.nextCursor !== undefined;
+ });
+ const branchesLoading = branchState.isPending && branchState.data === null;
const allBranchRefs = branchState.refs;
const availableBranches = pipe(
allBranchRefs,
Arr.filter((branch) => !branch.isRemote),
);
- const filteredBranches = filterNewTaskBranches(allBranchRefs, branchQuery);
-
const carryDraftContentTo = (project: EnvironmentProject) => {
const target = { environmentId: project.environmentId, projectId: project.id };
if (activeDraftKey !== null && isNewTaskDraftKey(activeDraftKey)) {
@@ -884,7 +860,6 @@ export function NewTaskFlowProvider(
};
const refreshBranches = branchState.refresh;
- const loadMoreBranches = branchState.loadNext;
const loadBranches = () => {
if (!selectedProject) {
return;
@@ -1163,11 +1138,7 @@ export function NewTaskFlowProvider(
prompt,
attachments,
submitting,
- branchQuery,
branchesLoading,
- branchesError: branchState.error,
- branchesFetchingNextPage,
- hasMoreBranches,
availableBranches,
currentCheckoutBranchName,
runtimeMode,
@@ -1182,7 +1153,6 @@ export function NewTaskFlowProvider(
selectedModelOption,
selectedProviderStatus,
providerGroups,
- filteredBranches,
reset,
setProject,
openDraft,
@@ -1203,9 +1173,7 @@ export function NewTaskFlowProvider(
removeAttachment,
clearAttachments,
setSubmitting,
- setBranchQuery,
loadBranches,
- loadMoreBranches,
setRuntimeMode,
setInteractionMode,
setSelectedModelOptions,