Skip to content

Commit 1efee3e

Browse files
fix(mobile): a draft route's branch checkout runs once, even across a reconnect
Opening a new task on a branch checks that branch out before the draft shows. The route screen ran the checkout from an effect keyed on the resolved project. When a reconnect dropped and restored the project while the checkout was in flight, the effect queued a second checkout of the same branch (a second switchRef), and the first result was thrown away. The checkout is now keyed by its request (draft route, project, branch) in a module-level checkout table read through an atom family. Reading the same request again returns the running checkout instead of starting another. Checkouts stay serialized across routes. The failure path (alert, then go back) and the split-view thread-selection hold live with the checkout, so the hold also covers the failure goBack. Routes that leave the stack are pruned from the navigation container's onStateChange, which now goes through a shared root navigation ref. Effects: NewTaskDraftRouteScreen 5 -> 2 (checkout runner, unmount release and failure handler removed; the draft reset layout effect and the release-after-prevent-commit effect stay, the latter because native-stack reads the prevent state one commit after usePreventRemove). Co-Authored-By: Claude Opus 5.5 <[email protected]>
1 parent a2398c2 commit 1efee3e

12 files changed

Lines changed: 589 additions & 128 deletions

‎apps/mobile/src/App.tsx‎

Lines changed: 15 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -9,10 +9,10 @@ import { GestureHandlerRootView } from "react-native-gesture-handler";
99
import { KeyboardProvider } from "react-native-keyboard-controller";
1010
import { SafeAreaProvider } from "react-native-safe-area-context";
1111
import {
12-
createNavigationContainerRef,
1312
createStaticNavigation,
1413
getActionFromState,
1514
getStateFromPath,
15+
type NavigationState,
1616
} from "@react-navigation/native";
1717

1818
import { RegistryContext } from "@effect/atom-react";
@@ -52,6 +52,8 @@ import {
5252
} from "./features/workspace/workspace-selection-store";
5353
import { workspaceDetailLinkAction } from "./features/workspace/workspace-detail-selection";
5454
import { NativeLayoutMetricsProvider } from "./native/native-layout-metrics";
55+
import { attachRootNavigation, rootNavigationRef } from "./lib/rootNavigation";
56+
import { pruneNewTaskBranchCheckouts } from "./features/threads/NewTaskDraftRouteScreen";
5557

5658
import "../global.css";
5759

@@ -84,7 +86,15 @@ const appLinking = {
8486
};
8587

8688
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+
}
8898

8999
declare const module: { readonly hot?: FoundationHotModule } | undefined;
90100

@@ -148,11 +158,11 @@ function AppContent() {
148158
<NativeLayoutMetricsProvider>
149159
<IncomingShareProvider>
150160
<Navigation
151-
ref={navigationRef}
161+
ref={attachRootNavigation}
152162
linking={appLinking}
153-
onReady={() => recordWorkspaceSelections(navigationRef.getRootState())}
163+
onReady={handleNavigationReady}
154164
theme={navigationTheme}
155-
onStateChange={recordWorkspaceSelections}
165+
onStateChange={handleNavigationStateChange}
156166
/>
157167
</IncomingShareProvider>
158168
<Dialog.Host />

‎apps/mobile/src/features/layout/AdaptiveWorkspaceLayout.tsx‎

Lines changed: 2 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
import { SafeAreaInsetsContext, useSafeAreaInsets } from "react-native-safe-area-context";
22
import { AdaptiveWorkspaceContext, useAdaptiveWorkspaceLayout } from "./adaptive-workspace-context";
3-
import { createDeferredNavigation } from "./deferred-navigation";
3+
import { threadSelectionDeferral } from "./deferred-navigation";
44
import { uuidv4 } from "../../lib/uuid";
55
import type {
66
EnvironmentProject,
@@ -491,10 +491,9 @@ function AdaptiveWorkspaceLayoutContent(
491491
};
492492
const handleOpenSettings = () => openWorkspaceTab("settings");
493493

494-
const deferredThreadSelection = useMemo(() => createDeferredNavigation(), []);
495494
/** The one way to show a page in the detail column; see `selectWorkspaceDetail`. */
496495
function handleSelectDetail(detail: WorkspaceDetail, sheet?: WorkspaceDetailSheet) {
497-
deferredThreadSelection.run(() => {
496+
threadSelectionDeferral.run(() => {
498497
if (Platform.OS === "android") Keyboard.dismiss();
499498
setFileInspectorPreferredVisible(false);
500499
if (layout.primarySidebarOverlaysContent) setPrimarySidebarVisible(false);
@@ -770,7 +769,6 @@ function AdaptiveWorkspaceLayoutContent(
770769
fileInspector,
771770
primarySidebarSearchQuery,
772771
startNewTask: handleStartNewTask,
773-
deferThreadSelectionUntil: deferredThreadSelection.waitFor,
774772
selectDetail: handleSelectDetail,
775773
activateAuxiliaryPaneRole,
776774
registerWorkspaceInspector,

‎apps/mobile/src/features/layout/adaptive-workspace-context.ts‎

Lines changed: 0 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -20,7 +20,6 @@ interface AdaptiveWorkspaceContextValue {
2020
readonly fileInspector: FileInspectorPaneLayout;
2121
readonly primarySidebarSearchQuery: string;
2222
readonly startNewTask: () => void;
23-
readonly deferThreadSelectionUntil: (operation: Promise<unknown>) => void;
2423
/** Use `useSelectWorkspaceDetail`, which also works outside the layout. */
2524
readonly selectDetail?: (detail: WorkspaceDetail, sheet?: WorkspaceDetailSheet) => void;
2625
readonly activateAuxiliaryPaneRole: (role: WorkspaceAuxiliaryPaneRole) => () => void;
@@ -67,7 +66,6 @@ export const AdaptiveWorkspaceContext = createContext<AdaptiveWorkspaceContextVa
6766
fileInspector: compactFileInspector,
6867
primarySidebarSearchQuery: "",
6968
startNewTask: () => undefined,
70-
deferThreadSelectionUntil: () => undefined,
7169
activateAuxiliaryPaneRole: () => () => undefined,
7270
registerWorkspaceInspector: () => () => undefined,
7371
setPrimarySidebarSearchQuery: () => undefined,

‎apps/mobile/src/features/layout/deferred-navigation.ts‎

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -20,3 +20,9 @@ export function createDeferredNavigation() {
2020
},
2121
};
2222
}
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();
Lines changed: 138 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,138 @@
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+
// Hook results stay stable across renders, as the real hooks' are.
38+
layout: { deferThreadSelectionUntil: () => undefined },
39+
navigation: { goBack: () => undefined },
40+
preventContext: { preventedRoutes: {} },
41+
};
42+
});
43+
44+
function useSnapshot(): Snapshot {
45+
return useSyncExternalStore(harness.subscribe, () => harness.state.snapshot!);
46+
}
47+
48+
vi.mock("react-native", () => ({
49+
View: ({ children }: { children: ReactNode }) => <div>{children}</div>,
50+
}));
51+
vi.mock("../../components/ui/AppText", () => ({
52+
AppText: ({ children }: { children: ReactNode }) => <span>{children}</span>,
53+
}));
54+
vi.mock("../../components/ui/Dialog", () => ({ alert: vi.fn() }));
55+
vi.mock("../../native/StackHeader", () => ({ NativeStackScreenOptions: () => null }));
56+
vi.mock("./ThreadScreenHost", () => ({
57+
ThreadScreenFallback: ({ children }: { children: ReactNode }) => <>{children}</>,
58+
}));
59+
vi.mock("./NewTaskDraftScreen", () => ({
60+
NewTaskDraftScreen: (props: { initialProjectRef: { branch?: string | null } }) => (
61+
<p>draft on {props.initialProjectRef.branch}</p>
62+
),
63+
}));
64+
vi.mock("./new-task-context-presentation", () => ({
65+
resolveNewTaskBranchWorktreePath: () => null,
66+
}));
67+
vi.mock("./new-task-flow-provider", () => ({
68+
useNewTaskFlow: () => harness,
69+
}));
70+
vi.mock("./checkout-new-task-branch", () => ({ checkoutNewTaskBranch: harness.checkout }));
71+
vi.mock("../layout/AdaptiveWorkspaceLayout", () => ({
72+
useAdaptiveWorkspaceLayout: () => harness.layout,
73+
}));
74+
vi.mock("../../state/entities", () => ({ useProjects: () => useSnapshot().projects }));
75+
vi.mock("../../state/workspace", () => ({
76+
useWorkspaceState: () => ({ state: useSnapshot().catalog }),
77+
}));
78+
vi.mock("../../state/vcs", () => ({ vcsEnvironment: { readRefs: {}, switchRef: {} } }));
79+
vi.mock("../../state/use-atom-command", () => ({ useAtomCommand: () => harness.checkout }));
80+
vi.mock("@react-navigation/native", () => ({
81+
CommonActions: { goBack: () => ({ type: "GO_BACK" }) },
82+
createNavigationContainerRef: () => ({ current: null }),
83+
useNavigation: () => harness.navigation,
84+
useRoute: () => harness.route,
85+
usePreventRemove: () => undefined,
86+
usePreventRemoveContext: () => harness.preventContext,
87+
}));
88+
89+
import { NewTaskDraftRouteScreen } from "./NewTaskDraftRouteScreen";
90+
91+
const project = { environmentId: "env-1", id: "project-1", workspaceRoot: "/repo" };
92+
const connected: Snapshot["catalog"] = {
93+
isLoadingConnections: false,
94+
hasLoadedShellSnapshot: true,
95+
hasConnectingEnvironment: false,
96+
connectionError: null,
97+
};
98+
99+
it("checks the branch out once when a reconnect drops and restores the project", async () => {
100+
(globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true;
101+
const firstCheckout = Promise.withResolvers<unknown>();
102+
harness.checkout.mockReturnValueOnce(firstCheckout.promise);
103+
harness.checkout.mockResolvedValue(
104+
AsyncResult.success({ name: "feature", current: true, isDefault: false, worktreePath: null }),
105+
);
106+
harness.set({ projects: [project], catalog: connected });
107+
const draft = { environmentId: "env-1", projectId: "project-1", branch: "feature" };
108+
harness.route = { key: "thread-route", name: "Thread", params: { draft } };
109+
110+
const container = document.createElement("div");
111+
const root = createRoot(container);
112+
using _root = { [Symbol.dispose]: () => act(() => root.unmount()) };
113+
act(() =>
114+
root.render(
115+
<NewTaskDraftRouteScreen
116+
route={{ key: "thread-route", name: "Thread", params: draft } as never}
117+
/>,
118+
),
119+
);
120+
await vi.waitFor(() => expect(harness.checkout).toHaveBeenCalledTimes(1));
121+
122+
// The connection drops while the checkout runs, then the project comes back.
123+
act(() => harness.set({ projects: [], catalog: { ...connected, isLoadingConnections: true } }));
124+
act(() => harness.set({ projects: [project], catalog: connected }));
125+
await act(async () => {
126+
firstCheckout.resolve(
127+
AsyncResult.success({ name: "feature", current: true, isDefault: false, worktreePath: null }),
128+
);
129+
});
130+
131+
await vi.waitFor(() =>
132+
expect(
133+
harness.checkout.mock.calls.length > 1 || container.textContent === "draft on feature",
134+
).toBe(true),
135+
);
136+
expect(harness.checkout).toHaveBeenCalledTimes(1);
137+
expect(container.textContent).toBe("draft on feature");
138+
});

0 commit comments

Comments
 (0)