Skip to content

Commit d2d7d62

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

2 files changed

Lines changed: 190 additions & 34 deletions

File tree

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

Lines changed: 136 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,7 @@ vi.mock("react-native", () => ({
3652
View: "View",
3753
}));
3854
vi.mock("@react-navigation/native", () => ({
39-
useNavigation: () => ({ dispatch: () => {} }),
55+
useNavigation: () => ({ dispatch: (action: unknown) => state.navigations.push(action) }),
4056
CommonActions: { reset: (input: unknown) => input },
4157
StackActions: {},
4258
}));
@@ -56,13 +72,17 @@ vi.mock("../../state/session", () => ({
5672
readEnvironmentScope: (_environmentId: string, scope: string) => state.scopes.has(scope),
5773
}));
5874
vi.mock("../../state/entities", () => ({
59-
useProjects: () => [],
75+
useProjects: () => state.existingProjects,
76+
waitForProject: async () => ({}),
6077
useServerConfigs: () =>
6178
new Map([
6279
[
6380
"environment",
6481
{
65-
environment: { platform: { os: "linux" }, capabilities: {} },
82+
environment: {
83+
platform: { os: "linux" },
84+
capabilities: { projectCloneTracking: state.cloneTracking },
85+
},
6686
settings: { addProjectBaseDirectory: state.baseDirectory },
6787
},
6888
],
@@ -80,17 +100,32 @@ vi.mock("../../state/use-remote-environment-registry", () => ({
80100
}),
81101
}));
82102
vi.mock("../../state/use-atom-command", () => ({ useAtomCommand: (command: unknown) => command }));
83-
vi.mock("../../state/use-atom-query-runner", () => ({ useAtomQueryRunner: () => () => {} }));
103+
vi.mock("../../state/use-atom-query-runner", () => ({
104+
useAtomQueryRunner:
105+
(query: unknown) =>
106+
async ({ input }: { input: { partialPath: string } }) => {
107+
if (query !== "browse") return undefined;
108+
const directory = expandHome(input.partialPath);
109+
return NodeFS.existsSync(directory)
110+
? AsyncResult.success({ parentPath: NodePath.resolve(directory), entries: [] })
111+
: AsyncResult.failure(Cause.fail(new Error("read_directory_failed")));
112+
},
113+
}));
84114
vi.mock("../../state/query", () => ({ useEnvironmentQuery: () => ({ data: null }) }));
85115
vi.mock("../../state/presentation", () => ({
86116
useEnvironmentPresentation: () => ({ isReady: true, presentation: null }),
87117
}));
88-
vi.mock("../../state/filesystem", () => ({ filesystemEnvironment: {} }));
118+
vi.mock("../../state/filesystem", () => ({ filesystemEnvironment: { browse: "browse" } }));
89119
vi.mock("../../state/sourceControl", () => ({
90120
sourceControlEnvironment: {
91121
cloneRepository: async ({ input }: { input: { destinationPath: string } }) => {
92-
NodeFS.mkdirSync(input.destinationPath);
93-
return AsyncResult.success({ cwd: input.destinationPath });
122+
const cwd = expandHome(input.destinationPath);
123+
NodeFS.mkdirSync(cwd);
124+
return AsyncResult.success({ cwd });
125+
},
126+
startProjectClone: async ({ input }: { input: { destinationPath: string } }) => {
127+
state.startedClones.push(input.destinationPath);
128+
return AsyncResult.success(undefined);
94129
},
95130
},
96131
}));
@@ -106,7 +141,13 @@ vi.mock("../../state/projects", () => ({
106141
},
107142
}));
108143

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

111152
function findAction(node: ReactNode, label: string): (() => unknown) | null {
112153
if (Array.isArray(node)) {
@@ -123,12 +164,13 @@ function findAction(node: ReactNode, label: string): (() => unknown) | null {
123164
return findAction(node.props.children, label);
124165
}
125166

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

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

Lines changed: 54 additions & 25 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";
@@ -673,10 +674,55 @@ async function draftWithPrompt(
673674
return draftId;
674675
}
675676

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

681727
return async (workspaceRoot: string) => {
682728
if (
@@ -691,30 +737,7 @@ function useCreateProject(environment: EnvironmentOption | null) {
691737
return;
692738
}
693739

694-
const existing = findExistingAddProject({
695-
projects,
696-
environmentId: environment.environmentId,
697-
path: workspaceRoot,
698-
});
699-
if (existing) {
700-
Dialog.alert("Project already exists", existing.title);
701-
navigation.dispatch(
702-
CommonActions.reset({
703-
index: 0,
704-
routes: [
705-
{
706-
name: "NewTaskDraft",
707-
params: {
708-
environmentId: existing.environmentId,
709-
projectId: existing.id,
710-
title: existing.title,
711-
},
712-
},
713-
],
714-
}),
715-
);
716-
return;
717-
}
740+
if (await openExistingProject(workspaceRoot)) return;
718741

719742
const projectId = ProjectId.make(uuidv4());
720743
const command = buildProjectCreateCommand({
@@ -1289,6 +1312,7 @@ export function AddProjectDestinationScreen(props: {
12891312
);
12901313
const canCloneProject = canWriteSourceControl && canCreateProject;
12911314
const createProject = useCreateProject(environment);
1315+
const openExistingProject = useOpenExistingProject(environment);
12921316
const remoteUrl = stringParam(props.remoteUrl);
12931317
const repositoryTitle = stringParam(props.repositoryTitle);
12941318
const prompt = stringParam(props.prompt);
@@ -1323,6 +1347,11 @@ export function AddProjectDestinationScreen(props: {
13231347
}
13241348

13251349
setIsSubmitting(true);
1350+
// Cloning into a folder that is already a project can only fail.
1351+
if (await openExistingProject(resolved.path, prompt)) {
1352+
setIsSubmitting(false);
1353+
return;
1354+
}
13261355
if (environment.supportsCloneTracking) {
13271356
const projectId = ProjectId.make(uuidv4());
13281357
const title = inferProjectTitleFromPath(resolved.path);

0 commit comments

Comments
 (0)