Skip to content

Commit 9c0756e

Browse files
synistrclaude
andcommitted
fix(mobile): windows keep their own links, layout and focus
Review of the multiple-windows change found paths that still assumed one window: - Navigation queued while the window in use was still mounting stayed queued when a ready window took over (the mounting one closed, or the person went back). Retargeting now flushes the queue. - A prompt link waiting for its screen was dropped when another window came into use, because the resolvers then saw that window's state. A pending link now remembers the window that took it, waits while another is in use, and is dropped only when its window closed. - A new window chose its first route from another window's layout metrics. It now waits for its own. - The launch-screen reveal was gated on the windows registered in JS, which misses a window that is connected but not mounted yet. Native code counts the windows instead. - Two windows side by side are both active scenes, and no notification says which one a touch went to. The window observer now also sees the first touch of each gesture in its window. Co-Authored-By: Claude Fable 5.2 <[email protected]>
1 parent 90a22c8 commit 9c0756e

11 files changed

Lines changed: 154 additions & 44 deletions

File tree

‎apps/mobile/modules/t3-native-controls/ios/T3NativeControlsModule.swift‎

Lines changed: 11 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -210,14 +210,19 @@ public final class T3NativeControlsModule: Module {
210210
@JS
211211
@MainActor
212212
func revealWindows() async {
213-
for case let windowScene as UIWindowScene in UIApplication.shared.connectedScenes {
214-
for window in windowScene.windows {
213+
let launchScreens = UIApplication.shared.connectedScenes
214+
.compactMap { $0 as? UIWindowScene }
215+
.flatMap { $0.windows }
216+
.compactMap { window -> UIView? in
215217
guard let rootView = window.rootViewController?.view,
216-
rootView.responds(to: NSSelectorFromString("loadingView")),
217-
let launchScreen = rootView.value(forKey: "loadingView") as? UIView
218-
else { continue }
219-
launchScreen.removeFromSuperview()
218+
rootView.responds(to: NSSelectorFromString("loadingView"))
219+
else { return nil }
220+
return rootView.value(forKey: "loadingView") as? UIView
220221
}
222+
// A single window's launch screen is the one expo-splash-screen hides itself, with its fade.
223+
guard launchScreens.count > 1 else { return }
224+
for launchScreen in launchScreens {
225+
launchScreen.removeFromSuperview()
221226
}
222227
}
223228

‎apps/mobile/modules/t3-native-controls/ios/T3WindowStateView.swift‎

Lines changed: 39 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,14 @@
11
import ExpoModulesCore
2-
import UIKit
2+
import UIKit.UIGestureRecognizerSubclass
33

44
/// Tells a React root about the window it is in. UIKit mounts the app again for every window
55
/// scene, and app-wide work such as an opened link belongs to the window used last.
66
final class T3WindowStateView: ExpoView {
77
let onWindowStateChange = EventDispatcher()
88
private weak var observedWindow: UIWindow?
9+
private var touchObserver: T3WindowTouchObserver?
10+
// Touches arrive constantly; only a change of window is news.
11+
private static weak var lastActive: T3WindowStateView?
912

1013
required init(appContext: AppContext? = nil) {
1114
super.init(appContext: appContext)
@@ -20,21 +23,29 @@ final class T3WindowStateView: ExpoView {
2023
super.didMoveToWindow()
2124
let center = NotificationCenter.default
2225
center.removeObserver(self)
26+
if let touchObserver {
27+
touchObserver.view?.removeGestureRecognizer(touchObserver)
28+
self.touchObserver = nil
29+
}
2330
guard let window, let scene = window.windowScene else {
2431
// A root view can outlive its window; it has nothing left to show.
2532
if observedWindow != nil { report("closed") }
2633
observedWindow = nil
2734
return
2835
}
2936
observedWindow = window
30-
// Side by side, both scenes are active; the key window is the one last touched.
3137
center.addObserver(self, selector: #selector(windowDidBecomeActive), name: UIWindow.didBecomeKeyNotification, object: window)
3238
center.addObserver(self, selector: #selector(windowDidBecomeActive), name: UIScene.didActivateNotification, object: scene)
3339
center.addObserver(self, selector: #selector(sceneDidDisconnect), name: UIScene.didDisconnectNotification, object: scene)
34-
if window.isKeyWindow { report("active") }
40+
// Side by side, both scenes stay active and no notification says which one a touch went to.
41+
let touchObserver = T3WindowTouchObserver(owner: self)
42+
window.addGestureRecognizer(touchObserver)
43+
self.touchObserver = touchObserver
44+
// A window opens in use, as its React root assumes when it mounts.
45+
report("active")
3546
}
3647

37-
@objc private func windowDidBecomeActive() {
48+
@objc fileprivate func windowDidBecomeActive() {
3849
report("active")
3950
}
4051

@@ -44,6 +55,12 @@ final class T3WindowStateView: ExpoView {
4455
}
4556

4657
private func report(_ state: String) {
58+
if state == "active" {
59+
guard Self.lastActive !== self else { return }
60+
Self.lastActive = self
61+
} else if Self.lastActive === self {
62+
Self.lastActive = nil
63+
}
4764
onWindowStateChange(["state": state])
4865
}
4966

@@ -62,3 +79,21 @@ final class T3WindowStateView: ExpoView {
6279
delegate.setValue(remaining, forKey: "window")
6380
}
6481
}
82+
83+
/// Sees the first touch of every gesture in a window without taking part in it.
84+
private final class T3WindowTouchObserver: UIGestureRecognizer {
85+
private weak var owner: T3WindowStateView?
86+
87+
init(owner: T3WindowStateView) {
88+
self.owner = owner
89+
super.init(target: nil, action: nil)
90+
delaysTouchesEnded = false
91+
cancelsTouchesInView = false
92+
}
93+
94+
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent) {
95+
super.touchesBegan(touches, with: event)
96+
owner?.windowDidBecomeActive()
97+
state = .failed
98+
}
99+
}

‎apps/mobile/src/App.tsx‎

Lines changed: 10 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -92,7 +92,6 @@ import {
9292
activateAppWindow,
9393
allocateAppWindowId,
9494
AppWindowContext,
95-
appWindowCount,
9695
closeAppWindow,
9796
subscribeAppWindows,
9897
useAppWindowId,
@@ -101,7 +100,7 @@ import {
101100
import {
102101
attachRootNavigation,
103102
flushRootNavigationQueue,
104-
isRootNavigationWindow,
103+
rootNavigationWindowStatus,
105104
linkToRootPath,
106105
rootNavigationRef,
107106
rootNavigationRoutes,
@@ -141,10 +140,12 @@ function getAppStateFromPath(path: string, options: Parameters<typeof getStateFr
141140
// app remembers; Android's replacement activity still reads the link that started it.
142141
let launchLinkTaken = false;
143142

144-
async function initialWindowURL() {
143+
async function initialWindowURL(windowId: AppWindowId) {
145144
const readsLaunchLink = !launchLinkTaken || Platform.OS !== "ios";
146145
launchLinkTaken = true;
147-
return (readsLaunchLink ? await Linking.getInitialURL() : null) ?? (await launchWorkspaceURL());
146+
return (
147+
(readsLaunchLink ? await Linking.getInitialURL() : null) ?? (await launchWorkspaceURL(windowId))
148+
);
148149
}
149150

150151
const appLinking = {
@@ -157,7 +158,6 @@ const appLinking = {
157158
],
158159
config: { initialRouteName: "Home" },
159160
filter: (url: string) => shouldHandleAppLink(url, hasCloudPublicConfig()),
160-
getInitialURL: initialWindowURL,
161161
getActionFromState: (
162162
state: Parameters<typeof getActionFromState>[0],
163163
options: Parameters<typeof getActionFromState>[1],
@@ -186,9 +186,10 @@ function linkToAppPath(href: string): void {
186186
function windowLinking(windowId: AppWindowId) {
187187
return {
188188
...appLinking,
189+
getInitialURL: () => initialWindowURL(windowId),
189190
subscribe: (listener: (url: string) => void) => {
190191
const subscription = Linking.addEventListener("url", ({ url }) => {
191-
if (isRootNavigationWindow(windowId)) listener(url);
192+
if (rootNavigationWindowStatus(windowId) === "current") listener(url);
192193
});
193194
return () => subscription.remove();
194195
},
@@ -230,8 +231,9 @@ const nativeControls = requireOptionalNativeModule<{
230231

231232
function hideSplashScreen(): void {
232233
void SplashScreen.hide();
233-
// expo-splash-screen hides the launch screen of the newest window only.
234-
if (appWindowCount() > 1) void nativeControls?.revealWindows?.().catch(() => undefined);
234+
// expo-splash-screen hides the launch screen of the newest window only. Native code counts the
235+
// windows: another one can be connected before its root has registered here.
236+
void nativeControls?.revealWindows?.().catch(() => undefined);
235237
}
236238

237239
declare const module: { readonly hot?: FoundationHotModule } | undefined;

‎apps/mobile/src/features/layout/workspace/workspace-selection-store.ts‎

Lines changed: 9 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@ import * as Linking from "expo-linking";
44
import { AppState, Dimensions, Platform } from "react-native";
55

66
import { environmentCatalog } from "../../../connection/catalog";
7+
import type { AppWindowId } from "../../../lib/appWindows";
78
import { deriveLayout } from "../../../lib/layout";
89
import {
910
NATIVE_METRICS_TIMEOUT_MS,
@@ -118,8 +119,7 @@ export const workspaceSelectionCheck: WorkspaceSelectionCheck = {
118119
};
119120

120121
/** Whether the window lays the workspace out in columns, by the rule the layout itself uses. */
121-
export function workspaceHasColumns() {
122-
const metrics = currentNativeLayoutMetrics();
122+
export function workspaceHasColumns(metrics = currentNativeLayoutMetrics()) {
123123
const { width, height } = metrics ?? Dimensions.get("window");
124124
return deriveLayout({
125125
width,
@@ -139,9 +139,9 @@ export function settingsLinkPage() {
139139
* chat beside the list instead of an empty detail column; a compact window opens on the list.
140140
* It waits for the first layout metrics as long as the workspace itself does.
141141
*/
142-
export async function launchWorkspaceURL(): Promise<string | null> {
142+
export async function launchWorkspaceURL(windowId: AppWindowId): Promise<string | null> {
143143
if (!REMEMBERS) return null;
144-
const metrics = firstNativeLayoutMetrics(NATIVE_METRICS_TIMEOUT_MS);
144+
const metrics = firstNativeLayoutMetrics(windowId, NATIVE_METRICS_TIMEOUT_MS);
145145
await hydrateWorkspaceSelections();
146146
const thread = selections.threads;
147147
// Read the chat's cached copy while the layout metrics are still on their way.
@@ -151,8 +151,11 @@ export async function launchWorkspaceURL(): Promise<string | null> {
151151
thread.threadId as ThreadId,
152152
);
153153
}
154-
await metrics;
155-
if (!thread || !workspaceHasColumns() || !workspaceSelectionCheck.thread(thread)) return null;
154+
// The opening window's own layout: another window may have columns while this one does not.
155+
const windowMetrics = await metrics;
156+
if (!thread || !workspaceHasColumns(windowMetrics) || !workspaceSelectionCheck.thread(thread)) {
157+
return null;
158+
}
156159
return Linking.createURL(
157160
`threads/${encodeURIComponent(thread.environmentId)}/${encodeURIComponent(thread.threadId)}`,
158161
);

‎apps/mobile/src/features/prompt-links/newTaskPromptLink.ts‎

Lines changed: 12 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -28,7 +28,12 @@ import {
2828
import { Atom, type AsyncResult } from "effect/reactivity";
2929

3030
import { findLinkedRoute, findStackRoute, updateLinkedRoute } from "../../lib/appLinking";
31-
import { rootNavigationRef } from "../../lib/rootNavigation";
31+
import type { AppWindowId } from "../../lib/appWindows";
32+
import {
33+
rootNavigationRef,
34+
rootNavigationWindowId,
35+
rootNavigationWindowStatus,
36+
} from "../../lib/rootNavigation";
3237
import { scopedThreadKey } from "../../lib/scopedEntities";
3338
import { appAtomRegistry } from "../../state/atom-registry";
3439
import { environmentProjects, projectEnvironment } from "../../state/projects";
@@ -82,6 +87,8 @@ const shellsSettledAtom = Atom.make((get) => {
8287
}).pipe(Atom.withLabel("mobile:prompt-link-shells-settled"));
8388

8489
let pendingLink: string | null = null;
90+
// The window that took the link: its screen lands there, and only that window's state shows it.
91+
let pendingWindow: AppWindowId | null = null;
8592
let stopWaitingForShells: (() => void) | null = null;
8693

8794
/**
@@ -98,6 +105,7 @@ export function takeNewTaskPromptLink(
98105
);
99106
if (search === null) return state;
100107
pendingLink = search;
108+
pendingWindow = rootNavigationWindowId();
101109
return updateLinkedRoute(state, NEW_TASK_ROUTES, (linked) => ({
102110
...linked,
103111
params: withoutPromptLinkParams(linked.params),
@@ -107,6 +115,9 @@ export function takeNewTaskPromptLink(
107115
/** Wired to the navigation container's state changes. */
108116
export function resolvePendingNewTaskPromptLink(state: NavigationState | undefined): void {
109117
if (pendingLink === null) return;
118+
const owner = rootNavigationWindowStatus(pendingWindow);
119+
if (owner === "closed") dropPendingLink();
120+
if (owner !== "current") return;
110121
const step = stepPendingPromptLink(pendingLink, {
111122
// A screen pushed above New task (such as Add project) drops the link, so it never lands
112123
// over the wrong screen.

‎apps/mobile/src/features/prompt-links/threadPromptLink.test.ts‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,8 @@ vi.mock("./prompt-link-actions", () => ({
1717
}));
1818
vi.mock("../../lib/rootNavigation", () => ({
1919
rootNavigationRef: { getRootState: () => fixture.root },
20+
rootNavigationWindowId: () => null,
21+
rootNavigationWindowStatus: () => "current",
2022
}));
2123
vi.mock("../../state/atom-registry", async () => {
2224
const { AtomRegistry } = await import("effect/reactivity");

‎apps/mobile/src/features/prompt-links/threadPromptLink.ts‎

Lines changed: 16 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,12 @@ import * as Option from "effect/Option";
66
import { AsyncResult } from "effect/reactivity";
77

88
import { findStackRoute } from "../../lib/appLinking";
9-
import { rootNavigationRef } from "../../lib/rootNavigation";
9+
import type { AppWindowId } from "../../lib/appWindows";
10+
import {
11+
rootNavigationRef,
12+
rootNavigationWindowId,
13+
rootNavigationWindowStatus,
14+
} from "../../lib/rootNavigation";
1015
import { scopedThreadKey } from "../../lib/scopedEntities";
1116
import { appAtomRegistry } from "../../state/atom-registry";
1217
import { environmentThreadShells, environmentThreads } from "../../state/threads";
@@ -19,7 +24,12 @@ import {
1924

2025
const THREAD_LINK_KEYS = ["prompt"];
2126

22-
type PendingThreadLink = { readonly ref: ScopedThreadRef; readonly prompt: LinkedPrompt };
27+
type PendingThreadLink = {
28+
readonly ref: ScopedThreadRef;
29+
readonly prompt: LinkedPrompt;
30+
// The window that took the link: its screen lands there, and only that window's state shows it.
31+
readonly windowId: AppWindowId | null;
32+
};
2333

2434
function firstString(value: unknown): string | null {
2535
const first = Array.isArray(value) ? value[0] : value;
@@ -64,6 +74,7 @@ export function takeThreadPromptLink(
6474
pendingLink = {
6575
ref: { environmentId: EnvironmentId.make(environmentId), threadId: ThreadId.make(threadId) },
6676
prompt: parsed.value,
77+
windowId: rootNavigationWindowId(),
6778
};
6879
}
6980
return nextState;
@@ -72,6 +83,9 @@ export function takeThreadPromptLink(
7283
/** Wired to the navigation container's state changes. */
7384
export function resolvePendingThreadPromptLink(state: NavigationState | undefined): void {
7485
if (pendingLink === null) return;
86+
const owner = rootNavigationWindowStatus(pendingLink.windowId);
87+
if (owner === "closed") dropPendingLink();
88+
if (owner !== "current") return;
7589
const { ref } = pendingLink;
7690
// A subagent thread the environment's list leaves out gets a shell once the screen mounts its
7791
// family. An archived thread never does; the screen shows it from its detail.

‎apps/mobile/src/lib/appWindows.ts‎

Lines changed: 0 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -37,10 +37,6 @@ export function activeAppWindowId(): AppWindowId | null {
3737
return windows.at(-1) ?? null;
3838
}
3939

40-
export function appWindowCount(): number {
41-
return windows.length;
42-
}
43-
4440
/** Notified when a window opens, closes or becomes the active one. */
4541
export function subscribeAppWindows(listener: () => void): () => void {
4642
listeners.add(listener);

‎apps/mobile/src/lib/rootNavigation.test.ts‎

Lines changed: 25 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -19,7 +19,8 @@ const { activateAppWindow, closeAppWindow } = await import("./appWindows");
1919
const {
2020
attachRootNavigation,
2121
flushRootNavigationQueue,
22-
isRootNavigationWindow,
22+
rootNavigationWindowId,
23+
rootNavigationWindowStatus,
2324
linkToRootPath,
2425
rootNavigationRef,
2526
whenRootNavigationReady,
@@ -50,22 +51,43 @@ it("follows the window in use, and falls back when it closes", () => {
5051
activateAppWindow(1);
5152
const detachSecond = attachRootNavigation(2, second);
5253
expect(rootNavigationRef.current).toBe(first);
53-
expect(isRootNavigationWindow(2)).toBe(false);
54+
expect(rootNavigationWindowStatus(2)).toBe("waiting");
5455

5556
activateAppWindow(2);
5657
expect(rootNavigationRef.current).toBe(second);
5758
activateAppWindow(1);
5859
expect(rootNavigationRef.current).toBe(first);
59-
expect(isRootNavigationWindow(1)).toBe(true);
60+
expect(rootNavigationWindowId()).toBe(1);
61+
expect(rootNavigationWindowStatus(1)).toBe("current");
6062

6163
closeAppWindow(1);
6264
detachFirst();
6365
expect(rootNavigationRef.current).toBe(second);
66+
expect(rootNavigationWindowStatus(1)).toBe("closed");
6467
closeAppWindow(2);
6568
detachSecond();
6669
expect(rootNavigationRef.current).toBeNull();
6770
});
6871

72+
it("runs queued navigation when a ready window takes over from one still mounting", () => {
73+
const navigate = vi.fn();
74+
const detachReady = attachRootNavigation(1, fakeContainer());
75+
activateAppWindow(1);
76+
const mounting = {
77+
isReady: () => false,
78+
} as NavigationContainerRef<ReactNavigation.RootParamList>;
79+
const detachMounting = attachRootNavigation(2, mounting);
80+
activateAppWindow(2);
81+
whenRootNavigationReady(navigate);
82+
expect(navigate).not.toHaveBeenCalled();
83+
84+
closeAppWindow(2);
85+
detachMounting();
86+
expect(navigate).toHaveBeenCalledOnce();
87+
closeAppWindow(1);
88+
detachReady();
89+
});
90+
6991
it("holds navigation until the container is ready, then runs it once", () => {
7092
const navigate = vi.fn();
7193
const failing = vi.fn(() => {

0 commit comments

Comments
 (0)