Skip to content

Commit 3a6b018

Browse files
maria-rcksflamboh
andauthored
fix(mobile): keep split-view inspectors registered across renders (pingdotgg#25197)
Co-authored-by: oliver <[email protected]>
1 parent f8278d8 commit 3a6b018

3 files changed

Lines changed: 175 additions & 11 deletions

File tree

‎apps/mobile/src/features/files/ThreadFilesRouteScreen.tsx‎

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -361,6 +361,7 @@ function useThreadFilesWorkspace(params: {
361361
readonly threadId?: string | string[];
362362
readonly cwd?: string | string[];
363363
readonly projectName?: string | string[];
364+
readonly path?: string | string[];
364365
}) {
365366
const routeEnvironmentId = firstRouteParam(params.environmentId);
366367
const routeThreadId = firstRouteParam(params.threadId);
@@ -382,6 +383,7 @@ function useThreadFilesWorkspace(params: {
382383
cwd: routeCwd ?? selectedThreadCwd ?? project?.workspaceRoot ?? null,
383384
environmentId,
384385
projectName: routeProjectName ?? project?.title ?? "Files",
386+
relativePath: normalizeRoutePath(params.path),
385387
selectedThread,
386388
threadId,
387389
};
@@ -592,11 +594,9 @@ export function ThreadFileScreen(props: ThreadFileRouteScreenProps) {
592594
const { appearance, setCodeWordBreak } = useAppearancePreferences();
593595
const iconColor = useUniwindTheme()["--color-icon"];
594596
const params = props.route.params;
595-
const relativePath = normalizeRoutePath(params.path);
596597
const targetLine = normalizeRouteLine(firstRouteParam(params.line));
597-
const { cwd, environmentId, projectName, selectedThread, threadId } = useThreadFilesWorkspace(
598-
props.route.params,
599-
);
598+
const { cwd, environmentId, projectName, relativePath, selectedThread, threadId } =
599+
useThreadFilesWorkspace(props.route.params);
600600
const fileAccessSession = useEnvironmentQuery(
601601
environmentId !== null ? environmentSession.sessionStateAtom(environmentId) : null,
602602
);

‎apps/mobile/src/features/layout/AdaptiveWorkspaceLayout.tsx‎

Lines changed: 52 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -15,7 +15,16 @@ import { EnvironmentId, ThreadId, type SidebarProjectGroupingMode } from "@t3too
1515
import { useAtomValue } from "@effect/atom-react";
1616
import { useFocusEffect } from "@react-navigation/native";
1717
import { NavigationContext, NavigationRouteContext, useNavigation } from "@react-navigation/native";
18-
import { use, useDeferredValue, useEffect, useMemo, useRef, useState, type ReactNode } from "react";
18+
import {
19+
use,
20+
useDeferredValue,
21+
useEffect,
22+
useEffectEvent,
23+
useMemo,
24+
useRef,
25+
useState,
26+
type ReactNode,
27+
} from "react";
1928
import { Keyboard, Platform, useWindowDimensions, View } from "react-native";
2029
import { KeyboardController, useKeyboardState } from "react-native-keyboard-controller";
2130
import Animated, {
@@ -129,12 +138,48 @@ export function useRegisterWorkspaceInspector(render: (() => ReactNode) | undefi
129138
);
130139
})();
131140

132-
// useFocusEffect re-runs when the renderer changes while focused, so the
133-
// pane always shows this render's content, and its cleanup deactivates on
134-
// blur and unmount.
135-
useFocusEffect(() =>
136-
wrappedRender === undefined ? undefined : registerWorkspaceInspector(wrappedRender),
137-
);
141+
const focusedRef = useRef(false);
142+
const deactivateRef = useRef<(() => void) | null>(null);
143+
144+
const syncRegistration = useEffectEvent(() => {
145+
if (!focusedRef.current || wrappedRender === undefined) {
146+
deactivateRef.current?.();
147+
return;
148+
}
149+
deactivateRef.current = registerWorkspaceInspector(wrappedRender);
150+
});
151+
152+
// oxlint-disable-next-line t3code/no-unreasoned-state-sync -- Navigation focus events own the inspector registration lifetime.
153+
useEffect(() => {
154+
if (navigation === undefined) return;
155+
const focus = () => {
156+
if (focusedRef.current) return;
157+
focusedRef.current = true;
158+
syncRegistration();
159+
};
160+
const blur = () => {
161+
focusedRef.current = false;
162+
syncRegistration();
163+
};
164+
if (navigation.isFocused()) focus();
165+
const unsubscribeFocus = navigation.addListener("focus", focus);
166+
const unsubscribeBlur = navigation.addListener("blur", blur);
167+
return () => {
168+
unsubscribeFocus();
169+
unsubscribeBlur();
170+
focusedRef.current = false;
171+
deactivateRef.current?.();
172+
deactivateRef.current = null;
173+
};
174+
}, [navigation]);
175+
176+
// oxlint-disable-next-line t3code/no-unreasoned-state-sync -- Changed pane content replaces the focused inspector registration.
177+
useEffect(() => {
178+
if (focusedRef.current) {
179+
syncRegistration();
180+
}
181+
// oxlint-disable-next-line react/exhaustive-effect-dependencies -- Changed pane content replaces its existing native workspace registration.
182+
}, [wrappedRender]);
138183
}
139184

140185
export function AdaptiveWorkspaceLayout(props: {

‎apps/mobile/src/features/threads/thread-inspector-navigation.test.tsx‎

Lines changed: 119 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,6 @@
1+
import * as NodePath from "node:path";
12
import * as NodeModule from "node:module";
3+
import * as React from "react";
24
import { act, useLayoutEffect } from "react";
35
import { createRoot } from "react-dom/client";
46
import { expect, it, vi } from "vite-plus/test";
@@ -167,3 +169,120 @@ it("keeps the parent when the maximized child's Agents sheet opens another child
167169
expect(screen.open({ type: "thread", ...child, threadId: "grandchild" }, child)).toBe(false);
168170
expect(screen.state).toEqual(originalState);
169171
});
172+
173+
it("keeps a focused inspector registered across renders and updates its content", () => {
174+
(globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true;
175+
const requireMobile = NodeModule.createRequire(import.meta.url);
176+
const listeners = { focus: new Set<() => void>(), blur: new Set<() => void>() };
177+
let focused = true;
178+
let activeRender: (() => React.ReactNode) | undefined;
179+
const deactivate = vi.fn(() => {
180+
activeRender = undefined;
181+
});
182+
const registerWorkspaceInspector = vi.fn((render: () => React.ReactNode) => {
183+
activeRender = render;
184+
return deactivate;
185+
});
186+
const navigation = {
187+
isFocused: () => focused,
188+
addListener(event: "focus" | "blur", listener: () => void) {
189+
listeners[event].add(listener);
190+
return () => {
191+
listeners[event].delete(listener);
192+
};
193+
},
194+
};
195+
const navigationContext = React.createContext(navigation);
196+
const routeContext = React.createContext({ key: "file" });
197+
const babel = requireMobile("@babel/core") as {
198+
transformFileSync(file: string, options: Record<string, unknown>): { code: string };
199+
};
200+
const compiled = babel.transformFileSync(
201+
NodePath.resolve(__dirname, "../layout/AdaptiveWorkspaceLayout.tsx"),
202+
{
203+
babelrc: false,
204+
configFile: false,
205+
presets: [
206+
[
207+
requireMobile.resolve("babel-preset-expo"),
208+
{ unstable_transformImportMeta: true, enableBabelRuntime: false },
209+
],
210+
],
211+
caller: {
212+
name: "metro",
213+
bundler: "metro",
214+
platform: "ios",
215+
isDev: false,
216+
isServer: false,
217+
isNodeModule: false,
218+
supportsStaticESM: false,
219+
supportsReactCompiler: true,
220+
},
221+
},
222+
);
223+
const exports: {
224+
useRegisterWorkspaceInspector?: (render: (() => React.ReactNode) | undefined) => void;
225+
} = {};
226+
const load = (name: string) => {
227+
if (name === "react" || name.startsWith("react/")) return requireMobile(name);
228+
if (name === "./adaptive-workspace-context")
229+
return {
230+
useAdaptiveWorkspaceLayout: () => ({ registerWorkspaceInspector }),
231+
};
232+
if (name === "@react-navigation/native")
233+
return {
234+
NavigationContext: navigationContext,
235+
NavigationRouteContext: routeContext,
236+
useFocusEffect: (callback: () => (() => void) | undefined) =>
237+
React.useEffect(callback, [callback]),
238+
};
239+
return {};
240+
};
241+
new Function("require", "exports", compiled.code)(load, exports);
242+
const useRegisterWorkspaceInspector = exports.useRegisterWorkspaceInspector!;
243+
function Screen({ render }: { render: (() => React.ReactNode) | undefined }) {
244+
useRegisterWorkspaceInspector(render);
245+
return null;
246+
}
247+
const root = createRoot(document.createElement("div"));
248+
using _root = { [Symbol.dispose]: () => act(() => root.unmount()) };
249+
const render = (content: (() => React.ReactNode) | undefined) =>
250+
act(() => root.render(<Screen render={content} />));
251+
const first = () => "first";
252+
render(first);
253+
registerWorkspaceInspector.mockClear();
254+
deactivate.mockClear();
255+
render(first);
256+
render(first);
257+
expect(registerWorkspaceInspector).not.toHaveBeenCalled();
258+
expect(deactivate).not.toHaveBeenCalled();
259+
const second = () => "second";
260+
render(second);
261+
expect(registerWorkspaceInspector).toHaveBeenCalledTimes(1);
262+
const paneContainer = document.createElement("div");
263+
const paneRoot = createRoot(paneContainer);
264+
using _pane = { [Symbol.dispose]: () => act(() => paneRoot.unmount()) };
265+
act(() => paneRoot.render(activeRender?.()));
266+
expect(paneContainer.textContent).toBe("second");
267+
const emit = (event: "focus" | "blur") =>
268+
act(() => {
269+
focused = event === "focus";
270+
for (const listener of listeners[event]) listener();
271+
});
272+
emit("blur");
273+
expect(deactivate).toHaveBeenCalledTimes(1);
274+
registerWorkspaceInspector.mockClear();
275+
render(first);
276+
expect(registerWorkspaceInspector).not.toHaveBeenCalled();
277+
emit("focus");
278+
expect(registerWorkspaceInspector).toHaveBeenCalledTimes(1);
279+
emit("focus");
280+
expect(registerWorkspaceInspector).toHaveBeenCalledTimes(1);
281+
render(undefined);
282+
expect(activeRender).toBeUndefined();
283+
render(second);
284+
expect(activeRender).toBeDefined();
285+
act(() => root.unmount());
286+
expect(activeRender).toBeUndefined();
287+
expect(listeners.focus.size + listeners.blur.size).toBe(0);
288+
});

0 commit comments

Comments
 (0)