Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

AddProjectScreen.test.ts

945 lines35.1 KB

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