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

AddProjectScreen.test.ts

928 lines34.3 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: "a change to the repository route parameters", changeParams: true },
254 { name: "submitting from a render with stale route parameters", replaceBeforeSubmit: true },
255])(
256 "ignores a pending repository reply after $name",
257 async ({ repeatSubmit, unmount, changeParams, replaceBeforeSubmit }) => {
258 const repository = AsyncResult.success({
259 provider: "github",
260 nameWithOwner: "example/slow",
261 url: "https://github.com/example/slow",
262 sshUrl: "git@github.com:example/slow.git",
263 });
264 const lookup = Promise.withResolvers<typeof repository>();
265 const duplicateLookup = Promise.withResolvers<typeof repository>();
266 state.lookupRepository
267 .mockReset()
268 .mockReturnValueOnce(lookup.promise)
269 .mockReturnValue(duplicateLookup.promise);
270 state.dispatch.mockReset();
271 state.environments = [{ environmentId: "environment", environmentLabel: "Environment" }];
272 state.connectionStates = {};
273 const flow = mountProjectFlow(false, false, false, "AddProjectRepository");
274 flow.setParams({ environmentId: "environment", source: "github" });
275 let screen: ReactNode;
276 function RepositoryScreen() {
277 screen = AddProjectRepositoryScreen({ environmentId: "environment", source: "github" });
278 return null;
279 }
280 function withRepositoryInput(
281 node: ReactNode,
282 action: (input: {
283 onChangeText: (value: string) => void;
284 onSubmitEditing: () => void;
285 }) => void,
286 ): void {
287 Children.forEach(node, (child) => {
288 if (
289 !isValidElement<{
290 children?: ReactNode;
291 onChangeText?: (value: string) => void;
292 onSubmitEditing?: () => void;
293 }>(child)
294 ) {
295 return;
296 }
297 const { onChangeText, onSubmitEditing } = child.props;
298 if (onChangeText && onSubmitEditing) {
299 action({ onChangeText, onSubmitEditing });
300 } else {
301 withRepositoryInput(child.props.children, action);
302 }
303 });
304 }
305 (globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true;
306 const root = createRoot(document.createElement("div"));
307 mountedRoots.push(root);
308 await act(() => root.render(createElement(RepositoryScreen)));
309 await act(() => withRepositoryInput(screen, (input) => input.onChangeText("example/slow")));
310 const submit = findAction(screen, "Lookup repository");
311 if (!submit) throw new Error("Repository lookup action missing");
312 try {
313 if (replaceBeforeSubmit) flow.setParams({ source: "gitlab" });
314 await act(() => {
315 if (repeatSubmit) {
316 withRepositoryInput(screen, (input) => input.onSubmitEditing());
317 }
318 void submit();
319 });
320 if (!replaceBeforeSubmit) {
321 expect(state.lookupRepository).toHaveBeenCalledWith("example/slow");
322 if (changeParams) {
323 flow.setParams({ source: "gitlab" });
324 } else {
325 flow.back();
326 }
327 }
328 if (unmount) await act(() => root.render(null));
329 await act(async () => {
330 lookup.resolve(repository);
331 duplicateLookup.resolve(repository);
332 await lookup.promise;
333 });
334 expect(state.dispatch).not.toHaveBeenCalled();
335 expect(state.lookupRepository).toHaveBeenCalledTimes(replaceBeforeSubmit ? 0 : 1);
336 } finally {
337 state.navigationState = undefined;
338 state.dispatch.mockReset();
339 }
340 },
341);
342​
343function cloneAction() {
344 const action = findAction(
345 renderScreen(() =>
346 AddProjectDestinationScreen({
347 environmentId: "environment",
348 remoteUrl: "https://example.com/owner/repo.git",
349 repositoryName: "repo",
350 }),
351 ),
352 "Clone project",
353 true,
354 );
355 if (!action) throw new Error("Clone action missing");
356 return action;
358​
359describe("clone project permissions", () => {
360 beforeEach(async () => {
361 state.baseDirectory = await NodeFSP.mkdtemp(
362 NodePath.join(NodeOS.tmpdir(), "t3-clone-permissions-"),
363 );
364 state.scopes = new Set([AuthSourceControlWriteScope]);
365 state.projects = [];
366 state.createResult = null;
367 });
368​
369 afterEach(async () => {
370 await NodeFSP.rm(state.baseDirectory, { recursive: true, force: true });
371 });
372​
373 it("does not leave a clone on disk when project creation is denied", async () => {
374 await cloneAction()();
375​
376 expect(NodeFS.existsSync(NodePath.join(state.baseDirectory, "repo"))).toBe(false);
377 expect(state.projects).toEqual([]);
378 });
379​
380 it.each([AuthSourceControlWriteScope, AuthOrchestrationOperateScope])(
381 "rechecks %s before a retained clone action creates a directory",
382 async (scope) => {
383 state.scopes.add(AuthOrchestrationOperateScope);
384 const submit = cloneAction();
385 state.scopes.delete(scope);
386 await submit();
387​
388 expect(NodeFS.existsSync(NodePath.join(state.baseDirectory, "repo"))).toBe(false);
389 expect(state.projects).toEqual([]);
390 },
391 );
392​
393 it.each([
394 [
395 "opens the existing project of that repository instead of cloning into its folder",
396 "example.com/owner/repo",
397 false,
398 ],
399 ["leaves a folder holding another repository to the clone", "example.com/owner/other", true],
400 ])("%s", async (_name, canonicalKey, clones) => {
401 state.scopes.add(AuthOrchestrationOperateScope);
402 state.cloneDestinations = [];
403 state.startCloneResult = Promise.resolve(
404 AsyncResult.failure(Cause.fail(new Error("Destination is not empty"))),
405 );
406 state.existingProjects = [
407 {
408 environmentId: "environment",
409 id: "existing",
410 title: "repo",
411 workspaceRoot: NodePath.join(state.baseDirectory, "repo"),
412 repositoryIdentity: { canonicalKey },
413 },
414 ];
415 try {
416 await cloneAction()();
417​
418 expect(state.cloneDestinations.length > 0).toBe(clones);
419 } finally {
420 state.existingProjects = [];
421 state.startCloneResult = null;
422 }
423 });
424});
425​
426function mountProjectFlow(
427 withDraft: boolean,
428 withChooser = true,
429 withPullRequest = false,
430 screenName = "AddProjectLocal",
431) {
432 const { StackRouter, StackActions, CommonActions } = loadRouters();
433 const base = StackRouter({});
434 const router = { ...base, ...workspaceDetailRouter(base) };
435 const options = {
436 routeNames: [
437 "Home",
438 "Thread",
439 "PullRequest",
440 "PullRequestFile",
441 "NewTaskProject",
442 "AddProject",
443 "AddProjectRepository",
444 "AddProjectLocal",
445 "AddProjectNew",
446 "AddProjectDestination",
447 ],
448 routeParamList: {},
449 routeGetIdList: {},
450 };
451 let current = router.getInitialState(options);
452 const home = current.routes[0]!;
453 const apply = (action: Parameters<typeof router.getStateForAction>[1]) => {
454 const next = router.getStateForAction(current, action, options);
455 if (!next || next.stale !== false) throw new Error("Navigation action rejected");
456 current = next;
457 state.navigationState = current;
458 };
459 if (withPullRequest) {
460 apply(StackActions.push("PullRequest", { number: 123 }));
461 apply(StackActions.push("PullRequestFile", { path: "file.ts" }));
462 }
463 const underlyingRoutes = current.routes;
464 if (withDraft) {
465 apply(StackActions.push("Thread", { draft: { projectId: "previous-project" } }));
466 }
467 const draftKey = withDraft ? current.routes[current.index]!.key : null;
468 for (const name of [...(withChooser ? ["NewTaskProject"] : []), "AddProject", screenName]) {
469 apply(StackActions.push(name));
470 }
471 state.navigationState = current;
472 state.dispatch.mockImplementation((action) =>
473 apply(
474 action.type === "PUSH" || action.type === "SELECT_WORKSPACE_DETAIL"
475 ? action
476 : CommonActions.reset(action),
477 ),
478 );
479 return {
480 home,
481 draftKey,
482 underlyingRoutes,
483 flowRoutes: current.routes.slice(underlyingRoutes.length),
484 getState: () => current,
485 back: () => apply(StackActions.pop()),
486 setParams: (params: object) => apply(CommonActions.setParams(params)),
487 push: (name: string) => apply(StackActions.push(name)),
488 };
490​
491describe("add project source environment", () => {
492 it("blocks local add on a requested unavailable host until reconnect or manual choice", async () => {
493 state.scopes = new Set([AuthOrchestrationOperateScope]);
494 state.dispatch.mockReset();
495 state.environments = [
496 { environmentId: "environment", environmentLabel: "Environment" },
497 { environmentId: "another-environment", environmentLabel: "Another environment" },
498 ];
499 (globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true;
500 const root = createRoot(document.createElement("div"));
501 let screen: ReactNode;
502 function SourceObserver() {
503 screen = AddProjectSourceScreen({ environmentId: "environment" });
504 return null;
505 }
506 try {
507 for (const phase of ["available", "offline", "error"] as const) {
508 state.connectionStates = { environment: phase };
509 await act(() => root.render(createElement(SourceObserver)));
510 expect(findAction(screen, "Local folder")).toBeNull();
511 expect(state.dispatch).not.toHaveBeenCalled();
512 }
513 state.connectionStates = {};
514 await act(() => root.render(createElement(SourceObserver)));
515 const reconnectedLocal = findAction(screen, "Local folder");
516 if (!reconnectedLocal) throw new Error("Reconnected local folder action missing");
517 reconnectedLocal();
518 expect(state.dispatch).toHaveBeenLastCalledWith({
519 type: "PUSH",
520 payload: { name: "AddProjectLocal", params: { environmentId: "environment" } },
521 });
522 state.connectionStates = { environment: "offline" };
523 await act(() => root.render(createElement(SourceObserver)));
524 expect(findAction(screen, "Local folder")).toBeNull();
525 const select = findAction(screen, "Another environment");
526 if (!select) throw new Error("Connected environment selection missing");
527 await act(() => select());
528 const local = findAction(screen, "Local folder");
529 if (!local) throw new Error("Manually selected local folder action missing");
530 local();
531 expect(state.dispatch).toHaveBeenLastCalledWith({
532 type: "PUSH",
533 payload: { name: "AddProjectLocal", params: { environmentId: "another-environment" } },
534 });
535 } finally {
536 await act(() => root.unmount());
537 state.connectionStates = {};
538 state.environments = [{ environmentId: "environment", environmentLabel: "Environment" }];
539 }
540 });
541​
542 it("keeps a manual host selection when the requested host finishes connecting", async () => {
543 state.scopes = new Set([AuthOrchestrationOperateScope]);
544 state.dispatch.mockReset();
545 const navigation = mountProjectFlow(false, true, false, "AddProject");
546 state.environments = [
547 { environmentId: "environment", environmentLabel: "Environment" },
548 { environmentId: "another-environment", environmentLabel: "Another environment" },
549 ];
550 state.connectionStates = { environment: "connecting" };
551 (globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true;
552 const root = createRoot(document.createElement("div"));
553 let screen: ReactNode;
554 function SourceObserver() {
555 screen = AddProjectSourceScreen({ environmentId: "environment" });
556 return null;
557 }
558 try {
559 await act(() => root.render(createElement(SourceObserver)));
560 expect(findAction(screen, "Local folder")).toBeNull();
561 expect(navigation.getState().routes.at(-1)?.name).toBe("AddProject");
562 const select = findAction(screen, "Another environment");
563 if (!select) throw new Error("Connected environment selection missing");
564 await act(() => select());
565 state.connectionStates = {};
566 await act(() => root.render(createElement(SourceObserver)));
567 const local = findAction(screen, "Local folder");
568 if (!local) throw new Error("Local folder action missing");
569 local();
570 expect(navigation.getState().routes.at(-1)).toMatchObject({
571 name: "AddProjectLocal",
572 params: { environmentId: "another-environment" },
573 });
574 } finally {
575 await act(() => root.unmount());
576 state.connectionStates = {};
577 state.environments = [{ environmentId: "environment", environmentLabel: "Environment" }];
578 }
579 });
580​
581 it("follows warm environment requests while preserving manual selection between requests", async () => {
582 state.scopes = new Set([AuthOrchestrationOperateScope]);
583 state.dispatch.mockReset();
584 const navigation = mountProjectFlow(false, true, false, "AddProject");
585 state.environments = [
586 { environmentId: "environment", environmentLabel: "Environment" },
587 { environmentId: "another-environment", environmentLabel: "Another environment" },
588 ];
589 (globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true;
590 const root = createRoot(document.createElement("div"));
591 let actions: { local: () => unknown; selectEnvironment: () => unknown } | undefined;
592 function SourceRouteObserver(props: { environmentId?: string | string[] }) {
593 const route = AddProjectSourceRoute({ route: { params: props } });
594 const screen = AddProjectSourceScreen(route.props);
595 const local = findAction(screen, "Local folder");
596 const selectEnvironment = findAction(screen, "Environment");
597 if (!local || !selectEnvironment) throw new Error("Source actions missing");
598 actions = { local, selectEnvironment };
599 return null;
600 }
601 const openLocalFolder = (environmentId: string) => {
602 state.dispatch.mockClear();
603 actions!.local();
604 expect(navigation.getState().routes.at(-1)).toMatchObject({
605 name: "AddProjectLocal",
606 params: { environmentId },
607 });
608 navigation.back();
609 };
610 try {
611 await act(() =>
612 root.render(createElement(SourceRouteObserver, { environmentId: "environment" })),
613 );
614 openLocalFolder("environment");
615 await act(() =>
616 root.render(createElement(SourceRouteObserver, { environmentId: "another-environment" })),
617 );
618 openLocalFolder("another-environment");
619 await act(() => actions!.selectEnvironment());
620 await act(() =>
621 root.render(createElement(SourceRouteObserver, { environmentId: ["another-environment"] })),
622 );
623 openLocalFolder("environment");
624 await act(() =>
625 root.render(createElement(SourceRouteObserver, { environmentId: "environment" })),
626 );
627 await act(() =>
628 root.render(createElement(SourceRouteObserver, { environmentId: "another-environment" })),
629 );
630 openLocalFolder("another-environment");
631 } finally {
632 await act(() => root.unmount());
633 state.environments = [{ environmentId: "environment", environmentLabel: "Environment" }];
634 }
635 });
636});
637​
638describe("local project navigation", () => {
639 function setup(baseDirectory = "/tmp/t3-mobile-audit-fixture") {
640 state.navigationState = undefined;
641 state.scopes = new Set([AuthOrchestrationOperateScope]);
642 state.baseDirectory = baseDirectory;
643 state.projects = [];
644 state.dispatch.mockReset();
645 state.alert.mockReset();
646 state.waitForProject.mockReset();
647 const created = Promise.withResolvers<ReturnType<typeof AsyncResult.success<void>>>();
648 const projected = Promise.withResolvers<unknown>();
649 state.createResult = created.promise;
650 state.waitForProject.mockReturnValue(projected.promise);
651 const submit = findAction(
652 renderScreen(() => AddProjectLocalFolderScreen({ environmentId: "environment" })),
653 "Add project",
654 );
655 if (!submit) throw new Error("Add project action missing");
656 return { created, projected, submit };
657 }
658​
659 it("keeps navigation in place and explains a project projection timeout", async () => {
660 const { created, projected, submit } = setup();
661 const submission = submit();
662 created.resolve(AsyncResult.success(undefined));
663 projected.resolve(null);
664 await submission;
665​
666 expect(state.projects).toEqual(["/tmp/t3-mobile-audit-fixture"]);
667 expect(state.dispatch).not.toHaveBeenCalled();
668 expect(state.alert).toHaveBeenCalledExactlyOnceWith(
669 "Project added",
670 "The project was created but has not reached this device yet. It will appear in the project list once the connection catches up.",
671 );
672 });
673​
674 it("opens an existing project typed as a home-relative path instead of creating it", async () => {
675 state.existingProjects = [
676 {
677 environmentId: "environment",
678 id: "existing",
679 title: "bike-documents",
680 workspaceRoot: "/home/tester/projects/bike-documents",
681 },
682 ];
683 try {
684 const { created, projected, submit } = setup("~/projects/bike-documents/");
685 state.scopes.add(AuthFilesystemReadScope);
686 created.resolve(AsyncResult.success(undefined));
687 projected.resolve(null);
688 await submit();
689​
690 expect(state.projects).toEqual([]);
691 } finally {
692 state.existingProjects = [];
693 }
694 });
695​
696 it("does not replace a reopened flow when the previous submission finishes", async () => {
697 const { created, projected, submit } = setup();
698 const navigation = mountProjectFlow(false);
699 const submission = submit();
700 created.resolve(AsyncResult.success(undefined));
701 await created.promise;
702 navigation.back();
703 navigation.push("AddProjectLocal");
704 const remaining = navigation.getState();
705 projected.resolve({ environmentId: "environment", id: "project" });
706 await submission;
707​
708 expect(state.projects).toEqual(["/tmp/t3-mobile-audit-fixture"]);
709 expect(navigation.getState()).toEqual(remaining);
710 expect(state.dispatch).not.toHaveBeenCalled();
711 });
712​
713 it("does not replace a warm-linked flow sharing the original route key", 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 const originalKey = navigation.getState().routes.at(-1)!.key;
720 navigation.setParams({ environmentId: "other-environment" });
721 const remaining = navigation.getState();
722 expect(remaining.routes.at(-1)!.key).toBe(originalKey);
723 projected.resolve({ environmentId: "environment", id: "project" });
724 await submission;
725​
726 expect(navigation.getState()).toEqual(remaining);
727 expect(state.dispatch).not.toHaveBeenCalled();
728 });
729​
730 it("does not redirect a reopened flow when an earlier new project finishes", async () => {
731 const { projected } = setup();
732 state.newProjectsRoot = "/projects";
733 const created = Promise.withResolvers<unknown>();
734 const waitingForProject = Promise.withResolvers<void>();
735 state.createNewResult = created.promise;
736 state.waitForProject.mockImplementation(() => {
737 waitingForProject.resolve();
738 return projected.promise;
739 });
740 const navigation = mountProjectFlow(false, true, true, "AddProjectNew");
741 (globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true;
742 const root = createRoot(document.createElement("div"));
743 let screen: ReactNode;
744 function NewProjectObserver() {
745 screen = AddProjectNewScreen({ environmentId: "environment" });
746 return null;
747 }
748 function enterName(node: ReactNode): boolean {
749 if (Array.isArray(node)) return node.some(enterName);
750 if (
751 !isValidElement<{
752 placeholder?: string;
753 onChangeText?: (text: string) => void;
754 children?: ReactNode;
755 }>(node)
756 )
757 return false;
758 if (node.props.placeholder === "Project name") {
759 node.props.onChangeText!("new-project");
760 return true;
761 }
762 return enterName(node.props.children);
763 }
764 try {
765 await act(() => root.render(createElement(NewProjectObserver)));
766 await act(() => {
767 expect(enterName(screen)).toBe(true);
768 });
769 const submit = findAction(screen, "Create project");
770 if (!submit) throw new Error("Create project action missing");
771 await act(async () => {
772 submit();
773 created.resolve(
774 AsyncResult.success({
775 projectId: "project",
776 workspaceRoot: "/projects/new-project",
777 }),
778 );
779 await waitingForProject.promise;
780 });
781 navigation.back();
782 navigation.push("AddProjectNew");
783 const remaining = navigation.getState();
784 await act(async () => {
785 projected.resolve({ environmentId: "environment", id: "project" });
786 await projected.promise;
787 });
788​
789 expect(navigation.getState()).toEqual(remaining);
790 expect(state.dispatch).not.toHaveBeenCalled();
791 } finally {
792 await act(() => root.unmount());
793 state.newProjectsRoot = null;
794 state.createNewResult = null;
795 }
796 });
797​
798 it.each([
799 { origin: "Thread", withDraft: true, withChooser: true },
800 { origin: "NewTaskProject", withDraft: false, withChooser: true },
801 { origin: "AddProject", withDraft: false, withChooser: false },
802 ])(
803 "waits for projection then selects the draft from $origin",
804 async ({ withDraft, withChooser }) => {
805 const { created, projected, submit } = setup();
806 const navigation = mountProjectFlow(withDraft, withChooser, true);
807 const before = navigation.getState();
808 const submission = submit();
809 created.resolve(AsyncResult.success(undefined));
810 await created.promise;
811 expect(state.projects).toEqual(["/tmp/t3-mobile-audit-fixture"]);
812 expect(navigation.getState()).toBe(before);
813 projected.resolve({ environmentId: "environment", id: "project" });
814 await submission;
815 expect(state.dispatch).toHaveBeenCalledTimes(1);
816 expect(navigation.getState().routes.map((route) => route.name)).toEqual(["Home", "Thread"]);
817 expect(navigation.getState().routes[1]?.params).toEqual({
818 draft: {
819 environmentId: "environment",
820 projectId: "project",
821 title: "t3-mobile-audit-fixture",
822 },
823 });
824 navigation.back();
825 expect(navigation.getState().routes).toEqual([navigation.home]);
826 },
827 );
828});
829​
830describe("local folder path", () => {
831 function findPathInput(
832 node: ReactNode,
833 ): { value: string; onChangeText: (value: string) => void } | null {
834 if (Array.isArray(node)) {
835 for (const child of node) {
836 const input = findPathInput(child);
837 if (input) return input;
838 }
839 return null;
840 }
841 if (
842 !isValidElement<{
843 value?: string;
844 onChangeText?: (value: string) => void;
845 onSubmit?: () => void;
846 children?: ReactNode;
847 }>(node)
848 ) {
849 return null;
850 }
851 const { value, onChangeText, onSubmit } = node.props;
852 if (typeof value === "string" && onChangeText && onSubmit) return { value, onChangeText };
853 return findPathInput(node.props.children);
854 }
855​
856 function mountLocalFolder() {
857 state.scopes = new Set([AuthOrchestrationOperateScope]);
858 state.baseDirectory = "/work";
859 state.connectionStates = {};
860 state.environments = [
861 { environmentId: "environment", environmentLabel: "Environment" },
862 { environmentId: "another-environment", environmentLabel: "Another environment" },
863 ];
864 (globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true;
865 const root = createRoot(document.createElement("div"));
866 const renderedPaths: string[] = [];
867 let input: ReturnType<typeof findPathInput> = null;
868 function LocalFolderObserver(props: { environmentId?: string }) {
869 input = findPathInput(AddProjectLocalFolderScreen(props));
870 if (input) renderedPaths.push(input.value);
871 return null;
872 }
873 return {
874 renderedPaths,
875 get path() {
876 return input?.value;
877 },
878 type: (value: string) => act(() => input!.onChangeText(value)),
879 render: (environmentId?: string) =>
880 act(() => root.render(createElement(LocalFolderObserver, { environmentId }))),
881 [Symbol.asyncDispose]: async () => {
882 await act(() => root.unmount());
883 state.connectionStates = {};
884 state.environments = [{ environmentId: "environment", environmentLabel: "Environment" }];
885 },
886 };
887 }
888​
889 it("shows the new host's default path on the first render after the host changes", async () => {
890 await using screen = mountLocalFolder();
891 await screen.render("environment");
892 await screen.type("/work/edited");
893 screen.renderedPaths.length = 0;
894​
895 await screen.render("another-environment");
896​
897 expect(screen.renderedPaths).not.toContain("/work/edited");
898 expect(screen.path).toBe("~/");
899 });
900​
901 it("keeps each host's typed path when switching between hosts", async () => {
902 await using screen = mountLocalFolder();
903 await screen.render("environment");
904 await screen.type("/work/a");
905 await screen.render("another-environment");
906 await screen.type("~/b");
907​
908 await screen.render("environment");
909 expect(screen.path).toBe("/work/a");
910 await screen.render("another-environment");
911 expect(screen.path).toBe("~/b");
912 });
913​
914 it("keeps a typed path when the default host drops out and comes back", async () => {
915 await using screen = mountLocalFolder();
916 await screen.render();
917 expect(screen.path).toBe("~/");
918 await screen.type("~/code/app");
919​
920 state.connectionStates = { "another-environment": "offline" };
921 await screen.render();
922 expect(screen.path).toBe("/work/");
923​
924 state.connectionStates = {};
925 await screen.render();
926 expect(screen.path).toBe("~/code/app");
927 });
928});