Open History to see the last commit
1import * as NodeFS from "node:fs";
2import * as NodeFSP from "node:fs/promises";
3import * as NodeOS from "node:os";
4import * as NodePath from "node:path";
5import * as NodeModule from "node:module";
6import type { EnvironmentConnectionPhase } from "@t3tools/client-runtime/connection";
7import { workspaceDetailRouter } from "../layout/workspace/workspace-detail-selection";
8import type { NavigationState } from "@react-navigation/native";
9import {
10 AuthFilesystemReadScope,
11 AuthOrchestrationOperateScope,
12 AuthSourceControlWriteScope,
13} from "@t3tools/contracts";
14import * as Cause from "effect/Cause";
15import { AsyncResult } from "effect/reactivity";
16import { act, createElement, isValidElement, type ReactNode } from "react";
17import { createRoot } from "react-dom/client";
18import { afterEach, beforeEach, describe, expect, it, vi } from "vite-plus/test";
19
20const state = vi.hoisted(() => ({
21 scopes: new Set<string>(),
22 baseDirectory: "",
23 projects: [] as string[],
24 trackedFolders: [] as unknown[],
25 scanResult: null as unknown,
26 existingProjects: [] as {
27 environmentId: string;
28 id: string;
29 title: string;
30 workspaceRoot: string;
31 repositoryIdentity?: { canonicalKey: string };
32 }[],
33 cloneDestinations: [] as string[],
34 createResult: null as Promise<unknown> | null,
35 createSent: null as (() => void) | null,
36 createNewResult: null as Promise<unknown> | null,
37 startCloneResult: null as Promise<unknown> | null,
38 connectionStates: {} as Record<string, EnvironmentConnectionPhase>,
39 newProjectsRoot: null as string | null,
40 waitForProject: vi.fn(),
41 dispatch: vi.fn(),
42 alert: vi.fn(),
43 navigationState: undefined as NavigationState | undefined,
44 environments: [{ environmentId: "environment", environmentLabel: "Environment" }],
45}));
46
47function loadRouters() {
48 const requireNavigation = NodeModule.createRequire(
49 NodeModule.createRequire(import.meta.url).resolve("@react-navigation/native/package.json"),
50 );
51 return requireNavigation("@react-navigation/routers") as {
52 StackRouter: typeof import("@react-navigation/native").StackRouter;
53 StackActions: typeof import("@react-navigation/native").StackActions;
54 CommonActions: typeof import("@react-navigation/native").CommonActions;
55 };
56}
57
58vi.mock("../layout/workspace/useSelectWorkspaceDetail", async () => {
59 const { selectWorkspaceDetail } = await import("../layout/workspace/workspace-detail-selection");
60 return {
61 useSelectWorkspaceDetail: () => (detail: Parameters<typeof selectWorkspaceDetail>[0]) =>
62 state.dispatch(selectWorkspaceDetail(detail)),
63 };
64});
65vi.mock("../../native/StackHeader", () => ({
66 nativeHeaderScrollEdgeEffects: () => undefined,
67}));
68vi.mock("../../components/ui/NavigationRow", () => ({ NavigationRow: "NavigationRow" }));
69vi.mock("../../components/ui/Button", () => ({ Button: "Button" }));
70vi.mock("../../components/ui/ScreenScrollView", () => ({ ScreenScrollView: "ScrollView" }));
71vi.mock("../settings/components/SettingsScreen", () => ({ SettingsScreen: "SettingsScreen" }));
72vi.mock("../../components/ui/ThemedSwitch", () => ({ ThemedSwitch: "Switch" }));
73vi.mock("react-native", () => ({
74 Platform: { OS: "ios" },
75 ActivityIndicator: "ActivityIndicator",
76 Alert: { alert: state.alert },
77 Pressable: "Pressable",
78 ScrollView: "ScrollView",
79 View: "View",
80}));
81vi.mock("@react-navigation/native", () => ({
82 useNavigation: () => ({
83 dispatch: state.dispatch,
84 getState: () =>
85 state.navigationState ?? {
86 index: 4,
87 routes: [
88 { key: "home", name: "Home" },
89 { key: "draft", name: "Thread", params: { draft: {} } },
90 { key: "picker", name: "NewTaskProject" },
91 { key: "add", name: "AddProject" },
92 { key: "local", name: "AddProjectLocal" },
93 ],
94 },
95 }),
96 CommonActions: { reset: (input: unknown) => input },
97 StackActions: {
98 push: (name: string, params: unknown) => ({ type: "PUSH", payload: { name, params } }),
99 },
100}));
101vi.mock("react-native-safe-area-context", () => ({
102 useSafeAreaInsets: () => ({ bottom: 0 }),
103}));
104vi.mock("../../components/ui/AppSymbol", () => ({ SymbolView: "SymbolView" }));
105vi.mock("../../components/ui/AppText", () => ({ AppText: "Text", AppTextInput: "TextInput" }));
106vi.mock("../../components/EnvironmentMachineSymbol", () => ({
107 EnvironmentMachineSymbol: "EnvironmentMachineSymbol",
108}));
109vi.mock("../../components/ui/ErrorBanner", () => ({ ErrorBanner: "ErrorBanner" }));
110vi.mock("./SourceControlIcon", () => ({ SourceControlIcon: "SourceControlIcon" }));
111vi.mock("../../lib/uuid", () => ({ uuidv4: () => "project" }));
112vi.mock("../../state/session", () => ({
113 useEnvironmentScope: (_environmentId: string, scope: string) => state.scopes.has(scope),
114 readEnvironmentScope: (_environmentId: string, scope: string) => state.scopes.has(scope),
115}));
116vi.mock("../../state/entities", () => ({
117 useProjects: () => state.existingProjects,
118 waitForProject: state.waitForProject,
119 useServerConfigs: () =>
120 new Map([
121 [
122 "environment",
123 {
124 environment: { platform: { os: "linux" }, capabilities: {} },
125 newProjectsRoot: state.newProjectsRoot,
126 settings: { addProjectBaseDirectory: state.baseDirectory },
127 },
128 ],
129 ]),
130}));
131vi.mock("../../state/use-remote-environment-registry", () => ({
132 useRemoteEnvironmentRuntime: () => ({ connectionState: "connected" }),
133 useRemoteConnectionStatus: () => ({
134 connectedEnvironments: state.environments.map((environment) => ({
135 environmentId: environment.environmentId,
136 connectionState: state.connectionStates[environment.environmentId] ?? "connected",
137 })),
138 }),
139 useSavedRemoteConnections: () => ({
140 savedConnectionsById: Object.fromEntries(
141 state.environments.map((environment) => [environment.environmentId, environment]),
142 ),
143 }),
144}));
145vi.mock("../../state/use-atom-command", () => ({ useAtomCommand: (command: unknown) => command }));
146// filesystem.browse of `~` answers with the host's home as its parentPath; a scan answers scanResult.
147vi.mock("../../state/use-atom-query-runner", () => ({
148 useAtomQueryRunner:
149 () =>
150 async ({ input }: { input?: { partialPath?: string; workspaceRoot?: string } }) => {
151 if (input?.partialPath === "~") {
152 return AsyncResult.success({ parentPath: "/home/tester", entries: [] });
153 }
154 if (input?.workspaceRoot === undefined) return undefined;
155 return state.scanResult ?? AsyncResult.failure(Cause.fail(new Error("Scan failed")));
156 },
157}));
158vi.mock("../../state/query", () => ({ useEnvironmentQuery: () => ({ data: null }) }));
159vi.mock("../../state/presentation", () => ({
160 useEnvironmentPresentation: () => ({ isReady: true, presentation: null }),
161}));
162vi.mock("../../state/filesystem", () => ({ filesystemEnvironment: {} }));
163vi.mock("../../state/sourceControl", () => ({
164 sourceControlEnvironment: {
165 discovery: (input: unknown) => input,
166 startProjectClone: async ({ input }: { input: { destinationPath: string } }) => {
167 state.cloneDestinations.push(input.destinationPath);
168 if (state.startCloneResult) return state.startCloneResult;
169 NodeFS.mkdirSync(input.destinationPath);
170 return AsyncResult.success(undefined);
171 },
172 },
173}));
174vi.mock("../../state/projects", () => ({
175 projectEnvironment: {
176 createNew: () => state.createNewResult,
177 create: ({ input }: { input: { workspaceRoot: string; trackedFolders?: unknown } }) => {
178 if (!state.scopes.has(AuthOrchestrationOperateScope)) {
179 return Promise.resolve(
180 AsyncResult.failure(Cause.fail(new Error("Project creation denied"))),
181 );
182 }
183 state.projects.push(input.workspaceRoot);
184 state.trackedFolders.push(input.trackedFolders);
185 state.createSent?.();
186 return state.createResult ?? Promise.resolve(AsyncResult.success(undefined));
187 },
188 },
189}));
190
191vi.mock("../../state/use-composer-drafts", () => ({
192 waitForComposerDraftsLoaded: async () => {},
193 createNewTaskDraft: () => "prompt-draft",
194 setComposerDraftText: () => {},
195}));
196
197import {
198 AddProjectNewScreen,
199 AddProjectDestinationScreen,
200 AddProjectLocalFolderScreen,
201 AddProjectSourceScreen,
202} from "./AddProjectScreen";
203import { AddProjectSourceRoute } from "./AddProjectSourceRoute";
204
205function findAction(
206 node: ReactNode,
207 label: string,
208 includeDisabled = false,
209): (() => unknown) | null {
210 if (Array.isArray(node)) {
211 for (const child of node) {
212 const action = findAction(child, label, includeDisabled);
213 if (action) return action;
214 }
215 return null;
216 }
217 if (
218 !isValidElement<{
219 label?: string;
220 title?: string;
221 onPress?: () => unknown;
222 disabled?: boolean;
223 children?: ReactNode;
224 }>(node)
225 ) {
226 return null;
227 }
228 if ((node.props.label ?? node.props.title) === label) {
229 return node.props.disabled && !includeDisabled ? null : (node.props.onPress ?? null);
230 }
231 return findAction(node.props.children, label, includeDisabled);
232}
233
234const mountedRoots: ReturnType<typeof createRoot>[] = [];
235afterEach(() => {
236 for (const root of mountedRoots.splice(0)) act(() => root.unmount());
237});
238function renderScreen(render: () => ReactNode) {
239 (globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true;
240 const root = createRoot(document.createElement("div"));
241 mountedRoots.push(root);
242 let screen: ReactNode;
243 function Observer() {
244 screen = render();
245 return null;
246 }
247 act(() => root.render(createElement(Observer)));
248 return screen;
249}
250
251function cloneAction() {
252 const action = findAction(
253 renderScreen(() =>
254 AddProjectDestinationScreen({
255 environmentId: "environment",
256 remoteUrl: "https://example.com/owner/repo.git",
257 repositoryName: "repo",
258 }),
259 ),
260 "Clone project",
261 true,
262 );
263 if (!action) throw new Error("Clone action missing");
264 return action;
265}
266
267describe("clone project permissions", () => {
268 beforeEach(async () => {
269 state.baseDirectory = await NodeFSP.mkdtemp(
270 NodePath.join(NodeOS.tmpdir(), "t3-clone-permissions-"),
271 );
272 state.scopes = new Set([AuthSourceControlWriteScope]);
273 state.projects = [];
274 state.createResult = null;
275 });
276
277 afterEach(async () => {
278 await NodeFSP.rm(state.baseDirectory, { recursive: true, force: true });
279 });
280
281 it("does not leave a clone on disk when project creation is denied", async () => {
282 await cloneAction()();
283
284 expect(NodeFS.existsSync(NodePath.join(state.baseDirectory, "repo"))).toBe(false);
285 expect(state.projects).toEqual([]);
286 });
287
288 it.each([AuthSourceControlWriteScope, AuthOrchestrationOperateScope])(
289 "rechecks %s before a retained clone action creates a directory",
290 async (scope) => {
291 state.scopes.add(AuthOrchestrationOperateScope);
292 const submit = cloneAction();
293 state.scopes.delete(scope);
294 await submit();
295
296 expect(NodeFS.existsSync(NodePath.join(state.baseDirectory, "repo"))).toBe(false);
297 expect(state.projects).toEqual([]);
298 },
299 );
300
301 it.each([
302 [
303 "opens the existing project of that repository instead of cloning into its folder",
304 "example.com/owner/repo",
305 false,
306 ],
307 ["leaves a folder holding another repository to the clone", "example.com/owner/other", true],
308 ])("%s", async (_name, canonicalKey, clones) => {
309 state.scopes.add(AuthOrchestrationOperateScope);
310 state.cloneDestinations = [];
311 state.startCloneResult = Promise.resolve(
312 AsyncResult.failure(Cause.fail(new Error("Destination is not empty"))),
313 );
314 state.existingProjects = [
315 {
316 environmentId: "environment",
317 id: "existing",
318 title: "repo",
319 workspaceRoot: NodePath.join(state.baseDirectory, "repo"),
320 repositoryIdentity: { canonicalKey },
321 },
322 ];
323 try {
324 await cloneAction()();
325
326 expect(state.cloneDestinations.length > 0).toBe(clones);
327 } finally {
328 state.existingProjects = [];
329 state.startCloneResult = null;
330 }
331 });
332});
333
334function mountProjectFlow(
335 withDraft: boolean,
336 withChooser = true,
337 withPullRequest = false,
338 screenName = "AddProjectLocal",
339) {
340 const { StackRouter, StackActions, CommonActions } = loadRouters();
341 const base = StackRouter({});
342 const router = { ...base, ...workspaceDetailRouter(base) };
343 const options = {
344 routeNames: [
345 "Home",
346 "Thread",
347 "PullRequest",
348 "PullRequestFile",
349 "NewTaskProject",
350 "AddProject",
351 "AddProjectLocal",
352 "AddProjectNew",
353 "AddProjectDestination",
354 ],
355 routeParamList: {},
356 routeGetIdList: {},
357 };
358 let current = router.getInitialState(options);
359 const home = current.routes[0]!;
360 const apply = (action: Parameters<typeof router.getStateForAction>[1]) => {
361 const next = router.getStateForAction(current, action, options);
362 if (!next || next.stale !== false) throw new Error("Navigation action rejected");
363 current = next;
364 state.navigationState = current;
365 };
366 if (withPullRequest) {
367 apply(StackActions.push("PullRequest", { number: 123 }));
368 apply(StackActions.push("PullRequestFile", { path: "file.ts" }));
369 }
370 const underlyingRoutes = current.routes;
371 if (withDraft) {
372 apply(StackActions.push("Thread", { draft: { projectId: "previous-project" } }));
373 }
374 const draftKey = withDraft ? current.routes[current.index]!.key : null;
375 for (const name of [...(withChooser ? ["NewTaskProject"] : []), "AddProject", screenName]) {
376 apply(StackActions.push(name));
377 }
378 state.navigationState = current;
379 state.dispatch.mockImplementation((action) =>
380 apply(
381 action.type === "PUSH" || action.type === "SELECT_WORKSPACE_DETAIL"
382 ? action
383 : CommonActions.reset(action),
384 ),
385 );
386 return {
387 home,
388 draftKey,
389 underlyingRoutes,
390 flowRoutes: current.routes.slice(underlyingRoutes.length),
391 getState: () => current,
392 back: () => apply(StackActions.pop()),
393 setParams: (params: object) => apply(CommonActions.setParams(params)),
394 push: (name: string) => apply(StackActions.push(name)),
395 };
396}
397
398describe("add project source environment", () => {
399 it("blocks local add on a requested unavailable host until reconnect or manual choice", async () => {
400 state.scopes = new Set([AuthOrchestrationOperateScope]);
401 state.dispatch.mockReset();
402 state.environments = [
403 { environmentId: "environment", environmentLabel: "Environment" },
404 { environmentId: "another-environment", environmentLabel: "Another environment" },
405 ];
406 (globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true;
407 const root = createRoot(document.createElement("div"));
408 let screen: ReactNode;
409 function SourceObserver() {
410 screen = AddProjectSourceScreen({ environmentId: "environment" });
411 return null;
412 }
413 try {
414 for (const phase of ["available", "offline", "error"] as const) {
415 state.connectionStates = { environment: phase };
416 await act(() => root.render(createElement(SourceObserver)));
417 expect(findAction(screen, "Local folder")).toBeNull();
418 expect(state.dispatch).not.toHaveBeenCalled();
419 }
420 state.connectionStates = {};
421 await act(() => root.render(createElement(SourceObserver)));
422 const reconnectedLocal = findAction(screen, "Local folder");
423 if (!reconnectedLocal) throw new Error("Reconnected local folder action missing");
424 reconnectedLocal();
425 expect(state.dispatch).toHaveBeenLastCalledWith({
426 type: "PUSH",
427 payload: { name: "AddProjectLocal", params: { environmentId: "environment" } },
428 });
429 state.connectionStates = { environment: "offline" };
430 await act(() => root.render(createElement(SourceObserver)));
431 expect(findAction(screen, "Local folder")).toBeNull();
432 const select = findAction(screen, "Another environment");
433 if (!select) throw new Error("Connected environment selection missing");
434 await act(() => select());
435 const local = findAction(screen, "Local folder");
436 if (!local) throw new Error("Manually selected local folder action missing");
437 local();
438 expect(state.dispatch).toHaveBeenLastCalledWith({
439 type: "PUSH",
440 payload: { name: "AddProjectLocal", params: { environmentId: "another-environment" } },
441 });
442 } finally {
443 await act(() => root.unmount());
444 state.connectionStates = {};
445 state.environments = [{ environmentId: "environment", environmentLabel: "Environment" }];
446 }
447 });
448
449 it("keeps a manual host selection when the requested host finishes connecting", async () => {
450 state.scopes = new Set([AuthOrchestrationOperateScope]);
451 state.dispatch.mockReset();
452 const navigation = mountProjectFlow(false, true, false, "AddProject");
453 state.environments = [
454 { environmentId: "environment", environmentLabel: "Environment" },
455 { environmentId: "another-environment", environmentLabel: "Another environment" },
456 ];
457 state.connectionStates = { environment: "connecting" };
458 (globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true;
459 const root = createRoot(document.createElement("div"));
460 let screen: ReactNode;
461 function SourceObserver() {
462 screen = AddProjectSourceScreen({ environmentId: "environment" });
463 return null;
464 }
465 try {
466 await act(() => root.render(createElement(SourceObserver)));
467 expect(findAction(screen, "Local folder")).toBeNull();
468 expect(navigation.getState().routes.at(-1)?.name).toBe("AddProject");
469 const select = findAction(screen, "Another environment");
470 if (!select) throw new Error("Connected environment selection missing");
471 await act(() => select());
472 state.connectionStates = {};
473 await act(() => root.render(createElement(SourceObserver)));
474 const local = findAction(screen, "Local folder");
475 if (!local) throw new Error("Local folder action missing");
476 local();
477 expect(navigation.getState().routes.at(-1)).toMatchObject({
478 name: "AddProjectLocal",
479 params: { environmentId: "another-environment" },
480 });
481 } finally {
482 await act(() => root.unmount());
483 state.connectionStates = {};
484 state.environments = [{ environmentId: "environment", environmentLabel: "Environment" }];
485 }
486 });
487
488 it("follows warm environment requests while preserving manual selection between requests", async () => {
489 state.scopes = new Set([AuthOrchestrationOperateScope]);
490 state.dispatch.mockReset();
491 const navigation = mountProjectFlow(false, true, false, "AddProject");
492 state.environments = [
493 { environmentId: "environment", environmentLabel: "Environment" },
494 { environmentId: "another-environment", environmentLabel: "Another environment" },
495 ];
496 (globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true;
497 const root = createRoot(document.createElement("div"));
498 let actions: { local: () => unknown; selectEnvironment: () => unknown } | undefined;
499 function SourceRouteObserver(props: { environmentId?: string | string[] }) {
500 const route = AddProjectSourceRoute({ route: { params: props } });
501 const screen = AddProjectSourceScreen(route.props);
502 const local = findAction(screen, "Local folder");
503 const selectEnvironment = findAction(screen, "Environment");
504 if (!local || !selectEnvironment) throw new Error("Source actions missing");
505 actions = { local, selectEnvironment };
506 return null;
507 }
508 const openLocalFolder = (environmentId: string) => {
509 state.dispatch.mockClear();
510 actions!.local();
511 expect(navigation.getState().routes.at(-1)).toMatchObject({
512 name: "AddProjectLocal",
513 params: { environmentId },
514 });
515 navigation.back();
516 };
517 try {
518 await act(() =>
519 root.render(createElement(SourceRouteObserver, { environmentId: "environment" })),
520 );
521 openLocalFolder("environment");
522 await act(() =>
523 root.render(createElement(SourceRouteObserver, { environmentId: "another-environment" })),
524 );
525 openLocalFolder("another-environment");
526 await act(() => actions!.selectEnvironment());
527 await act(() =>
528 root.render(createElement(SourceRouteObserver, { environmentId: ["another-environment"] })),
529 );
530 openLocalFolder("environment");
531 await act(() =>
532 root.render(createElement(SourceRouteObserver, { environmentId: "environment" })),
533 );
534 await act(() =>
535 root.render(createElement(SourceRouteObserver, { environmentId: "another-environment" })),
536 );
537 openLocalFolder("another-environment");
538 } finally {
539 await act(() => root.unmount());
540 state.environments = [{ environmentId: "environment", environmentLabel: "Environment" }];
541 }
542 });
543});
544
545describe("local project navigation", () => {
546 function setup(baseDirectory = "/tmp/t3-mobile-audit-fixture") {
547 state.navigationState = undefined;
548 state.scopes = new Set([AuthOrchestrationOperateScope]);
549 state.baseDirectory = baseDirectory;
550 state.projects = [];
551 state.trackedFolders = [];
552 state.scanResult = null;
553 state.dispatch.mockReset();
554 state.alert.mockReset();
555 state.waitForProject.mockReset();
556 const created = Promise.withResolvers<ReturnType<typeof AsyncResult.success<void>>>();
557 const projected = Promise.withResolvers<unknown>();
558 const sent = Promise.withResolvers<void>();
559 state.createResult = created.promise;
560 state.createSent = sent.resolve;
561 state.waitForProject.mockReturnValue(projected.promise);
562 const submit = findAction(
563 renderScreen(() => AddProjectLocalFolderScreen({ environmentId: "environment" })),
564 "Add project",
565 );
566 if (!submit) throw new Error("Add project action missing");
567 return { created, projected, sent: sent.promise, submit };
568 }
569
570 it("keeps navigation in place and explains a project projection timeout", async () => {
571 const { created, projected, submit } = setup();
572 const submission = submit();
573 created.resolve(AsyncResult.success(undefined));
574 projected.resolve(null);
575 await submission;
576
577 expect(state.projects).toEqual(["/tmp/t3-mobile-audit-fixture"]);
578 expect(state.dispatch).not.toHaveBeenCalled();
579 expect(state.alert).toHaveBeenCalledExactlyOnceWith(
580 "Project added",
581 "The project was created but has not reached this device yet. It will appear in the project list once the connection catches up.",
582 );
583 });
584
585 it("opens an existing project typed as a home-relative path instead of creating it", async () => {
586 state.existingProjects = [
587 {
588 environmentId: "environment",
589 id: "existing",
590 title: "bike-documents",
591 workspaceRoot: "/home/tester/projects/bike-documents",
592 },
593 ];
594 try {
595 const { created, projected, submit } = setup("~/projects/bike-documents/");
596 state.scopes.add(AuthFilesystemReadScope);
597 created.resolve(AsyncResult.success(undefined));
598 projected.resolve(null);
599 await submit();
600
601 expect(state.projects).toEqual([]);
602 } finally {
603 state.existingProjects = [];
604 }
605 });
606
607 it("offers the repositories a scan finds before adding the project", async () => {
608 const { created, projected } = setup();
609 state.scanResult = AsyncResult.success({
610 workspaceRoot: "/tmp/t3-mobile-audit-fixture",
611 isGitRepository: false,
612 codeWorkspaceFile: null,
613 folders: ["api", "web"].map((name) => ({
614 path: `/tmp/t3-mobile-audit-fixture/${name}`,
615 name,
616 isGitRepository: true,
617 source: "child",
618 })),
619 });
620 created.resolve(AsyncResult.success(undefined));
621 projected.resolve(null);
622 const root = createRoot(document.createElement("div"));
623 mountedRoots.push(root);
624 let screen: ReactNode;
625 function Observer() {
626 screen = AddProjectLocalFolderScreen({ environmentId: "environment" });
627 return null;
628 }
629 await act(() => root.render(createElement(Observer)));
630 await act(() => findAction(screen, "Add project")?.());
631
632 state.scanResult = null;
633
634 expect(state.projects).toEqual([]);
635 await act(() => findAction(screen, "Add with 2 repositories")?.());
636
637 expect(state.projects).toEqual(["/tmp/t3-mobile-audit-fixture"]);
638 expect(state.trackedFolders).toEqual([
639 [
640 { path: "/tmp/t3-mobile-audit-fixture/api", name: "api" },
641 { path: "/tmp/t3-mobile-audit-fixture/web", name: "web" },
642 ],
643 ]);
644 });
645
646 it("does not replace a reopened flow when the previous submission finishes", async () => {
647 const { created, projected, submit } = setup();
648 const navigation = mountProjectFlow(false);
649 const submission = submit();
650 created.resolve(AsyncResult.success(undefined));
651 await created.promise;
652 navigation.back();
653 navigation.push("AddProjectLocal");
654 const remaining = navigation.getState();
655 projected.resolve({ environmentId: "environment", id: "project" });
656 await submission;
657
658 expect(state.projects).toEqual(["/tmp/t3-mobile-audit-fixture"]);
659 expect(navigation.getState()).toEqual(remaining);
660 expect(state.dispatch).not.toHaveBeenCalled();
661 });
662
663 it("does not replace a warm-linked flow sharing the original route key", async () => {
664 const { created, projected, submit } = setup();
665 const navigation = mountProjectFlow(false);
666 const submission = submit();
667 created.resolve(AsyncResult.success(undefined));
668 await created.promise;
669 const originalKey = navigation.getState().routes.at(-1)!.key;
670 navigation.setParams({ environmentId: "other-environment" });
671 const remaining = navigation.getState();
672 expect(remaining.routes.at(-1)!.key).toBe(originalKey);
673 projected.resolve({ environmentId: "environment", id: "project" });
674 await submission;
675
676 expect(navigation.getState()).toEqual(remaining);
677 expect(state.dispatch).not.toHaveBeenCalled();
678 });
679
680 it("does not redirect a reopened flow when an earlier new project finishes", async () => {
681 const { projected } = setup();
682 state.newProjectsRoot = "/projects";
683 const created = Promise.withResolvers<unknown>();
684 const waitingForProject = Promise.withResolvers<void>();
685 state.createNewResult = created.promise;
686 state.waitForProject.mockImplementation(() => {
687 waitingForProject.resolve();
688 return projected.promise;
689 });
690 const navigation = mountProjectFlow(false, true, true, "AddProjectNew");
691 (globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true;
692 const root = createRoot(document.createElement("div"));
693 let screen: ReactNode;
694 function NewProjectObserver() {
695 screen = AddProjectNewScreen({ environmentId: "environment" });
696 return null;
697 }
698 function enterName(node: ReactNode): boolean {
699 if (Array.isArray(node)) return node.some(enterName);
700 if (
701 !isValidElement<{
702 placeholder?: string;
703 onChangeText?: (text: string) => void;
704 children?: ReactNode;
705 }>(node)
706 )
707 return false;
708 if (node.props.placeholder === "Project name") {
709 node.props.onChangeText!("new-project");
710 return true;
711 }
712 return enterName(node.props.children);
713 }
714 try {
715 await act(() => root.render(createElement(NewProjectObserver)));
716 await act(() => {
717 expect(enterName(screen)).toBe(true);
718 });
719 const submit = findAction(screen, "Create project");
720 if (!submit) throw new Error("Create project action missing");
721 await act(async () => {
722 submit();
723 created.resolve(
724 AsyncResult.success({
725 projectId: "project",
726 workspaceRoot: "/projects/new-project",
727 }),
728 );
729 await waitingForProject.promise;
730 });
731 navigation.back();
732 navigation.push("AddProjectNew");
733 const remaining = navigation.getState();
734 await act(async () => {
735 projected.resolve({ environmentId: "environment", id: "project" });
736 await projected.promise;
737 });
738
739 expect(navigation.getState()).toEqual(remaining);
740 expect(state.dispatch).not.toHaveBeenCalled();
741 } finally {
742 await act(() => root.unmount());
743 state.newProjectsRoot = null;
744 state.createNewResult = null;
745 }
746 });
747
748 it.each([
749 { origin: "Thread", withDraft: true, withChooser: true },
750 { origin: "NewTaskProject", withDraft: false, withChooser: true },
751 { origin: "AddProject", withDraft: false, withChooser: false },
752 ])(
753 "waits for projection then selects the draft from $origin",
754 async ({ withDraft, withChooser }) => {
755 const { created, projected, sent, submit } = setup();
756 const navigation = mountProjectFlow(withDraft, withChooser, true);
757 const before = navigation.getState();
758 const submission = submit();
759 created.resolve(AsyncResult.success(undefined));
760 await sent;
761 expect(state.projects).toEqual(["/tmp/t3-mobile-audit-fixture"]);
762 expect(navigation.getState()).toBe(before);
763 projected.resolve({ environmentId: "environment", id: "project" });
764 await submission;
765 expect(state.dispatch).toHaveBeenCalledTimes(1);
766 expect(navigation.getState().routes.map((route) => route.name)).toEqual(["Home", "Thread"]);
767 expect(navigation.getState().routes[1]?.params).toEqual({
768 draft: {
769 environmentId: "environment",
770 projectId: "project",
771 title: "t3-mobile-audit-fixture",
772 },
773 });
774 navigation.back();
775 expect(navigation.getState().routes).toEqual([navigation.home]);
776 },
777 );
778});
779
780describe("local folder path", () => {
781 function findPathInput(
782 node: ReactNode,
783 ): { value: string; onChangeText: (value: string) => void } | null {
784 if (Array.isArray(node)) {
785 for (const child of node) {
786 const input = findPathInput(child);
787 if (input) return input;
788 }
789 return null;
790 }
791 if (
792 !isValidElement<{
793 value?: string;
794 onChangeText?: (value: string) => void;
795 onSubmit?: () => void;
796 children?: ReactNode;
797 }>(node)
798 ) {
799 return null;
800 }
801 const { value, onChangeText, onSubmit } = node.props;
802 if (typeof value === "string" && onChangeText && onSubmit) return { value, onChangeText };
803 return findPathInput(node.props.children);
804 }
805
806 function mountLocalFolder() {
807 state.scopes = new Set([AuthOrchestrationOperateScope]);
808 state.baseDirectory = "/work";
809 state.connectionStates = {};
810 state.environments = [
811 { environmentId: "environment", environmentLabel: "Environment" },
812 { environmentId: "another-environment", environmentLabel: "Another environment" },
813 ];
814 (globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true;
815 const root = createRoot(document.createElement("div"));
816 const renderedPaths: string[] = [];
817 let input: ReturnType<typeof findPathInput> = null;
818 function LocalFolderObserver(props: { environmentId?: string }) {
819 input = findPathInput(AddProjectLocalFolderScreen(props));
820 if (input) renderedPaths.push(input.value);
821 return null;
822 }
823 return {
824 renderedPaths,
825 get path() {
826 return input?.value;
827 },
828 type: (value: string) => act(() => input!.onChangeText(value)),
829 render: (environmentId?: string) =>
830 act(() => root.render(createElement(LocalFolderObserver, { environmentId }))),
831 [Symbol.asyncDispose]: async () => {
832 await act(() => root.unmount());
833 state.connectionStates = {};
834 state.environments = [{ environmentId: "environment", environmentLabel: "Environment" }];
835 },
836 };
837 }
838
839 it("shows the new host's default path on the first render after the host changes", async () => {
840 await using screen = mountLocalFolder();
841 await screen.render("environment");
842 await screen.type("/work/edited");
843 screen.renderedPaths.length = 0;
844
845 await screen.render("another-environment");
846
847 expect(screen.renderedPaths).not.toContain("/work/edited");
848 expect(screen.path).toBe("~/");
849 });
850
851 it("keeps each host's typed path when switching between hosts", async () => {
852 await using screen = mountLocalFolder();
853 await screen.render("environment");
854 await screen.type("/work/a");
855 await screen.render("another-environment");
856 await screen.type("~/b");
857
858 await screen.render("environment");
859 expect(screen.path).toBe("/work/a");
860 await screen.render("another-environment");
861 expect(screen.path).toBe("~/b");
862 });
863
864 it("keeps a typed path when the default host drops out and comes back", async () => {
865 await using screen = mountLocalFolder();
866 await screen.render();
867 expect(screen.path).toBe("~/");
868 await screen.type("~/code/app");
869
870 state.connectionStates = { "another-environment": "offline" };
871 await screen.render();
872 expect(screen.path).toBe("/work/");
873
874 state.connectionStates = {};
875 await screen.render();
876 expect(screen.path).toBe("~/code/app");
877 });
878});