@devries-cameron20 / t3code-1 / commits / b45ca716f9
Fork 0

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

fix(mobile): a project picked while No project opens is no longer replaced (#38978)

Co-authored-by: Julius Marminge <julius0216@outlook.com>

Wout Stiens committed Nov 19, 2026 at 08:29 UTC b45ca716f92ded3fcf63f2acc8db94c47b7d9efc
5 files changed +268 -17
apps/mobile/src/features/threads/NewTaskRouteScreen.test.tsx new
+224
@@ -0,0 +1,224 @@
1 +import type { ReactNode } from "react";
2 +import { act } from "react";
3 +import * as React from "react";
4 +import { createRoot } from "react-dom/client";
5 +import type { EnvironmentProject } from "@t3tools/client-runtime/state/shell";
6 +import { EnvironmentId, ProjectId } from "@t3tools/contracts";
7 +import { expect, it, vi } from "vite-plus/test";
8 +import { retargetSavedNewTaskDraft } from "../../state/use-composer-drafts";
9 +
10 +const environmentId = EnvironmentId.make("env-1");
11 +
12 +function project(id: string, workspaceRoot: string): EnvironmentProject {
13 + return {
14 + environmentId,
15 + id: ProjectId.make(id),
16 + title: id,
17 + workspaceRoot,
18 + repositoryIdentity: null,
19 + defaultModelSelection: null,
20 + defaultThreadEnvMode: "worktree",
21 + scripts: [],
22 + createdAt: "2026-10-26T00:00:00Z",
23 + updatedAt: "2026-10-26T00:00:00Z",
24 + };
25 +}
26 +
27 +const regular = project("app", "/repo/app");
28 +const scratch = project("scratch", "/scratch");
29 +
30 +const harness = vi.hoisted(() => ({
31 + setProject: vi.fn(),
32 + openScratch: vi.fn(),
33 + selectDetail: vi.fn(),
34 + navigation: {
35 + goBack: vi.fn(),
36 + getState: () => ({
37 + routeNames: ["Thread", "NewTaskProject"],
38 + index: 1,
39 + routes: [{ name: "Thread", params: { draft: {} } }, { name: "NewTaskProject" }],
40 + }),
41 + getParent: () => undefined,
42 + canGoBack: () => true,
43 + dispatch: vi.fn(),
44 + navigate: vi.fn(),
45 + },
46 +}));
47 +
48 +vi.mock("react-native", () => ({
49 + Platform: { OS: "ios" },
50 + View: ({ children }: { children?: ReactNode }) => <div>{children}</div>,
51 + Pressable: (props: {
52 + accessibilityLabel: string;
53 + disabled?: boolean;
54 + onPress: () => void;
55 + children?: ReactNode;
56 + }) => (
57 + <button aria-label={props.accessibilityLabel} disabled={props.disabled} onClick={props.onPress}>
58 + {props.children}
59 + </button>
60 + ),
61 +}));
62 +vi.mock("react-native-safe-area-context", () => ({
63 + useSafeAreaInsets: () => ({ top: 0, bottom: 0, left: 0, right: 0 }),
64 +}));
65 +vi.mock("gt-react-native", () => ({
66 + msg: (text: string) => text,
67 + T: ({ children }: { children?: ReactNode }) => <>{children}</>,
68 + useGT: () => (text: string) => text,
69 + useMessages: () => (text: string) => text,
70 +}));
71 +vi.mock("@react-navigation/native", () => ({
72 + StackActions: { push: (name: string) => ({ type: "PUSH", name }) },
73 + useFocusEffect: (effect: () => () => void) => React.useEffect(effect, [effect]),
74 + useIsFocused: () => true,
75 + useNavigation: () => harness.navigation,
76 +}));
77 +vi.mock("../../components/ui/NavigationRow", () => ({
78 + NavigationRow: (props: { title: string; disabled?: boolean; onPress?: () => void }) => (
79 + <button aria-label={props.title} disabled={props.disabled === true} onClick={props.onPress}>
80 + {props.title}
81 + </button>
82 + ),
83 +}));
84 +vi.mock("../../components/ui/Dialog", () => ({ alert: vi.fn() }));
85 +vi.mock("../../components/ui/AppActivityIndicator", () => ({ AppActivityIndicator: () => null }));
86 +vi.mock("../../components/ui/AppBar", () => ({ AppBar: () => null }));
87 +vi.mock("../../components/ui/AppSymbol", () => ({ SymbolView: () => null }));
88 +vi.mock("../../components/ui/Button", () => ({ Button: () => null }));
89 +vi.mock("../../components/ui/ScreenContent", () => ({
90 + ScreenContent: ({ children }: { children?: ReactNode }) => <>{children}</>,
91 +}));
92 +vi.mock("../../components/ui/ScreenScrollView", () => ({
93 + ScreenScrollView: ({ children }: { children?: ReactNode }) => <>{children}</>,
94 +}));
95 +vi.mock("../../components/ui/AppText", () => ({
96 + AppText: ({ children }: { children?: ReactNode }) => <span>{children}</span>,
97 +}));
98 +vi.mock("../../components/ProjectFavicon", () => ({ ProjectFavicon: () => null }));
99 +vi.mock("../connection/environmentStatusText", () => ({ runtimeConnectionErrorText: () => null }));
100 +vi.mock("../../state/entities", () => ({
101 + useProjects: () => [regular, scratch],
102 + useServerConfigs: () => new Map([[environmentId, { scratchWorkspaceRoot: "/scratch" }]]),
103 +}));
104 +vi.mock("../../state/projects", () => ({ projectEnvironment: { openScratch: {} } }));
105 +vi.mock("../../state/use-atom-command", () => ({ useAtomCommand: () => harness.openScratch }));
106 +vi.mock("../../state/use-composer-drafts", () => ({ retargetSavedNewTaskDraft: vi.fn() }));
107 +vi.mock("../../state/use-remote-environment-registry", () => ({
108 + useRemoteConnectionStatus: () => ({
109 + connectedEnvironments: [{ environmentId, connectionState: "connected" }],
110 + }),
111 +}));
112 +vi.mock("../../state/workspace", () => ({
113 + useWorkspaceState: () => ({ state: { hasReadyEnvironment: true } }),
114 +}));
115 +vi.mock("../sharing/IncomingShareProvider", () => ({
116 + useIncomingShare: () => ({ getShare: () => null, releaseShareReservation: vi.fn() }),
117 +}));
118 +vi.mock("../layout/workspace/useSelectWorkspaceDetail", () => ({
119 + useSelectWorkspaceDetail: () => harness.selectDetail,
120 +}));
121 +vi.mock("./new-task-flow-provider", () => ({
122 + useNewTaskFlow: () => ({
123 + projectScopes: [
124 + {
125 + key: "app",
126 + title: "app",
127 + representative: regular,
128 + projects: [regular],
129 + projectRefs: [],
130 + pinned: false,
131 + archived: false,
132 + },
133 + ],
134 + selectedEnvironmentId: environmentId,
135 + setProject: harness.setProject,
136 + }),
137 +}));
138 +
139 +import { NewTaskRouteScreen } from "./NewTaskRouteScreen";
140 +
141 +it("keeps the project picked while No project was still opening", async () => {
142 + (globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true;
143 + const opening = Promise.withResolvers<unknown>();
144 + harness.openScratch.mockReturnValue(opening.promise);
145 +
146 + const container = document.createElement("div");
147 + const root = createRoot(container);
148 + using _root = { [Symbol.dispose]: () => act(() => root.unmount()) };
149 + act(() => root.render(<NewTaskRouteScreen route={{ params: undefined } as never} />));
150 + const row = (label: string) => container.querySelector<HTMLElement>(`[aria-label="${label}"]`)!;
151 +
152 + act(() => row("No project").click());
153 + await act(async () => row("app").click());
154 + await act(async () => opening.resolve({ _tag: "Success", value: scratch }));
155 +
156 + expect(harness.setProject.mock.calls).toEqual([[regular]]);
157 + expect(harness.navigation.goBack).toHaveBeenCalledTimes(1);
158 +});
159 +
160 +function renderWithSavedDraft() {
161 + (globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true;
162 + const opening = Promise.withResolvers<unknown>();
163 + const retargeting = Promise.withResolvers<boolean>();
164 + harness.openScratch.mockReturnValue(opening.promise);
165 + vi.mocked(retargetSavedNewTaskDraft)
166 + .mockReset()
167 + .mockImplementation((_draftId, target) =>
168 + target.projectId === scratch.id ? retargeting.promise : Promise.resolve(true),
169 + );
170 + harness.selectDetail.mockClear();
171 +
172 + const container = document.createElement("div");
173 + const root = createRoot(container);
174 + const route = { params: { draftId: "existing-draft" } } as never;
175 + act(() => root.render(<NewTaskRouteScreen key="first" route={route} />));
176 + return {
177 + opening,
178 + retargeting,
179 + root,
180 + route,
181 + row: (label: string) => container.querySelector<HTMLElement>(`[aria-label="${label}"]`)!,
182 + [Symbol.dispose]: () => act(() => root.unmount()),
183 + };
184 +}
185 +
186 +const appDraftSelection = [
187 + [
188 + {
189 + name: "Thread",
190 + params: { draft: { environmentId, projectId: regular.id, draftId: "existing-draft" } },
191 + },
192 + ],
193 +];
194 +
195 +it("keeps the picked project after backing out and reopening while No project is pending", async () => {
196 + using screen = renderWithSavedDraft();
197 +
198 + act(() => screen.row("No project").click());
199 + act(() => screen.root.render(null));
200 + act(() => screen.root.render(<NewTaskRouteScreen key="second" route={screen.route} />));
201 + await act(async () => screen.row("app").click());
202 + await act(async () => {
203 + screen.opening.resolve({ _tag: "Success", value: scratch });
204 + screen.retargeting.resolve(true);
205 + });
206 +
207 + expect(harness.selectDetail.mock.calls).toEqual(appDraftSelection);
208 +});
209 +
210 +it("cancels the No project draft retarget when another project is picked", async () => {
211 + using screen = renderWithSavedDraft();
212 +
213 + act(() => screen.row("No project").click());
214 + await act(async () => screen.opening.resolve({ _tag: "Success", value: scratch }));
215 + const scratchSignal = vi
216 + .mocked(retargetSavedNewTaskDraft)
217 + .mock.calls.find(([, target]) => target.projectId === scratch.id)?.[2];
218 + expect(scratchSignal?.aborted).toBe(false);
219 + await act(async () => screen.row("app").click());
220 + expect(scratchSignal?.aborted).toBe(true);
221 + await act(async () => screen.retargeting.resolve(true));
222 +
223 + expect(harness.selectDetail.mock.calls).toEqual(appDraftSelection);
224 +});
apps/mobile/src/features/threads/NewTaskRouteScreen.tsx
+31 -15
@@ -7,6 +7,7 @@ import { NavigationRow } from "../../components/ui/NavigationRow";
7 import { AppBar } from "../../components/ui/AppBar";
8 import {
9 StackActions,
10 + useFocusEffect,
11 useIsFocused,
12 useNavigation,
13 type StaticScreenProps,
@@ -19,7 +20,7 @@ import {
20 squashAtomCommandFailure,
21 } from "@t3tools/client-runtime/state/runtime";
22 import type { EnvironmentProject } from "@t3tools/client-runtime/state/shell";
22 -import { useEffect, useRef, useState } from "react";
23 +import { useCallback, useEffect, useRef, useState } from "react";
24 import { Platform, Pressable, View } from "react-native";
25 import { useSafeAreaInsets } from "react-native-safe-area-context";
26 import { cn } from "../../lib/cn";
@@ -235,13 +236,19 @@ export function NewTaskRouteScreen({ route }: StaticScreenProps<NewTaskRoutePara
236 })
237 : null;
238 const canStartScratch = scratchOption?.ready === true;
238 - const scratchStartInFlightRef = useRef(false);
239 + const pendingScratchRef = useRef<AbortController | null>(null);
240 + const cancelPendingScratch = useCallback(() => {
241 + pendingScratchRef.current?.abort();
242 + pendingScratchRef.current = null;
243 + }, []);
244 + useFocusEffect(useCallback(() => cancelPendingScratch, [cancelPendingScratch]));
245
240 - async function selectProject(project: EnvironmentProject): Promise<void> {
246 + async function selectProject(project: EnvironmentProject, signal?: AbortSignal): Promise<void> {
247 if (incomingShare?.destination && !reservedDestinationProject) {
248 try {
249 await releaseShareReservation(incomingShare.id, incomingShare.destination);
250 } catch (error) {
251 + if (signal?.aborted) return;
252 Dialog.alert(
253 gt("Could not change project"),
254 errorDisplayMessage(error, m) ??
@@ -249,6 +256,7 @@ export function NewTaskRouteScreen({ route }: StaticScreenProps<NewTaskRoutePara
256 );
257 return;
258 }
259 + if (signal?.aborted) return;
260 }
261 const root = navigation.getState()?.routeNames.includes("NewTaskProject")
262 ? navigation
@@ -264,13 +272,15 @@ export function NewTaskRouteScreen({ route }: StaticScreenProps<NewTaskRoutePara
272 const retargeted =
273 routeDraftId === undefined
274 ? false
267 - : await retargetSavedNewTaskDraft(routeDraftId, {
268 - environmentId: project.environmentId,
269 - projectId: project.id,
270 - }).then(
275 + : await retargetSavedNewTaskDraft(
276 + routeDraftId,
277 + { environmentId: project.environmentId, projectId: project.id },
278 + signal,
279 + ).then(
280 (found) => found,
281 () => null,
282 );
283 + if (signal?.aborted) return;
284 if (retargeted === null) {
285 Dialog.alert(
286 gt("Could not change project"),
@@ -292,13 +302,20 @@ export function NewTaskRouteScreen({ route }: StaticScreenProps<NewTaskRoutePara
302 });
303 }
304
305 + function chooseProject(project: EnvironmentProject): void {
306 + cancelPendingScratch();
307 + void selectProject(project);
308 + }
309 +
310 async function startScratch(): Promise<void> {
296 - if (!canStartScratch || !scratchOption || scratchStartInFlightRef.current) return;
311 + if (!canStartScratch || !scratchOption || pendingScratchRef.current) return;
312 const environmentId = scratchOption.environmentId;
298 - scratchStartInFlightRef.current = true;
313 + const request = new AbortController();
314 + pendingScratchRef.current = request;
315 const result = await openScratch({ environmentId, input: {} });
316 + if (request.signal.aborted) return;
317 if (result._tag === "Failure") {
301 - scratchStartInFlightRef.current = false;
318 + pendingScratchRef.current = null;
319 if (!isAtomCommandInterrupted(result)) {
320 const error = squashAtomCommandFailure(result);
321 Dialog.alert(
@@ -309,9 +326,8 @@ export function NewTaskRouteScreen({ route }: StaticScreenProps<NewTaskRoutePara
326 }
327 return;
328 }
312 - // selectProject handles its own failures, so this never throws.
313 - await selectProject(result.value);
314 - scratchStartInFlightRef.current = false;
329 + await selectProject(result.value, request.signal);
330 + if (pendingScratchRef.current === request) pendingScratchRef.current = null;
331 }
332
333 // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- navigates to the incoming share's reserved destination draft once its project loads and the screen is focused
@@ -545,7 +561,7 @@ export function NewTaskRouteScreen({ route }: StaticScreenProps<NewTaskRoutePara
561 subtitleNumberOfLines={1}
562 subtitleEllipsizeMode="middle"
563 disabled={reservedDestinationProject !== null}
548 - onPress={() => void selectProject(selectionTarget)}
564 + onPress={() => chooseProject(selectionTarget)}
565 leading={
566 <ProjectFavicon
567 environmentId={scope.representative.environmentId}
@@ -568,7 +584,7 @@ export function NewTaskRouteScreen({ route }: StaticScreenProps<NewTaskRoutePara
584 accessibilityRole="button"
585 accessibilityLabel={scope.title}
586 disabled={reservedDestinationProject !== null}
571 - onPress={() => void selectProject(selectionTarget)}
587 + onPress={() => chooseProject(selectionTarget)}
588 className="flex-row items-center gap-3 bg-grouped-card px-4 py-3.5"
589 >
590 <View className="h-7 w-7 items-center justify-center">
apps/mobile/src/state/use-composer-drafts.test.ts
+8
@@ -2053,6 +2053,14 @@ describe("mobile composer drafts", () => {
2053 appAtomRegistry.set(composerDraftsAtom, {});
2054 resetComposerDraftsLoadState();
2055
2056 + composerDraftFileMocks.blockRead();
2057 + const controller = new AbortController();
2058 + const cancelled = retargetSavedNewTaskDraft(key, to, controller.signal);
2059 + controller.abort();
2060 + composerDraftFileMocks.releaseRead();
2061 + await expect(cancelled).resolves.toBe(false);
2062 + expect(getComposerDraftSnapshot(key).project).toMatchObject(from);
2063 +
2064 await expect(retargetSavedNewTaskDraft(key, to)).resolves.toBe(true);
2065 expect(getComposerDraftSnapshot(key)).toMatchObject({
2066 text: "kept through a cold start",
apps/mobile/src/state/use-composer-drafts.ts
+4 -2
@@ -2075,13 +2075,15 @@ export function retargetNewTaskDraft(
2075 });
2076 }
2077
2078 -/** Retargets a saved draft once drafts load; an absent one is not created. */
2078 +/** Retargets a saved draft after loading. Returns false if absent or cancelled before the write. */
2079 export async function retargetSavedNewTaskDraft(
2080 draftKey: string,
2081 project: { readonly environmentId: EnvironmentId; readonly projectId: ProjectId },
2082 + signal?: AbortSignal,
2083 ): Promise<boolean> {
2084 await waitForComposerDraftsLoaded();
2084 - if (appAtomRegistry.get(composerDraftsAtom)[draftKey] === undefined) return false;
2085 + if (signal?.aborted || appAtomRegistry.get(composerDraftsAtom)[draftKey] === undefined)
2086 + return false;
2087 retargetNewTaskDraft(draftKey, project);
2088 return true;
2089 }
apps/mobile/vite.config.ts
+1
@@ -8,6 +8,7 @@ const reactTests = [
8 "src/features/threads/useSubmitAfterNativeImages.test.tsx",
9 "src/features/threads/git/GitBranchesSheet.test.tsx",
10 "src/features/threads/new-task-flow-provider.test.tsx",
11 + "src/features/threads/NewTaskRouteScreen.test.tsx",
12 "src/features/layout/workspace/workspace-tabs-state.test.ts",
13 "src/state/use-thread-pr.demand.test.tsx",
14 "src/features/threads/git/GitBranchesSheet.occupancy.test.tsx",