@devries-cameron20 / t3code Mirror · read-only / commits / d145077b4f
Fork 0

The best way to control Claude Code, Codex and more from any computer or phone

Mirrored from https://github.com/Camo67/t3code.git

Synced Nov 22, 15:45 UTC

fix(mobile): a draft route's branch checkout runs once, even across a reconnect (#25712)

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>

Julius Marminge committed Oct 26, 2026 at 20:04 UTC d145077b4f7dc9e476bacf346e3f2c04cc141d6d
12 files changed +699 -128
apps/mobile/src/App.tsx
+15 -5
@@ -9,10 +9,10 @@ import { GestureHandlerRootView } from "react-native-gesture-handler";
9 import { KeyboardProvider } from "react-native-keyboard-controller";
10 import { SafeAreaProvider } from "react-native-safe-area-context";
11 import {
12 - createNavigationContainerRef,
12 createStaticNavigation,
13 getActionFromState,
14 getStateFromPath,
15 + type NavigationState,
16 } from "@react-navigation/native";
17
18 import { RegistryContext } from "@effect/atom-react";
@@ -52,6 +52,8 @@ import {
52 } from "./features/workspace/workspace-selection-store";
53 import { workspaceDetailLinkAction } from "./features/workspace/workspace-detail-selection";
54 import { NativeLayoutMetricsProvider } from "./native/native-layout-metrics";
55 +import { attachRootNavigation, rootNavigationRef } from "./lib/rootNavigation";
56 +import { pruneNewTaskBranchCheckouts } from "./features/threads/NewTaskDraftRouteScreen";
57
58 import "../global.css";
59
@@ -84,7 +86,15 @@ const appLinking = {
86 };
87
88 const Navigation = createStaticNavigation(RootStack);
87 -const navigationRef = createNavigationContainerRef();
89 +
90 +function handleNavigationStateChange(state: NavigationState | undefined): void {
91 + recordWorkspaceSelections(state);
92 + if (state) pruneNewTaskBranchCheckouts(state);
93 +}
94 +
95 +function handleNavigationReady(): void {
96 + handleNavigationStateChange(rootNavigationRef.getRootState());
97 +}
98
99 declare const module: { readonly hot?: FoundationHotModule } | undefined;
100
@@ -148,11 +158,11 @@ function AppContent() {
158 <NativeLayoutMetricsProvider>
159 <IncomingShareProvider>
160 <Navigation
151 - ref={navigationRef}
161 + ref={attachRootNavigation}
162 linking={appLinking}
153 - onReady={() => recordWorkspaceSelections(navigationRef.getRootState())}
163 + onReady={handleNavigationReady}
164 theme={navigationTheme}
155 - onStateChange={recordWorkspaceSelections}
165 + onStateChange={handleNavigationStateChange}
166 />
167 </IncomingShareProvider>
168 <Dialog.Host />
apps/mobile/src/features/layout/AdaptiveWorkspaceLayout.tsx
+2 -4
@@ -1,6 +1,6 @@
1 import { SafeAreaInsetsContext, useSafeAreaInsets } from "react-native-safe-area-context";
2 import { AdaptiveWorkspaceContext, useAdaptiveWorkspaceLayout } from "./adaptive-workspace-context";
3 -import { createDeferredNavigation } from "./deferred-navigation";
3 +import { threadSelectionDeferral } from "./deferred-navigation";
4 import { uuidv4 } from "../../lib/uuid";
5 import type {
6 EnvironmentProject,
@@ -491,10 +491,9 @@ function AdaptiveWorkspaceLayoutContent(
491 };
492 const handleOpenSettings = () => openWorkspaceTab("settings");
493
494 - const deferredThreadSelection = useMemo(() => createDeferredNavigation(), []);
494 /** The one way to show a page in the detail column; see `selectWorkspaceDetail`. */
495 function handleSelectDetail(detail: WorkspaceDetail, sheet?: WorkspaceDetailSheet) {
497 - deferredThreadSelection.run(() => {
496 + threadSelectionDeferral.run(() => {
497 if (Platform.OS === "android") Keyboard.dismiss();
498 setFileInspectorPreferredVisible(false);
499 if (layout.primarySidebarOverlaysContent) setPrimarySidebarVisible(false);
@@ -770,7 +769,6 @@ function AdaptiveWorkspaceLayoutContent(
769 fileInspector,
770 primarySidebarSearchQuery,
771 startNewTask: handleStartNewTask,
773 - deferThreadSelectionUntil: deferredThreadSelection.waitFor,
772 selectDetail: handleSelectDetail,
773 activateAuxiliaryPaneRole,
774 registerWorkspaceInspector,
apps/mobile/src/features/layout/adaptive-workspace-context.ts
-2
@@ -20,7 +20,6 @@ interface AdaptiveWorkspaceContextValue {
20 readonly fileInspector: FileInspectorPaneLayout;
21 readonly primarySidebarSearchQuery: string;
22 readonly startNewTask: () => void;
23 - readonly deferThreadSelectionUntil: (operation: Promise<unknown>) => void;
23 /** Use `useSelectWorkspaceDetail`, which also works outside the layout. */
24 readonly selectDetail?: (detail: WorkspaceDetail, sheet?: WorkspaceDetailSheet) => void;
25 readonly activateAuxiliaryPaneRole: (role: WorkspaceAuxiliaryPaneRole) => () => void;
@@ -67,7 +66,6 @@ export const AdaptiveWorkspaceContext = createContext<AdaptiveWorkspaceContextVa
66 fileInspector: compactFileInspector,
67 primarySidebarSearchQuery: "",
68 startNewTask: () => undefined,
70 - deferThreadSelectionUntil: () => undefined,
69 activateAuxiliaryPaneRole: () => () => undefined,
70 registerWorkspaceInspector: () => () => undefined,
71 setPrimarySidebarSearchQuery: () => undefined,
apps/mobile/src/features/layout/deferred-navigation.ts
+6
@@ -20,3 +20,9 @@ export function createDeferredNavigation() {
20 },
21 };
22 }
23 +
24 +/**
25 + * The app's one thread-selection gate: a new-task branch checkout holds
26 + * split-view thread selection until the draft route can be left.
27 + */
28 +export const threadSelectionDeferral = createDeferredNavigation();
apps/mobile/src/features/threads/NewTaskDraftRouteScreen.test.tsx new
+191
@@ -0,0 +1,191 @@
1 +import type { ReactNode } from "react";
2 +import { act, useSyncExternalStore } from "react";
3 +import { createRoot } from "react-dom/client";
4 +import { AsyncResult } from "effect/reactivity";
5 +import { expect, it, vi } from "vite-plus/test";
6 +
7 +interface Snapshot {
8 + readonly projects: ReadonlyArray<{
9 + readonly environmentId: string;
10 + readonly id: string;
11 + readonly workspaceRoot: string;
12 + }>;
13 + readonly catalog: {
14 + readonly isLoadingConnections: boolean;
15 + readonly hasLoadedShellSnapshot: boolean;
16 + readonly hasConnectingEnvironment: boolean;
17 + readonly connectionError: string | null;
18 + };
19 +}
20 +
21 +const harness = vi.hoisted(() => {
22 + const listeners = new Set<() => void>();
23 + const state: { snapshot: Snapshot | null } = { snapshot: null };
24 + return {
25 + state,
26 + set(next: Snapshot) {
27 + state.snapshot = next;
28 + for (const listener of listeners) listener();
29 + },
30 + subscribe(listener: () => void) {
31 + listeners.add(listener);
32 + return () => listeners.delete(listener);
33 + },
34 + route: { key: "thread-route", name: "Thread", params: {} as object },
35 + reset: () => undefined,
36 + checkout: vi.fn(),
37 + draftProjectRefs: [] as unknown[],
38 + // Hook results stay stable across renders, as the real hooks' are. Only
39 + // main's screen reads these (see the main-comparison mocks below).
40 + layout: { deferThreadSelectionUntil: () => undefined },
41 + navigation: { goBack: () => undefined },
42 + preventContext: { preventedRoutes: {} },
43 + };
44 +});
45 +
46 +function useSnapshot(): Snapshot {
47 + return useSyncExternalStore(harness.subscribe, () => harness.state.snapshot!);
48 +}
49 +
50 +vi.mock("react-native", () => ({
51 + View: ({ children }: { children: ReactNode }) => <div>{children}</div>,
52 +}));
53 +vi.mock("../../components/ui/AppText", () => ({
54 + AppText: ({ children }: { children: ReactNode }) => <span>{children}</span>,
55 +}));
56 +vi.mock("../../components/ui/Dialog", () => ({ alert: vi.fn() }));
57 +vi.mock("../../native/StackHeader", () => ({ NativeStackScreenOptions: () => null }));
58 +vi.mock("./ThreadScreenHost", () => ({
59 + ThreadScreenFallback: ({ children }: { children: ReactNode }) => <>{children}</>,
60 +}));
61 +vi.mock("./NewTaskDraftScreen", () => ({
62 + NewTaskDraftScreen: (props: { initialProjectRef: { branch?: string | null } }) => {
63 + harness.draftProjectRefs.push(props.initialProjectRef);
64 + return <p>draft on {props.initialProjectRef.branch}</p>;
65 + },
66 +}));
67 +vi.mock("./new-task-context-presentation", () => ({
68 + resolveNewTaskBranchWorktreePath: () => null,
69 +}));
70 +vi.mock("./new-task-flow-provider", () => ({
71 + useNewTaskFlow: () => harness,
72 +}));
73 +vi.mock("./checkout-new-task-branch", () => ({ checkoutNewTaskBranch: harness.checkout }));
74 +// Main-comparison mocks: this screen no longer uses them, but main's screen
75 +// did (deferThreadSelectionUntil, useAtomCommand, useNavigation). They stay so
76 +// this test can run against main's screen and fail there for the right reason
77 +// (a second checkout) instead of on an unmockable import.
78 +vi.mock("../layout/AdaptiveWorkspaceLayout", () => ({
79 + useAdaptiveWorkspaceLayout: () => harness.layout,
80 +}));
81 +vi.mock("../../state/use-atom-command", () => ({ useAtomCommand: () => harness.checkout }));
82 +vi.mock("../../state/entities", () => ({ useProjects: () => useSnapshot().projects }));
83 +vi.mock("../../state/workspace", () => ({
84 + useWorkspaceState: () => ({ state: useSnapshot().catalog }),
85 +}));
86 +vi.mock("../../state/vcs", () => ({ vcsEnvironment: { readRefs: {}, switchRef: {} } }));
87 +vi.mock("@react-navigation/native", () => ({
88 + CommonActions: { goBack: () => ({ type: "GO_BACK" }) },
89 + createNavigationContainerRef: () => ({ current: null }),
90 + // Main-comparison only, like the mocks above.
91 + useNavigation: () => harness.navigation,
92 + useRoute: () => harness.route,
93 + usePreventRemove: () => undefined,
94 + usePreventRemoveContext: () => harness.preventContext,
95 +}));
96 +
97 +import { NewTaskDraftRouteScreen } from "./NewTaskDraftRouteScreen";
98 +
99 +const project = { environmentId: "env-1", id: "project-1", workspaceRoot: "/repo" };
100 +const connected: Snapshot["catalog"] = {
101 + isLoadingConnections: false,
102 + hasLoadedShellSnapshot: true,
103 + hasConnectingEnvironment: false,
104 + connectionError: null,
105 +};
106 +
107 +// The project can vanish while the catalog still loads, or while it reports ready.
108 +it.each([
109 + ["while the catalog reloads", { ...connected, isLoadingConnections: true }],
110 + ["while the catalog stays ready", connected],
111 +])(
112 + "checks the branch out once when a reconnect drops and restores the project %s",
113 + async (gap, gapCatalog) => {
114 + // Checkouts live in a module table keyed by route, so each case uses its own route.
115 + const routeKey = `thread-route ${gap}`;
116 + (globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true;
117 + const firstCheckout = Promise.withResolvers<unknown>();
118 + harness.checkout.mockReturnValueOnce(firstCheckout.promise);
119 + harness.checkout.mockResolvedValue(
120 + AsyncResult.success({ name: "feature", current: true, isDefault: false, worktreePath: null }),
121 + );
122 + harness.set({ projects: [project], catalog: connected });
123 + const draft = { environmentId: "env-1", projectId: "project-1", branch: "feature" };
124 + harness.route = { key: routeKey, name: "Thread", params: { draft } };
125 +
126 + const container = document.createElement("div");
127 + const root = createRoot(container);
128 + using _root = { [Symbol.dispose]: () => act(() => root.unmount()) };
129 + act(() =>
130 + root.render(
131 + <NewTaskDraftRouteScreen
132 + route={{ key: routeKey, name: "Thread", params: draft } as never}
133 + />,
134 + ),
135 + );
136 + await vi.waitFor(() => expect(harness.checkout).toHaveBeenCalledTimes(1));
137 +
138 + // The connection drops while the checkout runs, then the project comes back.
139 + act(() => harness.set({ projects: [], catalog: gapCatalog }));
140 + act(() => harness.set({ projects: [project], catalog: connected }));
141 + await act(async () => {
142 + firstCheckout.resolve(
143 + AsyncResult.success({
144 + name: "feature",
145 + current: true,
146 + isDefault: false,
147 + worktreePath: null,
148 + }),
149 + );
150 + });
151 +
152 + await vi.waitFor(() =>
153 + expect(
154 + harness.checkout.mock.calls.length > 1 || container.textContent === "draft on feature",
155 + ).toBe(true),
156 + );
157 + expect(harness.checkout).toHaveBeenCalledTimes(1);
158 + expect(container.textContent).toBe("draft on feature");
159 + },
160 +);
161 +
162 +it("hands the draft screen the same project ref across re-renders", async () => {
163 + (globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true;
164 + harness.checkout.mockReset();
165 + harness.draftProjectRefs.length = 0;
166 + harness.checkout.mockResolvedValue(
167 + AsyncResult.success({ name: "other", current: true, isDefault: false, worktreePath: null }),
168 + );
169 + harness.set({ projects: [project], catalog: connected });
170 + const draft = { environmentId: "env-1", projectId: "project-1", branch: "other" };
171 + harness.route = { key: "stable-route", name: "Thread", params: { draft } };
172 +
173 + const container = document.createElement("div");
174 + const root = createRoot(container);
175 + using _root = { [Symbol.dispose]: () => act(() => root.unmount()) };
176 + act(() =>
177 + root.render(
178 + <NewTaskDraftRouteScreen
179 + route={{ key: "stable-route", name: "Thread", params: draft } as never}
180 + />,
181 + ),
182 + );
183 + await vi.waitFor(() => expect(container.textContent).toBe("draft on other"));
184 +
185 + // The draft screen re-applies its route project when this identity changes,
186 + // and that write re-renders the route; an unstable ref loops forever.
187 + act(() => harness.set({ projects: [{ ...project }], catalog: { ...connected } }));
188 + // A stable ref lets the compiled screen skip re-rendering the draft screen at all; an unstable
189 + // one re-renders it with a second ref.
190 + expect(new Set(harness.draftProjectRefs).size).toBe(1);
191 +});
apps/mobile/src/features/threads/NewTaskDraftRouteScreen.tsx
+139 -117
@@ -1,26 +1,36 @@
1 -import { useAdaptiveWorkspaceLayout } from "../layout/AdaptiveWorkspaceLayout";
1 import { useNewTaskFlow } from "./new-task-flow-provider";
2 import * as Dialog from "../../components/ui/Dialog";
3 import {
5 - useNavigation,
4 + CommonActions,
5 useRoute,
6 usePreventRemove,
7 usePreventRemoveContext,
8 type StaticScreenProps,
9 } from "@react-navigation/native";
11 -import { useEffect, useLayoutEffect, useMemo, useRef, useState } from "react";
10 +import { useEffect, useLayoutEffect, useState } from "react";
11 import { View } from "react-native";
12 +import { useAtomValue } from "@effect/atom-react";
13 import {
14 isAtomCommandInterrupted,
15 + runAtomCommand,
16 squashAtomCommandFailure,
17 } from "@t3tools/client-runtime/state/runtime";
18 +import { AsyncResult, Atom } from "effect/reactivity";
19 import { AppText as Text } from "../../components/ui/AppText";
20 import { useProjects } from "../../state/entities";
19 -import { useAtomCommand } from "../../state/use-atom-command";
21 +import { appAtomRegistry } from "../../state/atom-registry";
22 +import { rootNavigationRef } from "../../lib/rootNavigation";
23 +import { threadSelectionDeferral } from "../layout/deferred-navigation";
24 import { useWorkspaceState } from "../../state/workspace";
25 import { vcsEnvironment } from "../../state/vcs";
26 import { checkoutNewTaskBranch } from "./checkout-new-task-branch";
27 import { resolveNewTaskBranchWorktreePath } from "./new-task-context-presentation";
28 +import {
29 + type BranchCheckoutResult,
30 + branchCheckoutRequestKey,
31 + makeNewTaskBranchCheckouts,
32 +} from "./new-task-branch-checkout";
33 +import { liveNewTaskFlowKeys, newTaskFlowKey } from "./new-task-flow-state";
34 import { NativeStackScreenOptions } from "../../native/StackHeader";
35
36 import { ThreadScreenFallback } from "./ThreadScreenHost";
@@ -29,11 +39,59 @@ import { NewTaskDraftScreen } from "./NewTaskDraftScreen";
39 import type { NewTaskDraftRouteParams } from "./thread-route-state";
40 export type { NewTaskDraftRouteParams } from "./thread-route-state";
41
42 +const branchCheckouts = makeNewTaskBranchCheckouts({
43 + run: (request) =>
44 + checkoutNewTaskBranch({
45 + branch: {
46 + name: request.branch,
47 + current: false,
48 + isDefault: false,
49 + worktreePath: request.worktreePath,
50 + },
51 + project:
52 + request.environmentId !== null && request.workspaceRoot !== null
53 + ? { environmentId: request.environmentId, workspaceRoot: request.workspaceRoot }
54 + : null,
55 + workspaceMode: "local",
56 + readRefs: (input) =>
57 + runAtomCommand(appAtomRegistry, vcsEnvironment.readRefs, input, {
58 + reportFailure: false,
59 + }),
60 + switchRef: (input) =>
61 + runAtomCommand(appAtomRegistry, vcsEnvironment.switchRef, input, {
62 + reportFailure: false,
63 + }),
64 + }),
65 + holdNavigation: threadSelectionDeferral.waitFor,
66 + onFailure: (request, result) => {
67 + if (!isAtomCommandInterrupted(result)) {
68 + const error = squashAtomCommandFailure(result);
69 + Dialog.alert(
70 + "Could not switch branch",
71 + error instanceof Error ? error.message : "The branch could not be checked out.",
72 + );
73 + }
74 + rootNavigationRef.dispatch({
75 + ...CommonActions.goBack(),
76 + source: request.routeKey,
77 + target: rootNavigationRef.getRootState()?.key,
78 + });
79 + },
80 +});
81 +
82 +/** Abandons the branch checkouts of draft routes that left the stack. */
83 +export function pruneNewTaskBranchCheckouts(state: Parameters<typeof liveNewTaskFlowKeys>[0]) {
84 + branchCheckouts.prune(liveNewTaskFlowKeys(state));
85 +}
86 +
87 +const idleBranchCheckoutAtom = Atom.make(AsyncResult.initial<BranchCheckoutResult, never>()).pipe(
88 + Atom.withLabel("mobile:new-task-branch-checkout:idle"),
89 +);
90 +
91 export function NewTaskDraftRouteScreen({ route }: StaticScreenProps<NewTaskDraftRouteParams>) {
92 const currentRoute = useRoute();
34 - const params = useMemo(() => route.params ?? {}, [route.params]);
93 + const params = route.params ?? {};
94 const { reset } = useNewTaskFlow();
36 - const { deferThreadSelectionUntil } = useAdaptiveWorkspaceLayout();
95 const [initialized, setInitialized] = useState(false);
96 useLayoutEffect(() => {
97 reset();
@@ -43,40 +101,41 @@ export function NewTaskDraftRouteScreen({ route }: StaticScreenProps<NewTaskDraf
101 const draftId = Array.isArray(params.draftId) ? params.draftId[0] : params.draftId;
102 const projects = useProjects();
103 const { state: catalogState } = useWorkspaceState();
46 - const navigation = useNavigation();
47 - const readRefs = useAtomCommand(vcsEnvironment.readRefs, { reportFailure: false });
48 - const switchRef = useAtomCommand(vcsEnvironment.switchRef, { reportFailure: false });
104
50 - const initialProjectRef = useMemo(
51 - () => ({
52 - environmentId: Array.isArray(params.environmentId)
53 - ? params.environmentId[0]
54 - : params.environmentId,
55 - projectId: Array.isArray(params.projectId) ? params.projectId[0] : params.projectId,
56 - branch: params.branch,
57 - worktreePath: params.worktreePath,
58 - cloning: (Array.isArray(params.cloning) ? params.cloning[0] : params.cloning) === "1",
59 - }),
60 - [params],
61 - );
105 + const initialProjectRef = {
106 + environmentId: Array.isArray(params.environmentId)
107 + ? params.environmentId[0]
108 + : params.environmentId,
109 + projectId: Array.isArray(params.projectId) ? params.projectId[0] : params.projectId,
110 + branch: params.branch,
111 + worktreePath: params.worktreePath,
112 + cloning: (Array.isArray(params.cloning) ? params.cloning[0] : params.cloning) === "1",
113 + };
114
63 - const [preparation, setPreparation] = useState<{
64 - request: typeof initialProjectRef;
65 - result: Awaited<ReturnType<typeof checkoutNewTaskBranch>>;
66 - workspaceRoot: string | undefined;
67 - } | null>(null);
115 const project = projects.find(
116 (candidate) =>
117 candidate.environmentId === initialProjectRef.environmentId &&
118 candidate.id === initialProjectRef.projectId,
119 );
73 - const environmentId = project?.environmentId;
120 + // A project can drop out of the list and come back while its catalog stays ready. The checkout
121 + // keeps the last project this route resolved, so that gap reads the same checkout.
122 + const [resolvedProject, setResolvedProject] = useState<Pick<
123 + NonNullable<typeof project>,
124 + "environmentId" | "workspaceRoot"
125 + > | null>(null);
126 + if (
127 + project &&
128 + (resolvedProject?.environmentId !== project.environmentId ||
129 + resolvedProject.workspaceRoot !== project.workspaceRoot)
130 + ) {
131 + setResolvedProject({
132 + environmentId: project.environmentId,
133 + workspaceRoot: project.workspaceRoot,
134 + });
135 + }
136 + const checkoutProject = project ?? resolvedProject;
137 const workspaceRoot = project?.workspaceRoot;
138 const needsPreparation = Boolean(initialProjectRef.branch && !draftId);
76 -
77 - const [pendingCheckouts, setPendingCheckouts] = useState(0);
78 - const checkoutTail = useRef(Promise.resolve());
79 - const committedCheckoutReleases = useRef(new Set<() => void>());
139 const waitingForProject =
140 !project &&
141 (catalogState.isLoadingConnections ||
@@ -84,99 +143,62 @@ export function NewTaskDraftRouteScreen({ route }: StaticScreenProps<NewTaskDraf
143 catalogState.hasConnectingEnvironment &&
144 catalogState.connectionError === null));
145
87 - useEffect(() => {
88 - if (!needsPreparation || !initialProjectRef.branch || waitingForProject) return;
89 - const branchName = initialProjectRef.branch;
90 - let active = true;
91 - // oxlint-disable-next-line react/set-state-in-effect -- Counts the serialized Git checkout this effect starts.
92 - setPendingCheckouts((count) => count + 1);
93 - // Serialize replacements: ignoring a stale result cannot undo its Git mutation.
94 - checkoutTail.current = checkoutTail.current.then(async () => {
95 - if (!active) {
96 - setPendingCheckouts((count) => count - 1);
97 - return;
98 - }
99 - const result = await checkoutNewTaskBranch({
100 - branch: {
101 - name: branchName,
102 - current: false,
103 - isDefault: false,
146 + // The checkout is keyed by its request, so a reconnect that drops and
147 + // restores the project reads the same checkout instead of running another.
148 + const flowKey = newTaskFlowKey(currentRoute);
149 + const checkoutKey =
150 + needsPreparation && initialProjectRef.branch && !waitingForProject && flowKey !== undefined
151 + ? branchCheckoutRequestKey({
152 + flowKey,
153 + routeKey: currentRoute.key,
154 + environmentId: checkoutProject?.environmentId ?? null,
155 + workspaceRoot: checkoutProject?.workspaceRoot ?? null,
156 + branch: initialProjectRef.branch,
157 worktreePath: initialProjectRef.worktreePath ?? null,
105 - },
106 - project: environmentId && workspaceRoot ? { environmentId, workspaceRoot } : null,
107 - workspaceMode: "local",
108 - readRefs,
109 - switchRef,
110 - });
111 - setPendingCheckouts((count) => count - 1);
112 - if (active) setPreparation({ request: initialProjectRef, result, workspaceRoot });
113 - });
114 - const committed = Promise.withResolvers<void>();
115 - committedCheckoutReleases.current.add(committed.resolve);
116 - deferThreadSelectionUntil(Promise.allSettled([checkoutTail.current, committed.promise]));
117 - return () => {
118 - active = false;
119 - };
120 - }, [
121 - deferThreadSelectionUntil,
122 - environmentId,
123 - workspaceRoot,
124 - initialProjectRef,
125 - needsPreparation,
126 - readRefs,
127 - switchRef,
128 - waitingForProject,
129 - ]);
130 -
131 - const result =
132 - preparation?.request === initialProjectRef && preparation.workspaceRoot === workspaceRoot
133 - ? preparation.result
158 + })
159 : null;
135 - // Guard native swipes too; replaced checkout requests must settle before leaving the shared checkout.
136 - const checkoutPending = pendingCheckouts > 0 || (needsPreparation && result === null);
160 + const checkout = useAtomValue(
161 + checkoutKey === null ? idleBranchCheckoutAtom : branchCheckouts.atom(checkoutKey),
162 + );
163 + const result = AsyncResult.isSuccess(checkout) ? checkout.value : null;
164 + // The native-stack guard covers iOS swipe dismissal as well as back actions.
165 + const checkoutPending = needsPreparation && result === null;
166 usePreventRemove(checkoutPending, () => undefined);
167 const { preventedRoutes } = usePreventRemoveContext();
168 const removalBlocked = preventedRoutes[currentRoute.key]?.preventRemove === true;
169 + // Native-stack reads the provider's prevent state, which commits a render
170 + // after usePreventRemove updates its registry; the deferred thread selection
171 + // (and the failure goBack) must wait for that commit.
172 useEffect(() => {
141 - if (checkoutPending || removalBlocked) return;
142 - // Native-stack reads the provider state, which commits after the hook updates its registry.
143 - for (const release of committedCheckoutReleases.current) release();
144 - committedCheckoutReleases.current.clear();
145 - }, [checkoutPending, removalBlocked]);
146 - useEffect(() => {
147 - const releases = committedCheckoutReleases.current;
148 - return () => {
149 - for (const release of releases) release();
150 - releases.clear();
151 - };
152 - }, []);
153 - useEffect(() => {
154 - if (checkoutPending || result?._tag !== "Failure") return;
155 - if (!isAtomCommandInterrupted(result)) {
156 - const error = squashAtomCommandFailure(result);
157 - Dialog.alert(
158 - "Could not switch branch",
159 - error instanceof Error ? error.message : "The branch could not be checked out.",
160 - );
161 - }
162 - navigation.goBack();
163 - }, [checkoutPending, result, navigation]);
173 + if (checkoutKey === null || checkoutPending || removalBlocked) return;
174 + branchCheckouts.release(checkoutKey);
175 + }, [checkoutKey, checkoutPending, removalBlocked]);
176
165 - const preparedProjectRef = useMemo(
166 - () =>
167 - result?._tag === "Success" && workspaceRoot
168 - ? {
169 - ...initialProjectRef,
170 - branch: result.value.name,
171 - worktreePath: resolveNewTaskBranchWorktreePath({
172 - workspaceMode: "local",
173 - projectCwd: workspaceRoot,
174 - branchWorktreePath: result.value.worktreePath,
175 - }),
176 - }
177 - : initialProjectRef,
178 - [initialProjectRef, result, workspaceRoot],
179 - );
177 + const prepared =
178 + result?._tag === "Success" && workspaceRoot
179 + ? {
180 + branch: result.value.name,
181 + worktreePath: resolveNewTaskBranchWorktreePath({
182 + workspaceMode: "local",
183 + projectCwd: workspaceRoot,
184 + branchWorktreePath: result.value.worktreePath,
185 + }),
186 + }
187 + : null;
188 + const preparedBranch = prepared ? prepared.branch : initialProjectRef.branch;
189 + const preparedWorktreePath = prepared ? prepared.worktreePath : initialProjectRef.worktreePath;
190 + // NewTaskDraftScreen re-applies the route project (and rewrites the draft's
191 + // workspace) whenever this object's identity changes. initialProjectRef is new
192 + // every render, so read its fields first: the compiler then memoizes this
193 + // object on them, instead of on initialProjectRef.
194 + const { environmentId, projectId, cloning } = initialProjectRef;
195 + const preparedProjectRef = {
196 + environmentId,
197 + projectId,
198 + branch: preparedBranch,
199 + worktreePath: preparedWorktreePath,
200 + cloning,
201 + };
202 const preparingBranch = checkoutPending || (needsPreparation && result?._tag !== "Success");
203
204 if (!initialized) return null;
apps/mobile/src/features/threads/new-task-branch-checkout.test.ts new
+132
@@ -0,0 +1,132 @@
1 +import { AsyncResult, AtomRegistry } from "effect/reactivity";
2 +import * as Cause from "effect/Cause";
3 +import { describe, expect, it, vi } from "vite-plus/test";
4 +
5 +import { appAtomRegistry } from "../../state/atom-registry";
6 +import {
7 + type BranchCheckoutRequest,
8 + type BranchCheckoutResult,
9 + branchCheckoutRequestKey,
10 + makeNewTaskBranchCheckouts,
11 +} from "./new-task-branch-checkout";
12 +
13 +function request(flowKey: string, branch: string): BranchCheckoutRequest {
14 + return {
15 + flowKey,
16 + routeKey: flowKey,
17 + environmentId: null,
18 + workspaceRoot: "/repo",
19 + branch,
20 + worktreePath: null,
21 + };
22 +}
23 +
24 +function setup() {
25 + const runs: Array<{
26 + readonly request: BranchCheckoutRequest;
27 + readonly settle: (result: BranchCheckoutResult) => void;
28 + }> = [];
29 + const holds: Array<Promise<unknown>> = [];
30 + const onFailure = vi.fn();
31 + const checkouts = makeNewTaskBranchCheckouts({
32 + run: (input) =>
33 + new Promise((resolve) => {
34 + runs.push({ request: input, settle: resolve });
35 + }),
36 + holdNavigation: (operation) => holds.push(operation),
37 + onFailure,
38 + });
39 + return { checkouts, runs, holds, onFailure };
40 +}
41 +
42 +const success = (name: string): BranchCheckoutResult =>
43 + AsyncResult.success({ name, current: true, isDefault: false, worktreePath: null });
44 +const failure: BranchCheckoutResult = AsyncResult.failure(Cause.fail(new Error("dirty tree")));
45 +
46 +describe("new task branch checkouts", () => {
47 + it("runs once per request even when its atom node is removed and rebuilt", async () => {
48 + const { checkouts, runs } = setup();
49 + const key = branchCheckoutRequestKey(request("flow-a", "feature"));
50 +
51 + // A render read with no subscriber, then the node is dropped before the
52 + // subscription commits, then the subscription builds a fresh node.
53 + const tasks: Array<() => void> = [];
54 + const registry = AtomRegistry.make({
55 + scheduleTask: (task) => {
56 + tasks.push(task);
57 + return () => undefined;
58 + },
59 + });
60 + const flushRemovals = () => tasks.splice(0).forEach((task) => task());
61 +
62 + registry.get(checkouts.atom(key));
63 + await vi.waitFor(() => expect(runs).toHaveLength(1));
64 + flushRemovals();
65 + expect(registry.getNodes().size).toBe(0);
66 + const unmount = registry.mount(checkouts.atom(key));
67 + runs[0]!.settle(success("feature"));
68 + await vi.waitFor(() =>
69 + expect(AsyncResult.isSuccess(registry.get(checkouts.atom(key)))).toBe(true),
70 + );
71 + unmount();
72 +
73 + expect(runs).toHaveLength(1);
74 + });
75 +
76 + it("serializes checkouts across routes", async () => {
77 + const { checkouts, runs } = setup();
78 + const unmountA = appAtomRegistry.mount(
79 + checkouts.atom(branchCheckoutRequestKey(request("flow-a", "a"))),
80 + );
81 + const unmountB = appAtomRegistry.mount(
82 + checkouts.atom(branchCheckoutRequestKey(request("flow-b", "b"))),
83 + );
84 + await vi.waitFor(() => expect(runs).toHaveLength(1));
85 + expect(runs[0]!.request.branch).toBe("a");
86 +
87 + runs[0]!.settle(success("a"));
88 + await vi.waitFor(() => expect(runs).toHaveLength(2));
89 + expect(runs[1]!.request.branch).toBe("b");
90 + runs[1]!.settle(success("b"));
91 + unmountA();
92 + unmountB();
93 + });
94 +
95 + it("handles a failure only after the route is released, and never once it left", async () => {
96 + const { checkouts, runs, holds, onFailure } = setup();
97 + const keyA = branchCheckoutRequestKey(request("flow-a", "a"));
98 + const keyB = branchCheckoutRequestKey(request("flow-b", "b"));
99 + const unmountA = appAtomRegistry.mount(checkouts.atom(keyA));
100 + const unmountB = appAtomRegistry.mount(checkouts.atom(keyB));
101 +
102 + await vi.waitFor(() => expect(runs).toHaveLength(1));
103 + runs[0]!.settle(failure);
104 + await vi.waitFor(() => expect(runs).toHaveLength(2));
105 + expect(onFailure).not.toHaveBeenCalled();
106 + checkouts.release(keyA);
107 + await vi.waitFor(() => expect(onFailure).toHaveBeenCalledTimes(1));
108 + expect(onFailure.mock.calls[0]![0]).toMatchObject({ flowKey: "flow-a" });
109 +
110 + checkouts.prune(new Set(["flow-a"]));
111 + runs[1]!.settle(failure);
112 + checkouts.release(keyB);
113 + // The hold settles only after the failure continuation has run.
114 + await holds[1];
115 + expect(onFailure).toHaveBeenCalledTimes(1);
116 + unmountA();
117 + unmountB();
118 + });
119 +
120 + it("stops holding navigation when its route leaves the stack", async () => {
121 + const { checkouts, runs, holds } = setup();
122 + const unmount = appAtomRegistry.mount(
123 + checkouts.atom(branchCheckoutRequestKey(request("flow-a", "a"))),
124 + );
125 + await vi.waitFor(() => expect(runs).toHaveLength(1));
126 + runs[0]!.settle(success("a"));
127 +
128 + checkouts.prune(new Set());
129 + await expect(holds[0]).resolves.toBeDefined();
130 + unmount();
131 + });
132 +});
apps/mobile/src/features/threads/new-task-branch-checkout.ts new
+126
@@ -0,0 +1,126 @@
1 +import type { AtomCommandResult } from "@t3tools/client-runtime/state/runtime";
2 +import type { VcsRef } from "@t3tools/client-runtime/state/vcs";
3 +import { EnvironmentId } from "@t3tools/contracts";
4 +import * as Effect from "effect/Effect";
5 +import * as Schema from "effect/Schema";
6 +import { Atom } from "effect/reactivity";
7 +
8 +export type BranchCheckoutResult = AtomCommandResult<VcsRef, unknown>;
9 +type BranchCheckoutFailure = Extract<BranchCheckoutResult, { readonly _tag: "Failure" }>;
10 +
11 +export interface BranchCheckoutRequest {
12 + /** The draft route's flow key; the checkout is abandoned once it leaves the stack. */
13 + readonly flowKey: string;
14 + readonly routeKey: string;
15 + readonly environmentId: EnvironmentId | null;
16 + readonly workspaceRoot: string | null;
17 + readonly branch: string;
18 + readonly worktreePath: string | null;
19 +}
20 +
21 +// The family key lists the request's fields in a fixed order, so equal
22 +// requests share one key and start can rebuild the request from it.
23 +const RequestKey = Schema.fromJsonString(
24 + Schema.Tuple([
25 + Schema.String,
26 + Schema.String,
27 + Schema.NullOr(EnvironmentId),
28 + Schema.NullOr(Schema.String),
29 + Schema.String,
30 + Schema.NullOr(Schema.String),
31 + ]),
32 +);
33 +const encodeRequestKey = Schema.encodeSync(RequestKey);
34 +const decodeRequestKey = Schema.decodeSync(RequestKey);
35 +
36 +/** A pure, stable key for a request: the same fields always give the same key. */
37 +export function branchCheckoutRequestKey(request: BranchCheckoutRequest): string {
38 + return encodeRequestKey([
39 + request.flowKey,
40 + request.routeKey,
41 + request.environmentId,
42 + request.workspaceRoot,
43 + request.branch,
44 + request.worktreePath,
45 + ]);
46 +}
47 +
48 +function requestFromKey(key: string): BranchCheckoutRequest {
49 + const [flowKey, routeKey, environmentId, workspaceRoot, branch, worktreePath] =
50 + decodeRequestKey(key);
51 + return { flowKey, routeKey, environmentId, workspaceRoot, branch, worktreePath };
52 +}
53 +
54 +interface CheckoutEntry {
55 + readonly request: BranchCheckoutRequest;
56 + readonly checkout: Promise<BranchCheckoutResult>;
57 + readonly release: () => void;
58 + abandoned: boolean;
59 +}
60 +
61 +/**
62 + * Branch checkouts for draft routes. A checkout is a Git mutation, so it is
63 + * tied to the request, not to an atom node: the node can be removed and rebuilt
64 + * (a render read before the subscription commits) without running it again.
65 + */
66 +export function makeNewTaskBranchCheckouts(deps: {
67 + readonly run: (request: BranchCheckoutRequest) => Promise<BranchCheckoutResult>;
68 + /** Holds navigation until the checkout settles and its route is released. */
69 + readonly holdNavigation: (operation: Promise<unknown>) => void;
70 + /** Runs once the route is released, unless the route was abandoned first. */
71 + readonly onFailure: (request: BranchCheckoutRequest, result: BranchCheckoutFailure) => void;
72 +}) {
73 + // Ignoring a stale result cannot undo its Git mutation, so checkouts run one
74 + // at a time across routes.
75 + let tail: Promise<unknown> = Promise.resolve();
76 + // Registered when a checkout starts, never from render.
77 + const entries = new Map<string, CheckoutEntry>();
78 +
79 + function abandon(key: string, entry: CheckoutEntry): void {
80 + entry.abandoned = true;
81 + entry.release();
82 + entries.delete(key);
83 + }
84 +
85 + function start(key: string): Promise<BranchCheckoutResult> {
86 + const existing = entries.get(key);
87 + if (existing) return existing.checkout;
88 + const request = requestFromKey(key);
89 + // A route asks for one checkout at a time; a superseded request no longer
90 + // owns the route's failure handling or holds navigation.
91 + for (const [otherKey, other] of entries) {
92 + if (other.request.flowKey === request.flowKey) abandon(otherKey, other);
93 + }
94 + const released = Promise.withResolvers<void>();
95 + const checkout = tail.then(() => deps.run(request));
96 + tail = checkout.catch(() => undefined);
97 + const entry: CheckoutEntry = { request, checkout, release: released.resolve, abandoned: false };
98 + entries.set(key, entry);
99 + const handled = checkout.then(async (result) => {
100 + if (result._tag === "Success") return;
101 + await released.promise;
102 + if (!entry.abandoned) deps.onFailure(request, result);
103 + });
104 + // Navigation waits for the failure handling too, so its goBack lands first.
105 + deps.holdNavigation(Promise.allSettled([handled, released.promise]));
106 + return checkout;
107 + }
108 +
109 + return {
110 + atom: Atom.family((key: string) =>
111 + Atom.make(Effect.promise(() => start(key))).pipe(
112 + Atom.withLabel("mobile:new-task-branch-checkout"),
113 + ),
114 + ),
115 + /** The route rendered with removal unblocked, so navigation may proceed. */
116 + release(key: string): void {
117 + entries.get(key)?.release();
118 + },
119 + /** Abandons the checkouts of draft routes that are no longer on the stack. */
120 + prune(liveFlowKeys: ReadonlySet<string>): void {
121 + for (const [key, entry] of entries) {
122 + if (!liveFlowKeys.has(entry.request.flowKey)) abandon(key, entry);
123 + }
124 + },
125 + };
126 +}
apps/mobile/src/features/threads/new-task-flow-state.ts new
+32
@@ -0,0 +1,32 @@
1 +import {
2 + draftRouteIdentity,
3 + isDraftThreadRoute,
4 + type NewTaskDraftRouteParams,
5 +} from "./thread-route-state";
6 +
7 +/** The flow key for a draft Thread route: its key plus the draft it opened. */
8 +export function newTaskFlowKey(route: {
9 + readonly key: string;
10 + readonly params?: object;
11 +}): string | undefined {
12 + const draft = (route.params as { draft?: NewTaskDraftRouteParams } | undefined)?.draft;
13 + return draft ? `${route.key}:${draftRouteIdentity(draft)}` : undefined;
14 +}
15 +
16 +interface NavigationRoutes {
17 + readonly routes: ReadonlyArray<{
18 + readonly key: string;
19 + readonly name: string;
20 + readonly params?: object;
21 + }>;
22 +}
23 +
24 +/** Flow keys of the draft routes on the stack. */
25 +export function liveNewTaskFlowKeys(state: NavigationRoutes): ReadonlySet<string> {
26 + return new Set(
27 + state.routes.flatMap((route) => {
28 + const flowKey = isDraftThreadRoute(route) ? newTaskFlowKey(route) : undefined;
29 + return flowKey === undefined ? [] : [flowKey];
30 + }),
31 + );
32 +}
apps/mobile/src/lib/rootNavigation.test.ts new
+31
@@ -0,0 +1,31 @@
1 +import { expect, it, vi } from "vite-plus/test";
2 +import type { NavigationContainerRef } from "@react-navigation/native";
3 +
4 +vi.mock("@react-navigation/native", () => ({
5 + createNavigationContainerRef: () => ({
6 + current: null as { isReady(): boolean } | null,
7 + isReady() {
8 + return this.current?.isReady() ?? false;
9 + },
10 + }),
11 +}));
12 +
13 +const { attachRootNavigation, rootNavigationRef } = await import("./rootNavigation");
14 +
15 +function fakeContainer() {
16 + return { isReady: () => true } as NavigationContainerRef<ReactNavigation.RootParamList>;
17 +}
18 +
19 +it("keeps the newer container when an older root unmounts after it attached", () => {
20 + // Android activity replacement mounts the new root before the old one unmounts.
21 + const detachPrevious = attachRootNavigation(fakeContainer());
22 + const current = fakeContainer();
23 + const detachCurrent = attachRootNavigation(current);
24 +
25 + detachPrevious();
26 + expect(rootNavigationRef.current).toBe(current);
27 + expect(rootNavigationRef.isReady()).toBe(true);
28 +
29 + detachCurrent();
30 + expect(rootNavigationRef.current).toBeNull();
31 +});
apps/mobile/src/lib/rootNavigation.ts new
+24
@@ -0,0 +1,24 @@
1 +import {
2 + createNavigationContainerRef,
3 + type NavigationContainerRef,
4 +} from "@react-navigation/native";
5 +
6 +/**
7 + * The app's single navigation container. Work that outlives a screen (a draft
8 + * route's branch checkout) navigates through it.
9 + */
10 +export const rootNavigationRef = createNavigationContainerRef<ReactNavigation.RootParamList>();
11 +
12 +/**
13 + * Ref callback for the container. Android activity replacement mounts the new
14 + * root before the old one unmounts, so the old container must not clear the
15 + * ref the new one already owns.
16 + */
17 +export function attachRootNavigation(
18 + navigation: NavigationContainerRef<ReactNavigation.RootParamList> | null,
19 +): () => void {
20 + rootNavigationRef.current = navigation;
21 + return () => {
22 + if (rootNavigationRef.current === navigation) rootNavigationRef.current = null;
23 + };
24 +}
apps/mobile/vite.config.ts
+1
@@ -17,6 +17,7 @@ const reactTests = [
17 "src/features/settings/components/BranchNamingSettings.test.tsx",
18 "src/features/threads/ThreadMarkdownImage.test.tsx",
19 "src/features/threads/UsageLimitRecoveryCard.test.tsx",
20 + "src/features/threads/NewTaskDraftRouteScreen.test.tsx",
21 "src/native/NativeHeaderToolbar.test.tsx",
22 "src/native/useRestingTopOffset.test.tsx",
23 "src/native/useRetryingImageSource.test.tsx",