Skip to content

Commit 4db2ffc

Browse files
refactor(mobile): branch picker owns its search and checkout guard (pingdotgg#25067)
Co-authored-by: Claude Opus 5.5 <[email protected]>
1 parent f995643 commit 4db2ffc

2 files changed

Lines changed: 45 additions & 74 deletions

File tree

‎apps/mobile/src/features/threads/NewTaskContextPickerScreens.tsx‎

Lines changed: 41 additions & 38 deletions
Original file line numberDiff line numberDiff line change
@@ -20,7 +20,8 @@ import {
2020
} from "@t3tools/client-runtime/state/runtime";
2121
import * as Haptics from "expo-haptics";
2222
import { useNavigation } from "@react-navigation/native";
23-
import { useEffect, useRef, useState, type ReactNode } from "react";
23+
import { useRef, useState, type ReactNode } from "react";
24+
import { sanitizeNewRefName } from "@t3tools/shared/git";
2425
import { Platform, Pressable, ScrollView, View } from "react-native";
2526
import { useSafeAreaInsets } from "react-native-safe-area-context";
2627

@@ -42,6 +43,9 @@ import {
4243
import { useNativeMailSearchToolbar } from "../../native/use-native-mail-search-toolbar";
4344
import { branchBadgeLabel, useNewTaskFlow } from "./new-task-flow-provider";
4445
import { checkoutNewTaskBranch } from "./checkout-new-task-branch";
46+
import { filterNewTaskBranches } from "./new-task-context-presentation";
47+
import { useDebouncedValue, usePaginatedBranches } from "../../state/queries";
48+
import { setPendingConnectionError } from "../../state/use-remote-environment-registry";
4549

4650
import { useEnvironmentPresentation } from "../../state/presentation";
4751
import { useRemoteConnections } from "../../state/use-remote-environment-registry";
@@ -52,6 +56,8 @@ import {
5256
} from "../connection/ConnectionDiagnosisDetails";
5357
import { environmentStatusText } from "../connection/environmentStatusText";
5458

59+
const BRANCH_SEARCH_DEBOUNCE_MS = 150;
60+
5561
function EnvironmentPickerRow(props: {
5662
environmentId: EnvironmentId;
5763
title: string;
@@ -240,26 +246,22 @@ export function NewTaskBranchPickerRouteScreen() {
240246
const switchRef = useAtomCommand(vcsEnvironment.switchRef, { reportFailure: false });
241247
const [switchingBranchName, setSwitchingBranchName] = useState<string | null>(null);
242248
const selectingBranchNameRef = useRef<string | null>(null);
243-
const allowSelectionNavigationRef = useRef(false);
244-
const mountedRef = useRef(true);
245-
246-
useEffect(() => {
247-
mountedRef.current = true;
248-
return () => {
249-
mountedRef.current = false;
250-
flow.setBranchQuery("");
251-
};
252-
}, [flow.setBranchQuery]);
253-
254-
useEffect(
255-
() =>
256-
navigation.addListener("beforeRemove", (event) => {
257-
if (selectingBranchNameRef.current !== null && !allowSelectionNavigationRef.current) {
258-
event.preventDefault();
259-
}
260-
}),
261-
[navigation],
262-
);
249+
const [branchQuery, setBranchQuery] = useState("");
250+
const branchSearchQuery = sanitizeNewRefName(branchQuery);
251+
const debouncedBranchQuery = useDebouncedValue(branchSearchQuery, BRANCH_SEARCH_DEBOUNCE_MS);
252+
const branchState = usePaginatedBranches({
253+
environmentId: flow.selectedProject?.environmentId ?? null,
254+
cwd: flow.selectedProject?.workspaceRoot || null,
255+
query: debouncedBranchQuery,
256+
});
257+
const branchesLoading =
258+
branchSearchQuery !== debouncedBranchQuery ||
259+
(branchState.isPending && branchState.data === null);
260+
const refreshBranches = () => {
261+
if (!flow.selectedProject) return;
262+
setPendingConnectionError(null);
263+
branchState.refresh();
264+
};
263265

264266
const selectBranch = async (branch: VcsRef) => {
265267
const needsCheckout = shouldCheckoutNewTaskBranch({
@@ -279,17 +281,22 @@ export function NewTaskBranchPickerRouteScreen() {
279281
return;
280282
}
281283
setSwitchingBranchName(branch.name);
284+
// The guard belongs to this checkout: back actions are refused while it is
285+
// in flight, and our own goBack runs after it is lifted.
286+
const releaseRemovalGuard = navigation.addListener("beforeRemove", (event) => {
287+
event.preventDefault();
288+
});
282289
const result = await checkoutNewTaskBranch({
283290
branch,
284291
project,
285292
workspaceMode: flow.workspaceMode,
286293
readRefs,
287294
switchRef,
288-
});
289-
if (mountedRef.current) setSwitchingBranchName(null);
295+
}).finally(releaseRemovalGuard);
296+
setSwitchingBranchName(null);
290297
if (result._tag === "Failure") {
291298
selectingBranchNameRef.current = null;
292-
if (mountedRef.current && navigation.isFocused() && !isAtomCommandInterrupted(result)) {
299+
if (navigation.isFocused() && !isAtomCommandInterrupted(result)) {
293300
const error = squashAtomCommandFailure(result);
294301
Dialog.alert(
295302
"Could not switch branch",
@@ -301,37 +308,33 @@ export function NewTaskBranchPickerRouteScreen() {
301308

302309
// Checkout already changed Git; persist the draft selection even if the sheet dismissed mid-command.
303310
flow.selectBranch(result.value);
304-
if (!mountedRef.current || !navigation.isFocused()) {
311+
if (!navigation.isFocused()) {
305312
selectingBranchNameRef.current = null;
306313
return;
307314
}
308-
flow.setBranchQuery("");
309-
// beforeRemove blocks dismissal while a switch is in flight; this one is ours.
310-
allowSelectionNavigationRef.current = true;
311315
navigation.goBack();
312-
allowSelectionNavigationRef.current = false;
313316
selectingBranchNameRef.current = null;
314317
};
315318

316319
return (
317320
<BranchPickerScreen
318321
title={flow.workspaceMode === "worktree" ? "Base branch" : "Branch"}
319322
project={flow.selectedProject}
320-
branches={flow.filteredBranches}
323+
branches={filterNewTaskBranches(branchState.refs, branchQuery)}
321324
selectedBranchName={
322325
flow.selectedBranchName ??
323326
flow.availableBranches.find((branch) => branch.current)?.name ??
324327
flow.availableBranches.find((branch) => branch.isDefault)?.name ??
325328
null
326329
}
327-
query={flow.branchQuery}
328-
onQueryChange={flow.setBranchQuery}
329-
loading={flow.branchesLoading}
330-
error={flow.branchesError}
331-
refreshing={flow.branchesFetchingNextPage}
332-
hasMore={flow.hasMoreBranches}
333-
onRefresh={flow.loadBranches}
334-
onLoadMore={flow.loadMoreBranches}
330+
query={branchQuery}
331+
onQueryChange={setBranchQuery}
332+
loading={branchesLoading}
333+
error={branchState.error}
334+
refreshing={branchState.isFetchingNextPage}
335+
hasMore={branchState.data?.nextCursor !== null && branchState.data?.nextCursor !== undefined}
336+
onRefresh={refreshBranches}
337+
onLoadMore={branchState.loadNext}
335338
selectionDisabled={switchingBranchName !== null}
336339
onSelect={selectBranch}
337340
worktree={

‎apps/mobile/src/features/threads/new-task-flow-provider.tsx‎

Lines changed: 4 additions & 36 deletions
Original file line numberDiff line numberDiff line change
@@ -24,7 +24,6 @@ import {
2424
T3_PROJECT_FILE_NAME,
2525
ThreadId,
2626
} from "@t3tools/contracts";
27-
import { sanitizeNewRefName } from "@t3tools/shared/git";
2827
import { threadContextsOutsideEnvironment } from "@t3tools/shared/composerContextReferences";
2928
import { resolveNewThreadEnvMode, resolveProjectSettings } from "@t3tools/shared/projectSettings";
3029
import { parseT3ProjectFile } from "@t3tools/shared/t3ProjectFile";
@@ -80,7 +79,7 @@ import {
8079
rememberModelOptions,
8180
withRememberedModelOptions,
8281
} from "../../state/use-model-option-memory";
83-
import { useBranches, useDebouncedValue, usePaginatedBranches } from "../../state/queries";
82+
import { useBranches, usePaginatedBranches } from "../../state/queries";
8483
import { vcsEnvironment } from "../../state/vcs";
8584
import {
8685
flattenQueuedThreadMessages,
@@ -117,7 +116,6 @@ import {
117116
} from "../../state/legacy-plan-mode";
118117
import { useLegacyPlanModeState } from "./use-legacy-plan-mode-enabled";
119118
import {
120-
filterNewTaskBranches,
121119
resolveNewTaskBranchWorktreePath,
122120
resolveNewTaskLocalWorkspaceSelection,
123121
resolveNewTaskWorkspaceSelection,
@@ -128,8 +126,6 @@ import { useOlderSettledCount } from "../../state/olderSettledShelf";
128126

129127
type WorkspaceMode = "local" | "worktree";
130128

131-
const BRANCH_SEARCH_DEBOUNCE_MS = 150;
132-
133129
function pendingTaskDraftKey(messageId: string): string {
134130
return `pending-task:${messageId}`;
135131
}
@@ -182,11 +178,7 @@ type NewTaskFlowContextValue = {
182178
readonly prompt: string;
183179
readonly attachments: ReadonlyArray<DraftComposerAttachment>;
184180
readonly submitting: boolean;
185-
readonly branchQuery: string;
186181
readonly branchesLoading: boolean;
187-
readonly branchesError: string | null;
188-
readonly branchesFetchingNextPage: boolean;
189-
readonly hasMoreBranches: boolean;
190182
readonly availableBranches: ReadonlyArray<VcsRef>;
191183
readonly currentCheckoutBranchName: string | null;
192184
readonly runtimeMode: RuntimeMode;
@@ -204,7 +196,6 @@ type NewTaskFlowContextValue = {
204196
readonly selectedModelOption: ModelOption | null;
205197
readonly selectedProviderStatus: ServerProvider | null;
206198
readonly providerGroups: ReadonlyArray<ProviderGroup>;
207-
readonly filteredBranches: ReadonlyArray<VcsRef>;
208199
readonly reset: () => void;
209200
readonly setProject: (project: EnvironmentProject) => void;
210201
/** Returns false if the existing draft is gone, allowing fallback to a fresh draft. */
@@ -238,9 +229,7 @@ type NewTaskFlowContextValue = {
238229
readonly removeAttachment: (imageId: string) => void;
239230
readonly clearAttachments: () => void;
240231
readonly setSubmitting: (value: boolean) => void;
241-
readonly setBranchQuery: (value: string) => void;
242232
readonly loadBranches: () => void;
243-
readonly loadMoreBranches: () => void;
244233
readonly setRuntimeMode: (value: RuntimeMode) => void;
245234
readonly setInteractionMode: (value: ProviderInteractionMode) => void;
246235
readonly setSelectedModelOptions: (
@@ -287,7 +276,6 @@ export function NewTaskFlowProvider(
287276
const [selectedProjectKey, setSelectedProjectKey] = useState<string | null>(null);
288277
const [activeDraftKey, setActiveDraftKey] = useState<string | null>(null);
289278
const [submitting, setSubmitting] = useState(false);
290-
const [branchQuery, setBranchQuery] = useState("");
291279
const [expandedProvider, setExpandedProvider] = useState<string | null>(null);
292280
const [editingPendingTask, setEditingPendingTask] = useState<QueuedThreadMessage | null>(null);
293281
const pendingLocalBranchSyncDraftKeysRef = useRef(new Set<string>());
@@ -300,7 +288,6 @@ export function NewTaskFlowProvider(
300288
setSelectedProjectKey(null);
301289
setActiveDraftKey(null);
302290
setSubmitting(false);
303-
setBranchQuery("");
304291
setExpandedProvider(null);
305292
pendingLocalBranchSyncDraftKeysRef.current.clear();
306293
const editing = editingPendingTaskRef.current;
@@ -684,28 +671,17 @@ export function NewTaskFlowProvider(
684671
}
685672
replaceComposerDraftAttachments(selectedProjectDraftKey, []);
686673
};
687-
const branchSearchQuery = sanitizeNewRefName(branchQuery);
688-
const debouncedBranchQuery = useDebouncedValue(branchSearchQuery, BRANCH_SEARCH_DEBOUNCE_MS);
689-
const branchTarget = {
674+
const branchState = usePaginatedBranches({
690675
environmentId: selectedProject?.environmentId ?? null,
691676
cwd: selectedProject?.workspaceRoot || null,
692-
query: debouncedBranchQuery,
693-
};
694-
const branchState = usePaginatedBranches(branchTarget);
695-
const branchSearchIsDebouncing = branchSearchQuery !== debouncedBranchQuery;
696-
const branchesLoading =
697-
branchSearchIsDebouncing || (branchState.isPending && branchState.data === null);
698-
const branchesFetchingNextPage = branchState.isFetchingNextPage;
699-
const hasMoreBranches =
700-
branchState.data?.nextCursor !== null && branchState.data?.nextCursor !== undefined;
677+
});
678+
const branchesLoading = branchState.isPending && branchState.data === null;
701679
const allBranchRefs = branchState.refs;
702680
const availableBranches = pipe(
703681
allBranchRefs,
704682
Arr.filter((branch) => !branch.isRemote),
705683
);
706684

707-
const filteredBranches = filterNewTaskBranches(allBranchRefs, branchQuery);
708-
709685
const carryDraftContentTo = (project: EnvironmentProject) => {
710686
const target = { environmentId: project.environmentId, projectId: project.id };
711687
if (activeDraftKey !== null && isNewTaskDraftKey(activeDraftKey)) {
@@ -884,7 +860,6 @@ export function NewTaskFlowProvider(
884860
};
885861

886862
const refreshBranches = branchState.refresh;
887-
const loadMoreBranches = branchState.loadNext;
888863
const loadBranches = () => {
889864
if (!selectedProject) {
890865
return;
@@ -1163,11 +1138,7 @@ export function NewTaskFlowProvider(
11631138
prompt,
11641139
attachments,
11651140
submitting,
1166-
branchQuery,
11671141
branchesLoading,
1168-
branchesError: branchState.error,
1169-
branchesFetchingNextPage,
1170-
hasMoreBranches,
11711142
availableBranches,
11721143
currentCheckoutBranchName,
11731144
runtimeMode,
@@ -1182,7 +1153,6 @@ export function NewTaskFlowProvider(
11821153
selectedModelOption,
11831154
selectedProviderStatus,
11841155
providerGroups,
1185-
filteredBranches,
11861156
reset,
11871157
setProject,
11881158
openDraft,
@@ -1203,9 +1173,7 @@ export function NewTaskFlowProvider(
12031173
removeAttachment,
12041174
clearAttachments,
12051175
setSubmitting,
1206-
setBranchQuery,
12071176
loadBranches,
1208-
loadMoreBranches,
12091177
setRuntimeMode,
12101178
setInteractionMode,
12111179
setSelectedModelOptions,

0 commit comments

Comments
 (0)