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

thread-inspector-navigation.test.tsx

392 lines14.3 KB

1import * as NodePath from "node:path";
2import * as NodeModule from "node:module";
3import * as React from "react";
4import { act, useLayoutEffect } from "react";
5import { createRoot } from "react-dom/client";
6import { EnvironmentId, ThreadId } from "@t3tools/contracts";
7import { expect, it, vi } from "vite-plus/test";
8​
9const harness = vi.hoisted(() => ({
10 dispatch: (_action: unknown) => {},
11 getState: (): unknown => undefined,
12 getRoute: (): unknown => undefined,
13 inspectorSupported: true,
14}));
15​
16vi.mock("react-native", () => ({ Platform: { OS: "ios" } }));
17vi.mock("../layout/AdaptiveWorkspaceLayout", () => ({
18 useWorkspacePaneState: () => ({ fileInspector: { supported: harness.inspectorSupported } }),
19}));
20vi.mock("@react-navigation/native", async () => {
21 const { createRequire } = await import("node:module");
22 const requireNavigation = createRequire(
23 createRequire(import.meta.url).resolve("@react-navigation/native/package.json"),
24 );
25 return {
26 StackActions: requireNavigation("@react-navigation/routers").StackActions,
27 useNavigation: () => ({ dispatch: harness.dispatch, getState: harness.getState }),
28 useRoute: () => harness.getRoute(),
29 };
30});
31​
32import { useOpenThreadInspector, useReturnToThread } from "./thread-inspector-navigation";
33import { useOpenLinkedThread, useOpenLinkedThreadRead } from "./useOpenLinkedThread";
34​
35const requireNavigation = NodeModule.createRequire(
36 NodeModule.createRequire(import.meta.url).resolve("@react-navigation/native/package.json"),
37);
38const { StackRouter, StackActions } = requireNavigation("@react-navigation/routers") as {
39 StackRouter: typeof import("@react-navigation/native").StackRouter;
40 StackActions: typeof import("@react-navigation/native").StackActions;
41};
42​
43function setup(fromAgents: boolean, fullscreen = false, inspectorSupported = true) {
44 harness.inspectorSupported = inspectorSupported;
45 (globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true;
46 const router = StackRouter({});
47 const options = {
48 routeNames: [
49 "Home",
50 "Thread",
51 "ThreadAgents",
52 "ThreadInspectorFullscreen",
53 "LinkedThread",
54 "ThreadReview",
55 "GitConfirm",
56 ],
57 routeParamList: {},
58 routeGetIdList: {},
59 };
60 let state = router.getInitialState(options);
61 const dispatch = (action: Parameters<typeof router.getStateForAction>[1]) => {
62 const next = router.getStateForAction(state, action, options);
63 if (!next) throw new Error(`Rejected ${action.type}`);
64 state = router.getRehydratedState(next, options);
65 };
66 harness.dispatch = (action) => dispatch(action as Parameters<typeof dispatch>[0]);
67 harness.getState = () => state;
68 harness.getRoute = () => state.routes.at(-1);
69 const source = { environmentId: "remote-environment", threadId: "parent" };
70 dispatch(StackActions.push("Thread", { ...source, prompt: "retained prompt" }));
71 const parentKey = state.routes.at(-1)!.key;
72 if (fullscreen)
73 dispatch(StackActions.push("ThreadInspectorFullscreen", { ...source, threadId: "child" }));
74 if (fromAgents)
75 dispatch(
76 StackActions.push("ThreadAgents", fullscreen ? { ...source, threadId: "child" } : source),
77 );
78 let openInspector: ReturnType<typeof useOpenThreadInspector>;
79 let openLinkedThread: ReturnType<typeof useOpenLinkedThread>;
80 let openLinkedThreadRead: ReturnType<typeof useOpenLinkedThreadRead>;
81 let returnToThread: ReturnType<typeof useReturnToThread>;
82 function Probe() {
83 const open = useOpenThreadInspector();
84 const openLinked = useOpenLinkedThread();
85 const openLinkedRead = useOpenLinkedThreadRead();
86 const returnTo = useReturnToThread();
87 useLayoutEffect(() => {
88 openInspector = open;
89 openLinkedThread = openLinked;
90 openLinkedThreadRead = openLinkedRead;
91 returnToThread = returnTo;
92 });
93 return null;
94 }
95 const root = createRoot(document.createElement("div"));
96 act(() => root.render(<Probe />));
97 return {
98 source,
99 parentKey,
100 dispatch,
101 get state() {
102 return state;
103 },
104 open(target: Parameters<typeof openInspector>[1], from = source) {
105 let opened = false;
106 act(() => {
107 opened = openInspector(from, target);
108 });
109 return opened;
110 },
111 openLinked(threadId: string) {
112 act(() => openLinkedThread({ environmentId: source.environmentId, threadId }));
113 },
114 openLinkedRead(...input: Parameters<typeof openLinkedThreadRead>) {
115 act(() => openLinkedThreadRead(...input));
116 },
117 returnTo(thread: Parameters<typeof returnToThread>[0]) {
118 act(() => returnToThread(thread));
119 },
120 [Symbol.dispose]() {
121 act(() => root.unmount());
122 },
123 };
125​
126it("opens a subagent from the Agents sheet without replacing the parent thread", () => {
127 using screen = setup(true);
128 const inspector = {
129 type: "thread",
130 environmentId: screen.source.environmentId,
131 threadId: "child",
132 } as const;
133 screen.open(inspector);
134 expect(screen.state.routes.map((route) => route.name)).toEqual(["Home", "Thread"]);
135 expect(screen.state.routes.at(-1)).toMatchObject({
136 key: screen.parentKey,
137 params: { ...screen.source, prompt: "retained prompt", inspector },
138 });
139 screen.dispatch(StackActions.push("ThreadInspectorFullscreen", inspector));
140 screen.dispatch(StackActions.pop());
141 expect(screen.state.routes.at(-1)).toMatchObject({
142 key: screen.parentKey,
143 params: { ...screen.source, inspector },
144 });
145});
146​
147it("opens a completion link in the parent inspector", () => {
148 using screen = setup(false);
149 screen.openLinked("child");
150 expect(screen.state.routes).toHaveLength(2);
151 expect(screen.state.routes.at(-1)).toMatchObject({
152 key: screen.parentKey,
153 params: {
154 ...screen.source,
155 inspector: { type: "thread", environmentId: screen.source.environmentId, threadId: "child" },
156 },
157 });
158});
159​
160it.each([
161 { inspectorSupported: true, fromAgents: false },
162 { inspectorSupported: true, fromAgents: true },
163 { inspectorSupported: false, fromAgents: false },
164 { inspectorSupported: false, fromAgents: true },
165])(
166 "opens a linked environment's thread in the inspector where there is one ($inspectorSupported, from Agents $fromAgents)",
167 ({ inspectorSupported, fromAgents }) => {
168 using screen = setup(fromAgents, false, inspectorSupported);
169 const thread = {
170 environmentId: EnvironmentId.make("linked-vm"),
171 threadId: ThreadId.make("there"),
172 };
173 const linked = { viaEnvironmentId: EnvironmentId.make("remote-environment"), label: "fs-17" };
174 screen.openLinkedRead(thread, linked, "Fix the build", {
175 source: screen.source,
176 replace: fromAgents,
177 });
178 if (inspectorSupported) {
179 // Beside the parent, like a subagent or a side chat; the Agents sheet gives way.
180 expect(screen.state.routes.map((route) => route.name)).toEqual(["Home", "Thread"]);
181 expect(screen.state.routes.at(-1)).toMatchObject({
182 key: screen.parentKey,
183 params: {
184 inspector: {
185 type: "linkedThread",
186 ...thread,
187 linked: { ...linked, title: "Fix the build" },
188 },
189 },
190 });
191 return;
192 }
193 // A phone has no inspector: the read-only thread takes the screen, replacing the sheet.
194 expect(screen.state.routes.map((route) => route.name)).toEqual([
195 "Home",
196 "Thread",
197 "LinkedThread",
198 ]);
199 expect(screen.state.routes.at(-1)?.params).toEqual({
200 ...thread,
201 ...linked,
202 title: "Fix the build",
203 });
204 },
205);
206​
207it.each([
208 { confirmFrom: "parent", routes: ["Home", "Thread"] },
209 // A side thread's review, opened from the parent's inspector, sits above the parent's route.
210 { confirmFrom: "child", routes: ["Home", "Thread", "ThreadReview", "Thread"] },
211])(
212 "returns from a Git confirmation to the $confirmFrom thread without replacing another",
213 ({ confirmFrom, routes }) => {
214 using screen = setup(false);
215 const inspector = { type: "device", ...screen.source } as const;
216 screen.open(inspector);
217 const thread = { ...screen.source, threadId: confirmFrom };
218 if (confirmFrom !== "parent") screen.dispatch(StackActions.push("ThreadReview", thread));
219 screen.dispatch(StackActions.push("GitConfirm", thread));
220 screen.returnTo(thread);
221 expect(screen.state.routes.map((route) => route.name)).toEqual(routes);
222 expect(screen.state.routes[1]).toMatchObject({
223 key: screen.parentKey,
224 params: { ...screen.source, prompt: "retained prompt", inspector },
225 });
226 expect(screen.state.routes.at(-1)?.params).toMatchObject(thread);
227 },
228);
229​
230it("switches between subagents and devices in the same parent route", () => {
231 using screen = setup(false);
232 screen.open({ type: "thread", environmentId: screen.source.environmentId, threadId: "child" });
233 const inspector = { type: "device", ...screen.source } as const;
234 screen.open(inspector);
235 expect(screen.state.routes).toHaveLength(2);
236 expect(screen.state.routes.at(-1)).toMatchObject({
237 key: screen.parentKey,
238 params: { ...screen.source, inspector },
239 });
240});
241​
242it.each(["thread", "device"] as const)(
243 "keeps the parent when a maximized child opens a %s preview",
244 (type) => {
245 using screen = setup(false, true);
246 const child = { ...screen.source, threadId: "child" };
247 const originalState = screen.state;
248 expect(screen.open({ type, ...child, threadId: "grandchild" }, child)).toBe(false);
249 expect(screen.state).toEqual(originalState);
250 screen.dispatch(StackActions.pop());
251 expect(screen.state.routes.at(-1)).toMatchObject({
252 key: screen.parentKey,
253 params: screen.source,
254 });
255 },
256);
257​
258it("keeps the parent when the maximized child's Agents sheet opens another child", () => {
259 using screen = setup(true, true);
260 const child = { ...screen.source, threadId: "child" };
261 const originalState = screen.state;
262 expect(screen.open({ type: "thread", ...child, threadId: "grandchild" }, child)).toBe(false);
263 expect(screen.state).toEqual(originalState);
264});
265​
266it("keeps a focused inspector registered across renders and updates its content", () => {
267 (globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true;
268 const requireMobile = NodeModule.createRequire(import.meta.url);
269 const listeners = { focus: new Set<() => void>(), blur: new Set<() => void>() };
270 let focused = true;
271 let activeRender: (() => React.ReactNode) | undefined;
272 const deactivate = vi.fn(() => {
273 activeRender = undefined;
274 });
275 const registerWorkspaceInspector = vi.fn(
276 (content: { readonly panes: ReadonlyArray<{ readonly render: () => React.ReactNode }> }) => {
277 activeRender = content.panes[0]?.render;
278 return deactivate;
279 },
280 );
281 const navigation = {
282 isFocused: () => focused,
283 addListener(event: "focus" | "blur", listener: () => void) {
284 listeners[event].add(listener);
285 return () => {
286 listeners[event].delete(listener);
287 };
288 },
289 };
290 const navigationContext = React.createContext(navigation);
291 const routeContext = React.createContext({ key: "file" });
292 const babel = requireMobile("@babel/core") as {
293 transformFileSync(file: string, options: Record<string, unknown>): { code: string };
294 };
295 const compiled = babel.transformFileSync(
296 NodePath.resolve(__dirname, "../layout/AdaptiveWorkspaceLayout.tsx"),
297 {
298 babelrc: false,
299 configFile: false,
300 presets: [
301 [
302 requireMobile.resolve("babel-preset-expo"),
303 { unstable_transformImportMeta: true, enableBabelRuntime: false },
304 ],
305 ],
306 caller: {
307 name: "metro",
308 bundler: "metro",
309 platform: "ios",
310 isDev: false,
311 isServer: false,
312 isNodeModule: false,
313 supportsStaticESM: false,
314 supportsReactCompiler: true,
315 },
316 },
317 );
318 const exports: {
319 Inspector?: (props: {
320 readonly content: {
321 readonly active: string;
322 readonly panes: ReadonlyArray<{ readonly key: string; readonly render: () => string }>;
323 };
324 }) => null;
325 } = {};
326 const load = (name: string) => {
327 if (name === "react" || name.startsWith("react/")) return requireMobile(name);
328 if (name === "./adaptive-workspace-context")
329 return {
330 useAdaptiveWorkspaceLayout: () => ({ registerWorkspaceInspector }),
331 };
332 if (name === "@react-navigation/native")
333 return {
334 NavigationContext: navigationContext,
335 NavigationRouteContext: routeContext,
336 };
337 return {};
338 };
339 new Function("require", "exports", compiled.code)(load, exports);
340 const Inspector = exports.Inspector!;
341 const contents = new Map<string, Parameters<typeof Inspector>[0]["content"]>();
342 function Screen({ content }: { content: string | undefined }) {
343 if (content === undefined) return null;
344 let panes = contents.get(content);
345 if (!panes) {
346 panes = { active: "main", panes: [{ key: "main", render: () => content }] };
347 contents.set(content, panes);
348 }
349 return <Inspector content={panes} />;
350 }
351 const root = createRoot(document.createElement("div"));
352 using _root = { [Symbol.dispose]: () => act(() => root.unmount()) };
353 const render = (content: string | undefined) =>
354 act(() => root.render(<Screen content={content} />));
355 const first = "first";
356 render(first);
357 registerWorkspaceInspector.mockClear();
358 deactivate.mockClear();
359 render(first);
360 render(first);
361 expect(registerWorkspaceInspector).not.toHaveBeenCalled();
362 expect(deactivate).not.toHaveBeenCalled();
363 const second = "second";
364 render(second);
365 expect(registerWorkspaceInspector).toHaveBeenCalledTimes(1);
366 const paneContainer = document.createElement("div");
367 const paneRoot = createRoot(paneContainer);
368 using _pane = { [Symbol.dispose]: () => act(() => paneRoot.unmount()) };
369 act(() => paneRoot.render(activeRender?.()));
370 expect(paneContainer.textContent).toBe("second");
371 const emit = (event: "focus" | "blur") =>
372 act(() => {
373 focused = event === "focus";
374 for (const listener of listeners[event]) listener();
375 });
376 emit("blur");
377 expect(deactivate).toHaveBeenCalledTimes(1);
378 registerWorkspaceInspector.mockClear();
379 render(first);
380 expect(registerWorkspaceInspector).not.toHaveBeenCalled();
381 emit("focus");
382 expect(registerWorkspaceInspector).toHaveBeenCalledTimes(1);
383 emit("focus");
384 expect(registerWorkspaceInspector).toHaveBeenCalledTimes(1);
385 render(undefined);
386 expect(activeRender).toBeUndefined();
387 render(second);
388 expect(activeRender).toBeDefined();
389 act(() => root.unmount());
390 expect(activeRender).toBeUndefined();
391 expect(listeners.focus.size + listeners.blur.size).toBe(0);
392});