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