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

AddProjectScreen.test.ts

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