TypeScript
fix(mobile): a draft route's branch checkout runs once, even across a reconnect (#25712)
Julius Marminged145077b4f7d
diff --git a/apps/mobile/src/App.tsx b/apps/mobile/src/App.tsxindex 2033b45d563..53d3717ebad 100644--- a/apps/mobile/src/App.tsx+++ b/apps/mobile/src/App.tsx@@ -9,10 +9,10 @@ import { GestureHandlerRootView } from "react-native-gesture-handler";import { KeyboardProvider } from "react-native-keyboard-controller";import { SafeAreaProvider } from "react-native-safe-area-context";import {- createNavigationContainerRef,createStaticNavigation,getActionFromState,getStateFromPath,+ type NavigationState,} from "@react-navigation/native";import { RegistryContext } from "@effect/atom-react";@@ -52,6 +52,8 @@ import {} from "./features/workspace/workspace-selection-store";import { workspaceDetailLinkAction } from "./features/workspace/workspace-detail-selection";import { NativeLayoutMetricsProvider } from "./native/native-layout-metrics";+import { attachRootNavigation, rootNavigationRef } from "./lib/rootNavigation";+import { pruneNewTaskBranchCheckouts } from "./features/threads/NewTaskDraftRouteScreen";import "../global.css";@@ -84,7 +86,15 @@ const appLinking = {};const Navigation = createStaticNavigation(RootStack);-const navigationRef = createNavigationContainerRef();++function handleNavigationStateChange(state: NavigationState | undefined): void {+ recordWorkspaceSelections(state);+ if (state) pruneNewTaskBranchCheckouts(state);+}++function handleNavigationReady(): void {+ handleNavigationStateChange(rootNavigationRef.getRootState());+}declare const module: { readonly hot?: FoundationHotModule } | undefined;@@ -148,11 +158,11 @@ function AppContent() {<NativeLayoutMetricsProvider><IncomingShareProvider><Navigation- ref={navigationRef}+ ref={attachRootNavigation}linking={appLinking}- onReady={() => recordWorkspaceSelections(navigationRef.getRootState())}+ onReady={handleNavigationReady}theme={navigationTheme}- onStateChange={recordWorkspaceSelections}+ onStateChange={handleNavigationStateChange}/></IncomingShareProvider><Dialog.Host />diff --git a/apps/mobile/src/features/layout/AdaptiveWorkspaceLayout.tsx b/apps/mobile/src/features/layout/AdaptiveWorkspaceLayout.tsxindex e2d758ee960..8ecbdce2709 100644--- a/apps/mobile/src/features/layout/AdaptiveWorkspaceLayout.tsx+++ b/apps/mobile/src/features/layout/AdaptiveWorkspaceLayout.tsx@@ -1,6 +1,6 @@import { SafeAreaInsetsContext, useSafeAreaInsets } from "react-native-safe-area-context";import { AdaptiveWorkspaceContext, useAdaptiveWorkspaceLayout } from "./adaptive-workspace-context";-import { createDeferredNavigation } from "./deferred-navigation";+import { threadSelectionDeferral } from "./deferred-navigation";import { uuidv4 } from "../../lib/uuid";import type {EnvironmentProject,@@ -491,10 +491,9 @@ function AdaptiveWorkspaceLayoutContent(};const handleOpenSettings = () => openWorkspaceTab("settings");- const deferredThreadSelection = useMemo(() => createDeferredNavigation(), []);/** The one way to show a page in the detail column; see `selectWorkspaceDetail`. */function handleSelectDetail(detail: WorkspaceDetail, sheet?: WorkspaceDetailSheet) {- deferredThreadSelection.run(() => {+ threadSelectionDeferral.run(() => {if (Platform.OS === "android") Keyboard.dismiss();setFileInspectorPreferredVisible(false);if (layout.primarySidebarOverlaysContent) setPrimarySidebarVisible(false);@@ -770,7 +769,6 @@ function AdaptiveWorkspaceLayoutContent(fileInspector,primarySidebarSearchQuery,startNewTask: handleStartNewTask,- deferThreadSelectionUntil: deferredThreadSelection.waitFor,selectDetail: handleSelectDetail,activateAuxiliaryPaneRole,registerWorkspaceInspector,diff --git a/apps/mobile/src/features/layout/adaptive-workspace-context.ts b/apps/mobile/src/features/layout/adaptive-workspace-context.tsindex 7cfeb3e76fb..a22459e6ecd 100644--- a/apps/mobile/src/features/layout/adaptive-workspace-context.ts+++ b/apps/mobile/src/features/layout/adaptive-workspace-context.ts@@ -20,7 +20,6 @@ interface AdaptiveWorkspaceContextValue {readonly fileInspector: FileInspectorPaneLayout;readonly primarySidebarSearchQuery: string;readonly startNewTask: () => void;- readonly deferThreadSelectionUntil: (operation: Promise<unknown>) => void;/** Use `useSelectWorkspaceDetail`, which also works outside the layout. */readonly selectDetail?: (detail: WorkspaceDetail, sheet?: WorkspaceDetailSheet) => void;readonly activateAuxiliaryPaneRole: (role: WorkspaceAuxiliaryPaneRole) => () => void;@@ -67,7 +66,6 @@ export const AdaptiveWorkspaceContext = createContext<AdaptiveWorkspaceContextVafileInspector: compactFileInspector,primarySidebarSearchQuery: "",startNewTask: () => undefined,- deferThreadSelectionUntil: () => undefined,activateAuxiliaryPaneRole: () => () => undefined,registerWorkspaceInspector: () => () => undefined,setPrimarySidebarSearchQuery: () => undefined,diff --git a/apps/mobile/src/features/layout/deferred-navigation.ts b/apps/mobile/src/features/layout/deferred-navigation.tsindex 8da68b10b39..579e1fed0a1 100644--- a/apps/mobile/src/features/layout/deferred-navigation.ts+++ b/apps/mobile/src/features/layout/deferred-navigation.ts@@ -20,3 +20,9 @@ export function createDeferredNavigation() {},};}++/**+ * The app's one thread-selection gate: a new-task branch checkout holds+ * split-view thread selection until the draft route can be left.+ */+export const threadSelectionDeferral = createDeferredNavigation();diff --git a/apps/mobile/src/features/threads/NewTaskDraftRouteScreen.test.tsx b/apps/mobile/src/features/threads/NewTaskDraftRouteScreen.test.tsxnew file mode 100644index 00000000000..ca955b2cd37--- /dev/null+++ b/apps/mobile/src/features/threads/NewTaskDraftRouteScreen.test.tsx@@ -0,0 +1,191 @@+import type { ReactNode } from "react";+import { act, useSyncExternalStore } from "react";+import { createRoot } from "react-dom/client";+import { AsyncResult } from "effect/reactivity";+import { expect, it, vi } from "vite-plus/test";++interface Snapshot {+ readonly projects: ReadonlyArray<{+ readonly environmentId: string;+ readonly id: string;+ readonly workspaceRoot: string;+ }>;+ readonly catalog: {+ readonly isLoadingConnections: boolean;+ readonly hasLoadedShellSnapshot: boolean;+ readonly hasConnectingEnvironment: boolean;+ readonly connectionError: string | null;+ };+}++const harness = vi.hoisted(() => {+ const listeners = new Set<() => void>();+ const state: { snapshot: Snapshot | null } = { snapshot: null };+ return {+ state,+ set(next: Snapshot) {+ state.snapshot = next;+ for (const listener of listeners) listener();+ },+ subscribe(listener: () => void) {+ listeners.add(listener);+ return () => listeners.delete(listener);+ },+ route: { key: "thread-route", name: "Thread", params: {} as object },+ reset: () => undefined,+ checkout: vi.fn(),+ draftProjectRefs: [] as unknown[],+ // Hook results stay stable across renders, as the real hooks' are. Only+ // main's screen reads these (see the main-comparison mocks below).+ layout: { deferThreadSelectionUntil: () => undefined },+ navigation: { goBack: () => undefined },+ preventContext: { preventedRoutes: {} },+ };+});++function useSnapshot(): Snapshot {+ return useSyncExternalStore(harness.subscribe, () => harness.state.snapshot!);+}++vi.mock("react-native", () => ({+ View: ({ children }: { children: ReactNode }) => <div>{children}</div>,+}));+vi.mock("../../components/ui/AppText", () => ({+ AppText: ({ children }: { children: ReactNode }) => <span>{children}</span>,+}));+vi.mock("../../components/ui/Dialog", () => ({ alert: vi.fn() }));+vi.mock("../../native/StackHeader", () => ({ NativeStackScreenOptions: () => null }));+vi.mock("./ThreadScreenHost", () => ({+ ThreadScreenFallback: ({ children }: { children: ReactNode }) => <>{children}</>,+}));+vi.mock("./NewTaskDraftScreen", () => ({+ NewTaskDraftScreen: (props: { initialProjectRef: { branch?: string | null } }) => {+ harness.draftProjectRefs.push(props.initialProjectRef);+ return <p>draft on {props.initialProjectRef.branch}</p>;+ },+}));+vi.mock("./new-task-context-presentation", () => ({+ resolveNewTaskBranchWorktreePath: () => null,+}));+vi.mock("./new-task-flow-provider", () => ({+ useNewTaskFlow: () => harness,+}));+vi.mock("./checkout-new-task-branch", () => ({ checkoutNewTaskBranch: harness.checkout }));+// Main-comparison mocks: this screen no longer uses them, but main's screen+// did (deferThreadSelectionUntil, useAtomCommand, useNavigation). They stay so+// this test can run against main's screen and fail there for the right reason+// (a second checkout) instead of on an unmockable import.+vi.mock("../layout/AdaptiveWorkspaceLayout", () => ({+ useAdaptiveWorkspaceLayout: () => harness.layout,+}));+vi.mock("../../state/use-atom-command", () => ({ useAtomCommand: () => harness.checkout }));+vi.mock("../../state/entities", () => ({ useProjects: () => useSnapshot().projects }));+vi.mock("../../state/workspace", () => ({+ useWorkspaceState: () => ({ state: useSnapshot().catalog }),+}));+vi.mock("../../state/vcs", () => ({ vcsEnvironment: { readRefs: {}, switchRef: {} } }));+vi.mock("@react-navigation/native", () => ({+ CommonActions: { goBack: () => ({ type: "GO_BACK" }) },+ createNavigationContainerRef: () => ({ current: null }),+ // Main-comparison only, like the mocks above.+ useNavigation: () => harness.navigation,+ useRoute: () => harness.route,+ usePreventRemove: () => undefined,+ usePreventRemoveContext: () => harness.preventContext,+}));++import { NewTaskDraftRouteScreen } from "./NewTaskDraftRouteScreen";++const project = { environmentId: "env-1", id: "project-1", workspaceRoot: "/repo" };+const connected: Snapshot["catalog"] = {+ isLoadingConnections: false,+ hasLoadedShellSnapshot: true,+ hasConnectingEnvironment: false,+ connectionError: null,+};++// The project can vanish while the catalog still loads, or while it reports ready.+it.each([+ ["while the catalog reloads", { ...connected, isLoadingConnections: true }],+ ["while the catalog stays ready", connected],+])(+ "checks the branch out once when a reconnect drops and restores the project %s",+ async (gap, gapCatalog) => {+ // Checkouts live in a module table keyed by route, so each case uses its own route.+ const routeKey = `thread-route ${gap}`;+ (globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true;+ const firstCheckout = Promise.withResolvers<unknown>();+ harness.checkout.mockReturnValueOnce(firstCheckout.promise);+ harness.checkout.mockResolvedValue(+ AsyncResult.success({ name: "feature", current: true, isDefault: false, worktreePath: null }),+ );+ harness.set({ projects: [project], catalog: connected });+ const draft = { environmentId: "env-1", projectId: "project-1", branch: "feature" };+ harness.route = { key: routeKey, name: "Thread", params: { draft } };++ const container = document.createElement("div");+ const root = createRoot(container);+ using _root = { [Symbol.dispose]: () => act(() => root.unmount()) };+ act(() =>+ root.render(+ <NewTaskDraftRouteScreen+ route={{ key: routeKey, name: "Thread", params: draft } as never}+ />,+ ),+ );+ await vi.waitFor(() => expect(harness.checkout).toHaveBeenCalledTimes(1));++ // The connection drops while the checkout runs, then the project comes back.+ act(() => harness.set({ projects: [], catalog: gapCatalog }));+ act(() => harness.set({ projects: [project], catalog: connected }));+ await act(async () => {+ firstCheckout.resolve(+ AsyncResult.success({+ name: "feature",+ current: true,+ isDefault: false,+ worktreePath: null,+ }),+ );+ });++ await vi.waitFor(() =>+ expect(+ harness.checkout.mock.calls.length > 1 || container.textContent === "draft on feature",+ ).toBe(true),+ );+ expect(harness.checkout).toHaveBeenCalledTimes(1);+ expect(container.textContent).toBe("draft on feature");+ },+);++it("hands the draft screen the same project ref across re-renders", async () => {+ (globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true;+ harness.checkout.mockReset();+ harness.draftProjectRefs.length = 0;+ harness.checkout.mockResolvedValue(+ AsyncResult.success({ name: "other", current: true, isDefault: false, worktreePath: null }),+ );+ harness.set({ projects: [project], catalog: connected });+ const draft = { environmentId: "env-1", projectId: "project-1", branch: "other" };+ harness.route = { key: "stable-route", name: "Thread", params: { draft } };++ const container = document.createElement("div");+ const root = createRoot(container);+ using _root = { [Symbol.dispose]: () => act(() => root.unmount()) };+ act(() =>+ root.render(+ <NewTaskDraftRouteScreen+ route={{ key: "stable-route", name: "Thread", params: draft } as never}+ />,+ ),+ );+ await vi.waitFor(() => expect(container.textContent).toBe("draft on other"));++ // The draft screen re-applies its route project when this identity changes,+ // and that write re-renders the route; an unstable ref loops forever.+ act(() => harness.set({ projects: [{ ...project }], catalog: { ...connected } }));+ // A stable ref lets the compiled screen skip re-rendering the draft screen at all; an unstable+ // one re-renders it with a second ref.+ expect(new Set(harness.draftProjectRefs).size).toBe(1);+});diff --git a/apps/mobile/src/features/threads/NewTaskDraftRouteScreen.tsx b/apps/mobile/src/features/threads/NewTaskDraftRouteScreen.tsxindex 73a43b7340d..2bdcb47ec48 100644--- a/apps/mobile/src/features/threads/NewTaskDraftRouteScreen.tsx+++ b/apps/mobile/src/features/threads/NewTaskDraftRouteScreen.tsx@@ -1,26 +1,36 @@-import { useAdaptiveWorkspaceLayout } from "../layout/AdaptiveWorkspaceLayout";import { useNewTaskFlow } from "./new-task-flow-provider";import * as Dialog from "../../components/ui/Dialog";import {- useNavigation,+ CommonActions,useRoute,usePreventRemove,usePreventRemoveContext,type StaticScreenProps,} from "@react-navigation/native";-import { useEffect, useLayoutEffect, useMemo, useRef, useState } from "react";+import { useEffect, useLayoutEffect, useState } from "react";import { View } from "react-native";+import { useAtomValue } from "@effect/atom-react";import {isAtomCommandInterrupted,+ runAtomCommand,squashAtomCommandFailure,} from "@t3tools/client-runtime/state/runtime";+import { AsyncResult, Atom } from "effect/reactivity";import { AppText as Text } from "../../components/ui/AppText";import { useProjects } from "../../state/entities";-import { useAtomCommand } from "../../state/use-atom-command";+import { appAtomRegistry } from "../../state/atom-registry";+import { rootNavigationRef } from "../../lib/rootNavigation";+import { threadSelectionDeferral } from "../layout/deferred-navigation";import { useWorkspaceState } from "../../state/workspace";import { vcsEnvironment } from "../../state/vcs";import { checkoutNewTaskBranch } from "./checkout-new-task-branch";import { resolveNewTaskBranchWorktreePath } from "./new-task-context-presentation";+import {+ type BranchCheckoutResult,+ branchCheckoutRequestKey,+ makeNewTaskBranchCheckouts,+} from "./new-task-branch-checkout";+import { liveNewTaskFlowKeys, newTaskFlowKey } from "./new-task-flow-state";import { NativeStackScreenOptions } from "../../native/StackHeader";import { ThreadScreenFallback } from "./ThreadScreenHost";@@ -29,11 +39,59 @@ import { NewTaskDraftScreen } from "./NewTaskDraftScreen";import type { NewTaskDraftRouteParams } from "./thread-route-state";export type { NewTaskDraftRouteParams } from "./thread-route-state";+const branchCheckouts = makeNewTaskBranchCheckouts({+ run: (request) =>+ checkoutNewTaskBranch({+ branch: {+ name: request.branch,+ current: false,+ isDefault: false,+ worktreePath: request.worktreePath,+ },+ project:+ request.environmentId !== null && request.workspaceRoot !== null+ ? { environmentId: request.environmentId, workspaceRoot: request.workspaceRoot }+ : null,+ workspaceMode: "local",+ readRefs: (input) =>+ runAtomCommand(appAtomRegistry, vcsEnvironment.readRefs, input, {+ reportFailure: false,+ }),+ switchRef: (input) =>+ runAtomCommand(appAtomRegistry, vcsEnvironment.switchRef, input, {+ reportFailure: false,+ }),+ }),+ holdNavigation: threadSelectionDeferral.waitFor,+ onFailure: (request, result) => {+ if (!isAtomCommandInterrupted(result)) {+ const error = squashAtomCommandFailure(result);+ Dialog.alert(+ "Could not switch branch",+ error instanceof Error ? error.message : "The branch could not be checked out.",+ );+ }+ rootNavigationRef.dispatch({+ ...CommonActions.goBack(),+ source: request.routeKey,+ target: rootNavigationRef.getRootState()?.key,+ });+ },+});++/** Abandons the branch checkouts of draft routes that left the stack. */+export function pruneNewTaskBranchCheckouts(state: Parameters<typeof liveNewTaskFlowKeys>[0]) {+ branchCheckouts.prune(liveNewTaskFlowKeys(state));+}++const idleBranchCheckoutAtom = Atom.make(AsyncResult.initial<BranchCheckoutResult, never>()).pipe(+ Atom.withLabel("mobile:new-task-branch-checkout:idle"),+);+export function NewTaskDraftRouteScreen({ route }: StaticScreenProps<NewTaskDraftRouteParams>) {const currentRoute = useRoute();- const params = useMemo(() => route.params ?? {}, [route.params]);+ const params = route.params ?? {};const { reset } = useNewTaskFlow();- const { deferThreadSelectionUntil } = useAdaptiveWorkspaceLayout();const [initialized, setInitialized] = useState(false);useLayoutEffect(() => {reset();@@ -43,40 +101,41 @@ export function NewTaskDraftRouteScreen({ route }: StaticScreenProps<NewTaskDrafconst draftId = Array.isArray(params.draftId) ? params.draftId[0] : params.draftId;const projects = useProjects();const { state: catalogState } = useWorkspaceState();- const navigation = useNavigation();- const readRefs = useAtomCommand(vcsEnvironment.readRefs, { reportFailure: false });- const switchRef = useAtomCommand(vcsEnvironment.switchRef, { reportFailure: false });- const initialProjectRef = useMemo(- () => ({- environmentId: Array.isArray(params.environmentId)- ? params.environmentId[0]- : params.environmentId,- projectId: Array.isArray(params.projectId) ? params.projectId[0] : params.projectId,- branch: params.branch,- worktreePath: params.worktreePath,- cloning: (Array.isArray(params.cloning) ? params.cloning[0] : params.cloning) === "1",- }),- [params],- );+ const initialProjectRef = {+ environmentId: Array.isArray(params.environmentId)+ ? params.environmentId[0]+ : params.environmentId,+ projectId: Array.isArray(params.projectId) ? params.projectId[0] : params.projectId,+ branch: params.branch,+ worktreePath: params.worktreePath,+ cloning: (Array.isArray(params.cloning) ? params.cloning[0] : params.cloning) === "1",+ };- const [preparation, setPreparation] = useState<{- request: typeof initialProjectRef;- result: Awaited<ReturnType<typeof checkoutNewTaskBranch>>;- workspaceRoot: string | undefined;- } | null>(null);const project = projects.find((candidate) =>candidate.environmentId === initialProjectRef.environmentId &&candidate.id === initialProjectRef.projectId,);- const environmentId = project?.environmentId;+ // A project can drop out of the list and come back while its catalog stays ready. The checkout+ // keeps the last project this route resolved, so that gap reads the same checkout.+ const [resolvedProject, setResolvedProject] = useState<Pick<+ NonNullable<typeof project>,+ "environmentId" | "workspaceRoot"+ > | null>(null);+ if (+ project &&+ (resolvedProject?.environmentId !== project.environmentId ||+ resolvedProject.workspaceRoot !== project.workspaceRoot)+ ) {+ setResolvedProject({+ environmentId: project.environmentId,+ workspaceRoot: project.workspaceRoot,+ });+ }+ const checkoutProject = project ?? resolvedProject;const workspaceRoot = project?.workspaceRoot;const needsPreparation = Boolean(initialProjectRef.branch && !draftId);-- const [pendingCheckouts, setPendingCheckouts] = useState(0);- const checkoutTail = useRef(Promise.resolve());- const committedCheckoutReleases = useRef(new Set<() => void>());const waitingForProject =!project &&(catalogState.isLoadingConnections ||@@ -84,99 +143,62 @@ export function NewTaskDraftRouteScreen({ route }: StaticScreenProps<NewTaskDrafcatalogState.hasConnectingEnvironment &&catalogState.connectionError === null));- useEffect(() => {- if (!needsPreparation || !initialProjectRef.branch || waitingForProject) return;- const branchName = initialProjectRef.branch;- let active = true;- // oxlint-disable-next-line react/set-state-in-effect -- Counts the serialized Git checkout this effect starts.- setPendingCheckouts((count) => count + 1);- // Serialize replacements: ignoring a stale result cannot undo its Git mutation.- checkoutTail.current = checkoutTail.current.then(async () => {- if (!active) {- setPendingCheckouts((count) => count - 1);- return;- }- const result = await checkoutNewTaskBranch({- branch: {- name: branchName,- current: false,- isDefault: false,+ // The checkout is keyed by its request, so a reconnect that drops and+ // restores the project reads the same checkout instead of running another.+ const flowKey = newTaskFlowKey(currentRoute);+ const checkoutKey =+ needsPreparation && initialProjectRef.branch && !waitingForProject && flowKey !== undefined+ ? branchCheckoutRequestKey({+ flowKey,+ routeKey: currentRoute.key,+ environmentId: checkoutProject?.environmentId ?? null,+ workspaceRoot: checkoutProject?.workspaceRoot ?? null,+ branch: initialProjectRef.branch,worktreePath: initialProjectRef.worktreePath ?? null,- },- project: environmentId && workspaceRoot ? { environmentId, workspaceRoot } : null,- workspaceMode: "local",- readRefs,- switchRef,- });- setPendingCheckouts((count) => count - 1);- if (active) setPreparation({ request: initialProjectRef, result, workspaceRoot });- });- const committed = Promise.withResolvers<void>();- committedCheckoutReleases.current.add(committed.resolve);- deferThreadSelectionUntil(Promise.allSettled([checkoutTail.current, committed.promise]));- return () => {- active = false;- };- }, [- deferThreadSelectionUntil,- environmentId,- workspaceRoot,- initialProjectRef,- needsPreparation,- readRefs,- switchRef,- waitingForProject,- ]);-- const result =- preparation?.request === initialProjectRef && preparation.workspaceRoot === workspaceRoot- ? preparation.result+ }): null;- // Guard native swipes too; replaced checkout requests must settle before leaving the shared checkout.- const checkoutPending = pendingCheckouts > 0 || (needsPreparation && result === null);+ const checkout = useAtomValue(+ checkoutKey === null ? idleBranchCheckoutAtom : branchCheckouts.atom(checkoutKey),+ );+ const result = AsyncResult.isSuccess(checkout) ? checkout.value : null;+ // The native-stack guard covers iOS swipe dismissal as well as back actions.+ const checkoutPending = needsPreparation && result === null;usePreventRemove(checkoutPending, () => undefined);const { preventedRoutes } = usePreventRemoveContext();const removalBlocked = preventedRoutes[currentRoute.key]?.preventRemove === true;+ // Native-stack reads the provider's prevent state, which commits a render+ // after usePreventRemove updates its registry; the deferred thread selection+ // (and the failure goBack) must wait for that commit.useEffect(() => {- if (checkoutPending || removalBlocked) return;- // Native-stack reads the provider state, which commits after the hook updates its registry.- for (const release of committedCheckoutReleases.current) release();- committedCheckoutReleases.current.clear();- }, [checkoutPending, removalBlocked]);- useEffect(() => {- const releases = committedCheckoutReleases.current;- return () => {- for (const release of releases) release();- releases.clear();- };- }, []);- useEffect(() => {- if (checkoutPending || result?._tag !== "Failure") return;- if (!isAtomCommandInterrupted(result)) {- const error = squashAtomCommandFailure(result);- Dialog.alert(- "Could not switch branch",- error instanceof Error ? error.message : "The branch could not be checked out.",- );- }- navigation.goBack();- }, [checkoutPending, result, navigation]);+ if (checkoutKey === null || checkoutPending || removalBlocked) return;+ branchCheckouts.release(checkoutKey);+ }, [checkoutKey, checkoutPending, removalBlocked]);- const preparedProjectRef = useMemo(- () =>- result?._tag === "Success" && workspaceRoot- ? {- ...initialProjectRef,- branch: result.value.name,- worktreePath: resolveNewTaskBranchWorktreePath({- workspaceMode: "local",- projectCwd: workspaceRoot,- branchWorktreePath: result.value.worktreePath,- }),- }- : initialProjectRef,- [initialProjectRef, result, workspaceRoot],- );+ const prepared =+ result?._tag === "Success" && workspaceRoot+ ? {+ branch: result.value.name,+ worktreePath: resolveNewTaskBranchWorktreePath({+ workspaceMode: "local",+ projectCwd: workspaceRoot,+ branchWorktreePath: result.value.worktreePath,+ }),+ }+ : null;+ const preparedBranch = prepared ? prepared.branch : initialProjectRef.branch;+ const preparedWorktreePath = prepared ? prepared.worktreePath : initialProjectRef.worktreePath;+ // NewTaskDraftScreen re-applies the route project (and rewrites the draft's+ // workspace) whenever this object's identity changes. initialProjectRef is new+ // every render, so read its fields first: the compiler then memoizes this+ // object on them, instead of on initialProjectRef.+ const { environmentId, projectId, cloning } = initialProjectRef;+ const preparedProjectRef = {+ environmentId,+ projectId,+ branch: preparedBranch,+ worktreePath: preparedWorktreePath,+ cloning,+ };const preparingBranch = checkoutPending || (needsPreparation && result?._tag !== "Success");if (!initialized) return null;diff --git a/apps/mobile/src/features/threads/new-task-branch-checkout.test.ts b/apps/mobile/src/features/threads/new-task-branch-checkout.test.tsnew file mode 100644index 00000000000..f6826ed6ac5--- /dev/null+++ b/apps/mobile/src/features/threads/new-task-branch-checkout.test.ts@@ -0,0 +1,132 @@+import { AsyncResult, AtomRegistry } from "effect/reactivity";+import * as Cause from "effect/Cause";+import { describe, expect, it, vi } from "vite-plus/test";++import { appAtomRegistry } from "../../state/atom-registry";+import {+ type BranchCheckoutRequest,+ type BranchCheckoutResult,+ branchCheckoutRequestKey,+ makeNewTaskBranchCheckouts,+} from "./new-task-branch-checkout";++function request(flowKey: string, branch: string): BranchCheckoutRequest {+ return {+ flowKey,+ routeKey: flowKey,+ environmentId: null,+ workspaceRoot: "/repo",+ branch,+ worktreePath: null,+ };+}++function setup() {+ const runs: Array<{+ readonly request: BranchCheckoutRequest;+ readonly settle: (result: BranchCheckoutResult) => void;+ }> = [];+ const holds: Array<Promise<unknown>> = [];+ const onFailure = vi.fn();+ const checkouts = makeNewTaskBranchCheckouts({+ run: (input) =>+ new Promise((resolve) => {+ runs.push({ request: input, settle: resolve });+ }),+ holdNavigation: (operation) => holds.push(operation),+ onFailure,+ });+ return { checkouts, runs, holds, onFailure };+}++const success = (name: string): BranchCheckoutResult =>+ AsyncResult.success({ name, current: true, isDefault: false, worktreePath: null });+const failure: BranchCheckoutResult = AsyncResult.failure(Cause.fail(new Error("dirty tree")));++describe("new task branch checkouts", () => {+ it("runs once per request even when its atom node is removed and rebuilt", async () => {+ const { checkouts, runs } = setup();+ const key = branchCheckoutRequestKey(request("flow-a", "feature"));++ // A render read with no subscriber, then the node is dropped before the+ // subscription commits, then the subscription builds a fresh node.+ const tasks: Array<() => void> = [];+ const registry = AtomRegistry.make({+ scheduleTask: (task) => {+ tasks.push(task);+ return () => undefined;+ },+ });+ const flushRemovals = () => tasks.splice(0).forEach((task) => task());++ registry.get(checkouts.atom(key));+ await vi.waitFor(() => expect(runs).toHaveLength(1));+ flushRemovals();+ expect(registry.getNodes().size).toBe(0);+ const unmount = registry.mount(checkouts.atom(key));+ runs[0]!.settle(success("feature"));+ await vi.waitFor(() =>+ expect(AsyncResult.isSuccess(registry.get(checkouts.atom(key)))).toBe(true),+ );+ unmount();++ expect(runs).toHaveLength(1);+ });++ it("serializes checkouts across routes", async () => {+ const { checkouts, runs } = setup();+ const unmountA = appAtomRegistry.mount(+ checkouts.atom(branchCheckoutRequestKey(request("flow-a", "a"))),+ );+ const unmountB = appAtomRegistry.mount(+ checkouts.atom(branchCheckoutRequestKey(request("flow-b", "b"))),+ );+ await vi.waitFor(() => expect(runs).toHaveLength(1));+ expect(runs[0]!.request.branch).toBe("a");++ runs[0]!.settle(success("a"));+ await vi.waitFor(() => expect(runs).toHaveLength(2));+ expect(runs[1]!.request.branch).toBe("b");+ runs[1]!.settle(success("b"));+ unmountA();+ unmountB();+ });++ it("handles a failure only after the route is released, and never once it left", async () => {+ const { checkouts, runs, holds, onFailure } = setup();+ const keyA = branchCheckoutRequestKey(request("flow-a", "a"));+ const keyB = branchCheckoutRequestKey(request("flow-b", "b"));+ const unmountA = appAtomRegistry.mount(checkouts.atom(keyA));+ const unmountB = appAtomRegistry.mount(checkouts.atom(keyB));++ await vi.waitFor(() => expect(runs).toHaveLength(1));+ runs[0]!.settle(failure);+ await vi.waitFor(() => expect(runs).toHaveLength(2));+ expect(onFailure).not.toHaveBeenCalled();+ checkouts.release(keyA);+ await vi.waitFor(() => expect(onFailure).toHaveBeenCalledTimes(1));+ expect(onFailure.mock.calls[0]![0]).toMatchObject({ flowKey: "flow-a" });++ checkouts.prune(new Set(["flow-a"]));+ runs[1]!.settle(failure);+ checkouts.release(keyB);+ // The hold settles only after the failure continuation has run.+ await holds[1];+ expect(onFailure).toHaveBeenCalledTimes(1);+ unmountA();+ unmountB();+ });++ it("stops holding navigation when its route leaves the stack", async () => {+ const { checkouts, runs, holds } = setup();+ const unmount = appAtomRegistry.mount(+ checkouts.atom(branchCheckoutRequestKey(request("flow-a", "a"))),+ );+ await vi.waitFor(() => expect(runs).toHaveLength(1));+ runs[0]!.settle(success("a"));++ checkouts.prune(new Set());+ await expect(holds[0]).resolves.toBeDefined();+ unmount();+ });+});diff --git a/apps/mobile/src/features/threads/new-task-branch-checkout.ts b/apps/mobile/src/features/threads/new-task-branch-checkout.tsnew file mode 100644index 00000000000..3cd777af435--- /dev/null+++ b/apps/mobile/src/features/threads/new-task-branch-checkout.ts@@ -0,0 +1,126 @@+import type { AtomCommandResult } from "@t3tools/client-runtime/state/runtime";+import type { VcsRef } from "@t3tools/client-runtime/state/vcs";+import { EnvironmentId } from "@t3tools/contracts";+import * as Effect from "effect/Effect";+import * as Schema from "effect/Schema";+import { Atom } from "effect/reactivity";++export type BranchCheckoutResult = AtomCommandResult<VcsRef, unknown>;+type BranchCheckoutFailure = Extract<BranchCheckoutResult, { readonly _tag: "Failure" }>;++export interface BranchCheckoutRequest {+ /** The draft route's flow key; the checkout is abandoned once it leaves the stack. */+ readonly flowKey: string;+ readonly routeKey: string;+ readonly environmentId: EnvironmentId | null;+ readonly workspaceRoot: string | null;+ readonly branch: string;+ readonly worktreePath: string | null;+}++// The family key lists the request's fields in a fixed order, so equal+// requests share one key and start can rebuild the request from it.+const RequestKey = Schema.fromJsonString(+ Schema.Tuple([+ Schema.String,+ Schema.String,+ Schema.NullOr(EnvironmentId),+ Schema.NullOr(Schema.String),+ Schema.String,+ Schema.NullOr(Schema.String),+ ]),+);+const encodeRequestKey = Schema.encodeSync(RequestKey);+const decodeRequestKey = Schema.decodeSync(RequestKey);++/** A pure, stable key for a request: the same fields always give the same key. */+export function branchCheckoutRequestKey(request: BranchCheckoutRequest): string {+ return encodeRequestKey([+ request.flowKey,+ request.routeKey,+ request.environmentId,+ request.workspaceRoot,+ request.branch,+ request.worktreePath,+ ]);+}++function requestFromKey(key: string): BranchCheckoutRequest {+ const [flowKey, routeKey, environmentId, workspaceRoot, branch, worktreePath] =+ decodeRequestKey(key);+ return { flowKey, routeKey, environmentId, workspaceRoot, branch, worktreePath };+}++interface CheckoutEntry {+ readonly request: BranchCheckoutRequest;+ readonly checkout: Promise<BranchCheckoutResult>;+ readonly release: () => void;+ abandoned: boolean;+}++/**+ * Branch checkouts for draft routes. A checkout is a Git mutation, so it is+ * tied to the request, not to an atom node: the node can be removed and rebuilt+ * (a render read before the subscription commits) without running it again.+ */+export function makeNewTaskBranchCheckouts(deps: {+ readonly run: (request: BranchCheckoutRequest) => Promise<BranchCheckoutResult>;+ /** Holds navigation until the checkout settles and its route is released. */+ readonly holdNavigation: (operation: Promise<unknown>) => void;+ /** Runs once the route is released, unless the route was abandoned first. */+ readonly onFailure: (request: BranchCheckoutRequest, result: BranchCheckoutFailure) => void;+}) {+ // Ignoring a stale result cannot undo its Git mutation, so checkouts run one+ // at a time across routes.+ let tail: Promise<unknown> = Promise.resolve();+ // Registered when a checkout starts, never from render.+ const entries = new Map<string, CheckoutEntry>();++ function abandon(key: string, entry: CheckoutEntry): void {+ entry.abandoned = true;+ entry.release();+ entries.delete(key);+ }++ function start(key: string): Promise<BranchCheckoutResult> {+ const existing = entries.get(key);+ if (existing) return existing.checkout;+ const request = requestFromKey(key);+ // A route asks for one checkout at a time; a superseded request no longer+ // owns the route's failure handling or holds navigation.+ for (const [otherKey, other] of entries) {+ if (other.request.flowKey === request.flowKey) abandon(otherKey, other);+ }+ const released = Promise.withResolvers<void>();+ const checkout = tail.then(() => deps.run(request));+ tail = checkout.catch(() => undefined);+ const entry: CheckoutEntry = { request, checkout, release: released.resolve, abandoned: false };+ entries.set(key, entry);+ const handled = checkout.then(async (result) => {+ if (result._tag === "Success") return;+ await released.promise;+ if (!entry.abandoned) deps.onFailure(request, result);+ });+ // Navigation waits for the failure handling too, so its goBack lands first.+ deps.holdNavigation(Promise.allSettled([handled, released.promise]));+ return checkout;+ }++ return {+ atom: Atom.family((key: string) =>+ Atom.make(Effect.promise(() => start(key))).pipe(+ Atom.withLabel("mobile:new-task-branch-checkout"),+ ),+ ),+ /** The route rendered with removal unblocked, so navigation may proceed. */+ release(key: string): void {+ entries.get(key)?.release();+ },+ /** Abandons the checkouts of draft routes that are no longer on the stack. */+ prune(liveFlowKeys: ReadonlySet<string>): void {+ for (const [key, entry] of entries) {+ if (!liveFlowKeys.has(entry.request.flowKey)) abandon(key, entry);+ }+ },+ };+}diff --git a/apps/mobile/src/features/threads/new-task-flow-state.ts b/apps/mobile/src/features/threads/new-task-flow-state.tsnew file mode 100644index 00000000000..37a04a0b4de--- /dev/null+++ b/apps/mobile/src/features/threads/new-task-flow-state.ts@@ -0,0 +1,32 @@+import {+ draftRouteIdentity,+ isDraftThreadRoute,+ type NewTaskDraftRouteParams,+} from "./thread-route-state";++/** The flow key for a draft Thread route: its key plus the draft it opened. */+export function newTaskFlowKey(route: {+ readonly key: string;+ readonly params?: object;+}): string | undefined {+ const draft = (route.params as { draft?: NewTaskDraftRouteParams } | undefined)?.draft;+ return draft ? `${route.key}:${draftRouteIdentity(draft)}` : undefined;+}++interface NavigationRoutes {+ readonly routes: ReadonlyArray<{+ readonly key: string;+ readonly name: string;+ readonly params?: object;+ }>;+}++/** Flow keys of the draft routes on the stack. */+export function liveNewTaskFlowKeys(state: NavigationRoutes): ReadonlySet<string> {+ return new Set(+ state.routes.flatMap((route) => {+ const flowKey = isDraftThreadRoute(route) ? newTaskFlowKey(route) : undefined;+ return flowKey === undefined ? [] : [flowKey];+ }),+ );+}diff --git a/apps/mobile/src/lib/rootNavigation.test.ts b/apps/mobile/src/lib/rootNavigation.test.tsnew file mode 100644index 00000000000..af1fff8c1c7--- /dev/null+++ b/apps/mobile/src/lib/rootNavigation.test.ts@@ -0,0 +1,31 @@+import { expect, it, vi } from "vite-plus/test";+import type { NavigationContainerRef } from "@react-navigation/native";++vi.mock("@react-navigation/native", () => ({+ createNavigationContainerRef: () => ({+ current: null as { isReady(): boolean } | null,+ isReady() {+ return this.current?.isReady() ?? false;+ },+ }),+}));++const { attachRootNavigation, rootNavigationRef } = await import("./rootNavigation");++function fakeContainer() {+ return { isReady: () => true } as NavigationContainerRef<ReactNavigation.RootParamList>;+}++it("keeps the newer container when an older root unmounts after it attached", () => {+ // Android activity replacement mounts the new root before the old one unmounts.+ const detachPrevious = attachRootNavigation(fakeContainer());+ const current = fakeContainer();+ const detachCurrent = attachRootNavigation(current);++ detachPrevious();+ expect(rootNavigationRef.current).toBe(current);+ expect(rootNavigationRef.isReady()).toBe(true);++ detachCurrent();+ expect(rootNavigationRef.current).toBeNull();+});diff --git a/apps/mobile/src/lib/rootNavigation.ts b/apps/mobile/src/lib/rootNavigation.tsnew file mode 100644index 00000000000..3f064f9301f--- /dev/null+++ b/apps/mobile/src/lib/rootNavigation.ts@@ -0,0 +1,24 @@+import {+ createNavigationContainerRef,+ type NavigationContainerRef,+} from "@react-navigation/native";++/**+ * The app's single navigation container. Work that outlives a screen (a draft+ * route's branch checkout) navigates through it.+ */+export const rootNavigationRef = createNavigationContainerRef<ReactNavigation.RootParamList>();++/**+ * Ref callback for the container. Android activity replacement mounts the new+ * root before the old one unmounts, so the old container must not clear the+ * ref the new one already owns.+ */+export function attachRootNavigation(+ navigation: NavigationContainerRef<ReactNavigation.RootParamList> | null,+): () => void {+ rootNavigationRef.current = navigation;+ return () => {+ if (rootNavigationRef.current === navigation) rootNavigationRef.current = null;+ };+}diff --git a/apps/mobile/vite.config.ts b/apps/mobile/vite.config.tsindex c341dec4e2b..8eaaaa1604f 100644--- a/apps/mobile/vite.config.ts+++ b/apps/mobile/vite.config.ts@@ -17,6 +17,7 @@ const reactTests = ["src/features/settings/components/BranchNamingSettings.test.tsx","src/features/threads/ThreadMarkdownImage.test.tsx","src/features/threads/UsageLimitRecoveryCard.test.tsx",+ "src/features/threads/NewTaskDraftRouteScreen.test.tsx","src/native/NativeHeaderToolbar.test.tsx","src/native/useRestingTopOffset.test.tsx","src/native/useRetryingImageSource.test.tsx",