Skip to content

Commit f80b516

Browse files
committed
fix(mobile): open the existing project when adding a duplicate path
1 parent f054d1b commit f80b516

2 files changed

Lines changed: 199 additions & 24 deletions

File tree

‎apps/mobile/src/features/projects/AddProjectScreen.test.ts‎

Lines changed: 145 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -11,9 +11,25 @@ import { afterEach, beforeEach, describe, expect, it, vi } from "vite-plus/test"
1111
const state = vi.hoisted(() => ({
1212
scopes: new Set<string>(),
1313
baseDirectory: "",
14+
home: "",
15+
cloneTracking: false,
1416
projects: [] as string[],
17+
existingProjects: [] as Array<{
18+
environmentId: string;
19+
id: string;
20+
title: string;
21+
workspaceRoot: string;
22+
}>,
23+
navigations: [] as unknown[],
24+
startedClones: [] as string[],
25+
draftTexts: new Map<string, string>(),
1526
}));
1627

28+
// Mirrors the server: `~` is the environment's home, which the client cannot see.
29+
function expandHome(path: string) {
30+
return path.startsWith("~") ? `${state.home}${path.slice(1)}` : path;
31+
}
32+
1733
vi.mock("react", async (importOriginal) => ({
1834
...(await importOriginal<typeof import("react")>()),
1935
useCallback: (callback: unknown) => callback,
@@ -36,7 +52,10 @@ vi.mock("react-native", () => ({
3652
View: "View",
3753
}));
3854
vi.mock("@react-navigation/native", () => ({
39-
useNavigation: () => ({ dispatch: () => {} }),
55+
useNavigation: () => ({
56+
dispatch: (action: unknown) => state.navigations.push(action),
57+
getState: () => ({ index: 0, routes: [{ key: "home", name: "Home" }] }),
58+
}),
4059
CommonActions: { reset: (input: unknown) => input },
4160
StackActions: {},
4261
}));
@@ -56,13 +75,17 @@ vi.mock("../../state/session", () => ({
5675
readEnvironmentScope: (_environmentId: string, scope: string) => state.scopes.has(scope),
5776
}));
5877
vi.mock("../../state/entities", () => ({
59-
useProjects: () => [],
78+
useProjects: () => state.existingProjects,
79+
waitForProject: async () => ({}),
6080
useServerConfigs: () =>
6181
new Map([
6282
[
6383
"environment",
6484
{
65-
environment: { platform: { os: "linux" }, capabilities: {} },
85+
environment: {
86+
platform: { os: "linux" },
87+
capabilities: { projectCloneTracking: state.cloneTracking },
88+
},
6689
settings: { addProjectBaseDirectory: state.baseDirectory },
6790
},
6891
],
@@ -80,17 +103,32 @@ vi.mock("../../state/use-remote-environment-registry", () => ({
80103
}),
81104
}));
82105
vi.mock("../../state/use-atom-command", () => ({ useAtomCommand: (command: unknown) => command }));
83-
vi.mock("../../state/use-atom-query-runner", () => ({ useAtomQueryRunner: () => () => {} }));
106+
vi.mock("../../state/use-atom-query-runner", () => ({
107+
useAtomQueryRunner:
108+
(query: unknown) =>
109+
async ({ input }: { input: { partialPath: string } }) => {
110+
if (query !== "browse") return undefined;
111+
const directory = expandHome(input.partialPath);
112+
return NodeFS.existsSync(directory)
113+
? AsyncResult.success({ parentPath: NodePath.resolve(directory), entries: [] })
114+
: AsyncResult.failure(Cause.fail(new Error("read_directory_failed")));
115+
},
116+
}));
84117
vi.mock("../../state/query", () => ({ useEnvironmentQuery: () => ({ data: null }) }));
85118
vi.mock("../../state/presentation", () => ({
86119
useEnvironmentPresentation: () => ({ isReady: true, presentation: null }),
87120
}));
88-
vi.mock("../../state/filesystem", () => ({ filesystemEnvironment: {} }));
121+
vi.mock("../../state/filesystem", () => ({ filesystemEnvironment: { browse: "browse" } }));
89122
vi.mock("../../state/sourceControl", () => ({
90123
sourceControlEnvironment: {
91124
cloneRepository: async ({ input }: { input: { destinationPath: string } }) => {
92-
NodeFS.mkdirSync(input.destinationPath);
93-
return AsyncResult.success({ cwd: input.destinationPath });
125+
const cwd = expandHome(input.destinationPath);
126+
NodeFS.mkdirSync(cwd);
127+
return AsyncResult.success({ cwd });
128+
},
129+
startProjectClone: async ({ input }: { input: { destinationPath: string } }) => {
130+
state.startedClones.push(input.destinationPath);
131+
return AsyncResult.success(undefined);
94132
},
95133
},
96134
}));
@@ -106,7 +144,13 @@ vi.mock("../../state/projects", () => ({
106144
},
107145
}));
108146

109-
import { AddProjectDestinationScreen } from "./AddProjectScreen";
147+
vi.mock("../../state/use-composer-drafts", () => ({
148+
waitForComposerDraftsLoaded: async () => {},
149+
createNewTaskDraft: () => "draft",
150+
setComposerDraftText: (draftId: string, text: string) => state.draftTexts.set(draftId, text),
151+
}));
152+
153+
import { AddProjectDestinationScreen, AddProjectLocalFolderScreen } from "./AddProjectScreen";
110154

111155
function findAction(node: ReactNode, label: string): (() => unknown) | null {
112156
if (Array.isArray(node)) {
@@ -123,12 +167,13 @@ function findAction(node: ReactNode, label: string): (() => unknown) | null {
123167
return findAction(node.props.children, label);
124168
}
125169

126-
function cloneAction() {
170+
function cloneAction(prompt?: string) {
127171
const action = findAction(
128172
AddProjectDestinationScreen({
129173
environmentId: "environment",
130174
remoteUrl: "https://example.com/repo.git",
131175
repositoryName: "repo",
176+
...(prompt ? { prompt } : {}),
132177
}),
133178
"Clone project",
134179
);
@@ -169,3 +214,94 @@ describe("clone project permissions", () => {
169214
},
170215
);
171216
});
217+
218+
function addLocalFolderAction() {
219+
const action = findAction(
220+
AddProjectLocalFolderScreen({ environmentId: "environment" }),
221+
"Add project",
222+
);
223+
if (!action) throw new Error("Add project action missing");
224+
return action;
225+
}
226+
227+
function openedDraft() {
228+
expect(state.navigations).toHaveLength(1);
229+
const { routes } = state.navigations[0] as {
230+
routes: Array<{ name: string; params: { draft: object } }>;
231+
};
232+
const route = routes.at(-1);
233+
expect(route?.name).toBe("Thread");
234+
return route?.params.draft;
235+
}
236+
237+
describe("adding a destination that is already a project", () => {
238+
beforeEach(async () => {
239+
state.home = await NodeFSP.mkdtemp(NodePath.join(NodeOS.tmpdir(), "t3-existing-project-"));
240+
await NodeFSP.mkdir(NodePath.join(state.home, "work", "repo"), { recursive: true });
241+
state.scopes = new Set([AuthSourceControlWriteScope, AuthOrchestrationOperateScope]);
242+
state.cloneTracking = false;
243+
state.projects = [];
244+
state.navigations = [];
245+
state.startedClones = [];
246+
state.draftTexts = new Map();
247+
state.existingProjects = [
248+
{
249+
environmentId: "environment",
250+
id: "existing",
251+
title: "repo",
252+
workspaceRoot: NodePath.join(state.home, "work", "repo"),
253+
},
254+
];
255+
});
256+
257+
afterEach(async () => {
258+
await NodeFSP.rm(state.home, { recursive: true, force: true });
259+
});
260+
261+
it.each(["~/work/repo", "ABSOLUTE"])(
262+
"opens the existing project for local folder %s",
263+
async (baseDirectory) => {
264+
state.baseDirectory =
265+
baseDirectory === "ABSOLUTE" ? NodePath.join(state.home, "work", "repo") : baseDirectory;
266+
await addLocalFolderAction()();
267+
268+
expect(state.projects).toEqual([]);
269+
expect(openedDraft()).toEqual({
270+
environmentId: "environment",
271+
projectId: "existing",
272+
title: "repo",
273+
});
274+
},
275+
);
276+
277+
it("still adds the folder when only another environment has that path", async () => {
278+
state.baseDirectory = "~/work/repo";
279+
state.existingProjects = state.existingProjects.map((project) => ({
280+
...project,
281+
environmentId: "other-environment",
282+
}));
283+
await addLocalFolderAction()();
284+
285+
expect(state.projects).toEqual(["~/work/repo"]);
286+
expect(openedDraft()).toMatchObject({ projectId: "project" });
287+
});
288+
289+
it("opens the existing project instead of cloning into it", async () => {
290+
state.baseDirectory = "~/work";
291+
await cloneAction()();
292+
293+
expect(await NodeFSP.readdir(NodePath.join(state.home, "work", "repo"))).toEqual([]);
294+
expect(state.projects).toEqual([]);
295+
expect(openedDraft()).toMatchObject({ projectId: "existing" });
296+
});
297+
298+
it("carries the prompt into the existing project instead of starting a tracked clone", async () => {
299+
state.baseDirectory = "~/work";
300+
state.cloneTracking = true;
301+
await cloneAction("Fix the flaky test")();
302+
303+
expect(state.startedClones).toEqual([]);
304+
expect(openedDraft()).toMatchObject({ projectId: "existing", draftId: "draft" });
305+
expect(state.draftTexts.get("draft")).toBe("Fix the flaky test");
306+
});
307+
});

‎apps/mobile/src/features/projects/AddProjectScreen.tsx‎

Lines changed: 54 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -40,6 +40,7 @@ import {
4040
} from "@t3tools/client-runtime/state/filesystem";
4141
import {
4242
appendBrowsePathSegment,
43+
ensureBrowseDirectoryPath,
4344
inferProjectTitleFromPath,
4445
isWindowsPlatform,
4546
} from "@t3tools/client-runtime/state/projects";
@@ -687,10 +688,55 @@ async function draftWithPrompt(
687688
return draftId;
688689
}
689690

691+
// Adding a folder the environment already tracks should behave like picking
692+
// that project from the list. Stored workspace roots are absolute, so a `~`
693+
// path is first expanded by the environment: browsing a directory reports it
694+
// back with home resolved the same way project creation resolves it.
695+
function useOpenExistingProject(environment: EnvironmentOption | null) {
696+
const navigation = useNavigation();
697+
const projects = useProjects();
698+
const loadBrowsePath = useAtomQueryRunner(filesystemEnvironment.browse, {
699+
reportFailure: false,
700+
reportDefect: false,
701+
});
702+
703+
return async (path: string, prompt?: string | null): Promise<boolean> => {
704+
if (!environment) return false;
705+
let workspaceRoot = path;
706+
if (path.startsWith("~")) {
707+
const browseResult = await loadBrowsePath({
708+
environmentId: environment.environmentId,
709+
input: { partialPath: ensureBrowseDirectoryPath(path) },
710+
});
711+
// A folder that cannot be browsed is not an existing project's root.
712+
if (!AsyncResult.isSuccess(browseResult)) return false;
713+
workspaceRoot = browseResult.value.parentPath;
714+
}
715+
const existing = findExistingAddProject({
716+
projects,
717+
environmentId: environment.environmentId,
718+
path: workspaceRoot,
719+
});
720+
if (!existing) return false;
721+
openNewTaskDraft(navigation, {
722+
environmentId: existing.environmentId,
723+
projectId: existing.id,
724+
title: existing.title,
725+
...(prompt
726+
? await draftWithPrompt(existing.environmentId, existing.id, prompt).then(
727+
(draftId) => ({ draftId }),
728+
() => ({}),
729+
)
730+
: {}),
731+
});
732+
return true;
733+
};
734+
}
735+
690736
function useCreateProject(environment: EnvironmentOption | null) {
691737
const navigation = useNavigation();
692738
const createProject = useAtomCommand(projectEnvironment.create, { reportFailure: false });
693-
const projects = useProjects();
739+
const openExistingProject = useOpenExistingProject(environment);
694740

695741
return async (workspaceRoot: string) => {
696742
if (
@@ -705,20 +751,7 @@ function useCreateProject(environment: EnvironmentOption | null) {
705751
return;
706752
}
707753

708-
const existing = findExistingAddProject({
709-
projects,
710-
environmentId: environment.environmentId,
711-
path: workspaceRoot,
712-
});
713-
if (existing) {
714-
Dialog.alert("Project already exists", existing.title);
715-
openNewTaskDraft(navigation, {
716-
environmentId: existing.environmentId,
717-
projectId: existing.id,
718-
title: existing.title,
719-
});
720-
return;
721-
}
754+
if (await openExistingProject(workspaceRoot)) return;
722755

723756
const projectId = ProjectId.make(uuidv4());
724757
const command = buildProjectCreateCommand({
@@ -1283,6 +1316,7 @@ export function AddProjectDestinationScreen(props: {
12831316
);
12841317
const canCloneProject = canWriteSourceControl && canCreateProject;
12851318
const createProject = useCreateProject(environment);
1319+
const openExistingProject = useOpenExistingProject(environment);
12861320
const remoteUrl = stringParam(props.remoteUrl);
12871321
const repositoryTitle = stringParam(props.repositoryTitle);
12881322
const prompt = stringParam(props.prompt);
@@ -1317,6 +1351,11 @@ export function AddProjectDestinationScreen(props: {
13171351
}
13181352

13191353
setIsSubmitting(true);
1354+
// Cloning into a folder that is already a project can only fail.
1355+
if (await openExistingProject(resolved.path, prompt)) {
1356+
setIsSubmitting(false);
1357+
return;
1358+
}
13201359
if (environment.supportsCloneTracking) {
13211360
const projectId = ProjectId.make(uuidv4());
13221361
const title = inferProjectTitleFromPath(resolved.path);

0 commit comments

Comments
 (0)