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

NewTaskDraftRouteScreen.test.tsx

191 lines7.6 KB

1import type { ReactNode } from "react";
2import { act, useSyncExternalStore } from "react";
3import { createRoot } from "react-dom/client";
4import { AsyncResult } from "effect/reactivity";
5import { expect, it, vi } from "vite-plus/test";
6​
7interface Snapshot {
8 readonly projects: ReadonlyArray<{
9 readonly environmentId: string;
10 readonly id: string;
11 readonly workspaceRoot: string;
12 }>;
13 readonly catalog: {
14 readonly isLoadingConnections: boolean;
15 readonly hasLoadedShellSnapshot: boolean;
16 readonly hasConnectingEnvironment: boolean;
17 readonly connectionError: string | null;
18 };
20​
21const harness = vi.hoisted(() => {
22 const listeners = new Set<() => void>();
23 const state: { snapshot: Snapshot | null } = { snapshot: null };
24 return {
25 state,
26 set(next: Snapshot) {
27 state.snapshot = next;
28 for (const listener of listeners) listener();
29 },
30 subscribe(listener: () => void) {
31 listeners.add(listener);
32 return () => listeners.delete(listener);
33 },
34 route: { key: "thread-route", name: "Thread", params: {} as object },
35 reset: () => undefined,
36 checkout: vi.fn(),
37 draftProjectRefs: [] as unknown[],
38 // Hook results stay stable across renders, as the real hooks' are. Only
39 // main's screen reads these (see the main-comparison mocks below).
40 layout: { deferThreadSelectionUntil: () => undefined },
41 navigation: { goBack: () => undefined },
42 preventContext: { preventedRoutes: {} },
43 };
44});
45​
46function useSnapshot(): Snapshot {
47 return useSyncExternalStore(harness.subscribe, () => harness.state.snapshot!);
49​
50vi.mock("react-native", () => ({
51 View: ({ children }: { children: ReactNode }) => <div>{children}</div>,
52}));
53vi.mock("../../components/ui/AppText", () => ({
54 AppText: ({ children }: { children: ReactNode }) => <span>{children}</span>,
55}));
56vi.mock("../../components/ui/Dialog", () => ({ alert: vi.fn() }));
57vi.mock("../../native/StackHeader", () => ({ NativeStackScreenOptions: () => null }));
58vi.mock("./ThreadScreenHost", () => ({
59 ThreadScreenFallback: ({ children }: { children: ReactNode }) => <>{children}</>,
60}));
61vi.mock("./NewTaskDraftScreen", () => ({
62 NewTaskDraftScreen: (props: { initialProjectRef: { branch?: string | null } }) => {
63 harness.draftProjectRefs.push(props.initialProjectRef);
64 return <p>draft on {props.initialProjectRef.branch}</p>;
65 },
66}));
67vi.mock("./new-task-context-presentation", () => ({
68 resolveNewTaskBranchWorktreePath: () => null,
69}));
70vi.mock("./new-task-flow-provider", () => ({
71 useNewTaskFlow: () => harness,
72}));
73vi.mock("./checkout-new-task-branch", () => ({ checkoutNewTaskBranch: harness.checkout }));
74// Main-comparison mocks: this screen no longer uses them, but main's screen
75// did (deferThreadSelectionUntil, useAtomCommand, useNavigation). They stay so
76// this test can run against main's screen and fail there for the right reason
77// (a second checkout) instead of on an unmockable import.
78vi.mock("../layout/AdaptiveWorkspaceLayout", () => ({
79 useAdaptiveWorkspaceLayout: () => harness.layout,
80}));
81vi.mock("../../state/use-atom-command", () => ({ useAtomCommand: () => harness.checkout }));
82vi.mock("../../state/entities", () => ({ useProjects: () => useSnapshot().projects }));
83vi.mock("../../state/workspace", () => ({
84 useWorkspaceState: () => ({ state: useSnapshot().catalog }),
85}));
86vi.mock("../../state/vcs", () => ({ vcsEnvironment: { readRefs: {}, switchRef: {} } }));
87vi.mock("@react-navigation/native", () => ({
88 CommonActions: { goBack: () => ({ type: "GO_BACK" }) },
89 createNavigationContainerRef: () => ({ current: null }),
90 // Main-comparison only, like the mocks above.
91 useNavigation: () => harness.navigation,
92 useRoute: () => harness.route,
93 usePreventRemove: () => undefined,
94 usePreventRemoveContext: () => harness.preventContext,
95}));
96​
97import { NewTaskDraftRouteScreen } from "./NewTaskDraftRouteScreen";
98​
99const project = { environmentId: "env-1", id: "project-1", workspaceRoot: "/repo" };
100const connected: Snapshot["catalog"] = {
101 isLoadingConnections: false,
102 hasLoadedShellSnapshot: true,
103 hasConnectingEnvironment: false,
104 connectionError: null,
105};
106​
107// The project can vanish while the catalog still loads, or while it reports ready.
108it.each([
109 ["while the catalog reloads", { ...connected, isLoadingConnections: true }],
110 ["while the catalog stays ready", connected],
111])(
112 "checks the branch out once when a reconnect drops and restores the project %s",
113 async (gap, gapCatalog) => {
114 // Checkouts live in a module table keyed by route, so each case uses its own route.
115 const routeKey = `thread-route ${gap}`;
116 (globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true;
117 const firstCheckout = Promise.withResolvers<unknown>();
118 harness.checkout.mockReturnValueOnce(firstCheckout.promise);
119 harness.checkout.mockResolvedValue(
120 AsyncResult.success({ name: "feature", current: true, isDefault: false, worktreePath: null }),
121 );
122 harness.set({ projects: [project], catalog: connected });
123 const draft = { environmentId: "env-1", projectId: "project-1", branch: "feature" };
124 harness.route = { key: routeKey, name: "Thread", params: { draft } };
125​
126 const container = document.createElement("div");
127 const root = createRoot(container);
128 using _root = { [Symbol.dispose]: () => act(() => root.unmount()) };
129 act(() =>
130 root.render(
131 <NewTaskDraftRouteScreen
132 route={{ key: routeKey, name: "Thread", params: draft } as never}
133 />,
134 ),
135 );
136 await vi.waitFor(() => expect(harness.checkout).toHaveBeenCalledTimes(1));
137​
138 // The connection drops while the checkout runs, then the project comes back.
139 act(() => harness.set({ projects: [], catalog: gapCatalog }));
140 act(() => harness.set({ projects: [project], catalog: connected }));
141 await act(async () => {
142 firstCheckout.resolve(
143 AsyncResult.success({
144 name: "feature",
145 current: true,
146 isDefault: false,
147 worktreePath: null,
148 }),
149 );
150 });
151​
152 await vi.waitFor(() =>
153 expect(
154 harness.checkout.mock.calls.length > 1 || container.textContent === "draft on feature",
155 ).toBe(true),
156 );
157 expect(harness.checkout).toHaveBeenCalledTimes(1);
158 expect(container.textContent).toBe("draft on feature");
159 },
160);
161​
162it("hands the draft screen the same project ref across re-renders", async () => {
163 (globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true;
164 harness.checkout.mockReset();
165 harness.draftProjectRefs.length = 0;
166 harness.checkout.mockResolvedValue(
167 AsyncResult.success({ name: "other", current: true, isDefault: false, worktreePath: null }),
168 );
169 harness.set({ projects: [project], catalog: connected });
170 const draft = { environmentId: "env-1", projectId: "project-1", branch: "other" };
171 harness.route = { key: "stable-route", name: "Thread", params: { draft } };
172​
173 const container = document.createElement("div");
174 const root = createRoot(container);
175 using _root = { [Symbol.dispose]: () => act(() => root.unmount()) };
176 act(() =>
177 root.render(
178 <NewTaskDraftRouteScreen
179 route={{ key: "stable-route", name: "Thread", params: draft } as never}
180 />,
181 ),
182 );
183 await vi.waitFor(() => expect(container.textContent).toBe("draft on other"));
184​
185 // The draft screen re-applies its route project when this identity changes,
186 // and that write re-renders the route; an unstable ref loops forever.
187 act(() => harness.set({ projects: [{ ...project }], catalog: { ...connected } }));
188 // A stable ref lets the compiled screen skip re-rendering the draft screen at all; an unstable
189 // one re-renders it with a second ref.
190 expect(new Set(harness.draftProjectRefs).size).toBe(1);
191});