The best way to control Claude Code, Codex and more from any computer or phone
refactor(mobile): notifications, quick actions and Connect onboarding navigate through the root ref (#25769)
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
Julius Marminge committed
Oct 26, 2026 at 23:17 UTC
0b02b21e5a451fa7e488a8596cedbeb0ddd9d63c
14 files changed
+560
-261
apps/mobile/src/App.tsx
+50
-10
@@ -9,9 +9,12 @@ import { GestureHandlerRootView } from "react-native-gesture-handler";
9
import { KeyboardProvider } from "react-native-keyboard-controller";
10
import { SafeAreaProvider } from "react-native-safe-area-context";
11
import {
12
+ CommonActions,
13
+ createPathConfigForStaticNavigation,
14
createStaticNavigation,
15
getActionFromState,
16
getStateFromPath,
17
+ type NavigationAction,
18
type NavigationState,
19
} from "@react-navigation/native";
20
@@ -25,12 +28,20 @@ import {
28
presentPendingIncomingShare,
29
startIncomingShareInbox,
30
} from "./features/sharing/IncomingShareProvider";
31
+import {
32
+ installAgentNotificationNavigation,
33
+ setAgentNotificationPathname,
34
+} from "./features/agent-awareness/notificationNavigation";
35
+import {
36
+ installAppShortcuts,
37
+ recordAppShortcutNavigationState,
38
+} from "./features/shortcuts/appShortcutsRuntime";
39
import {
40
AppearancePreferencesProvider,
41
installAppearanceRuntime,
42
useAppearancePreferences,
43
} from "./features/settings/appearance/AppearancePreferencesProvider";
33
-import { RootStack } from "./Stack";
44
+import { RootStack, workspaceLocationFromState } from "./Stack";
45
import { appAtomRegistry } from "./state/atom-registry";
46
import { subscribeComposerDraftModelReconciliation } from "./state/use-composer-drafts";
47
import { environmentThreadShells } from "./state/threads";
@@ -57,7 +68,12 @@ import {
68
} from "./features/workspace/workspace-selection-store";
69
import { workspaceDetailLinkAction } from "./features/workspace/workspace-detail-selection";
70
import { NativeLayoutMetricsProvider } from "./native/native-layout-metrics";
60
-import { attachRootNavigation, rootNavigationRef } from "./lib/rootNavigation";
71
+import {
72
+ attachRootNavigation,
73
+ flushRootNavigationQueue,
74
+ linkToRootPath,
75
+ rootNavigationRef,
76
+} from "./lib/rootNavigation";
77
import { pruneNewTaskBranchCheckouts } from "./features/threads/NewTaskDraftRouteScreen";
78
79
import "../global.css";
@@ -69,6 +85,20 @@ if (process.env.EXPO_PUBLIC_SHOWCASE === "1") {
85
void SplashScreen.preventAutoHideAsync().catch(() => {});
86
void hydrateWorkspaceSelections();
87
88
+const linkingConfig = {
89
+ initialRouteName: "Home",
90
+ screens: createPathConfigForStaticNavigation(RootStack, { initialRouteName: "Home" }) ?? {},
91
+} as const;
92
+
93
+function getAppStateFromPath(path: string, options: Parameters<typeof getStateFromPath>[1]) {
94
+ return takeScheduledTaskNewLink(
95
+ restoreSettingsLinkState(
96
+ restoreDraftLinkState(getStateFromPath(path, options), path),
97
+ settingsLinkPage(),
98
+ ),
99
+ );
100
+}
101
+
102
const appLinking = {
103
prefixes: [Linking.createURL("/"), "t3code://", "t3code-dev://", "t3code-preview://"],
104
config: { initialRouteName: "Home" },
@@ -81,25 +111,33 @@ const appLinking = {
111
// Our router handles the selection; React Navigation's type only lists its own actions.
112
(workspaceDetailLinkAction(state) as ReturnType<typeof getActionFromState>) ??
113
getActionFromState(state, options),
84
- getStateFromPath: (path: string, options: Parameters<typeof getStateFromPath>[1]) =>
85
- takeScheduledTaskNewLink(
86
- restoreSettingsLinkState(
87
- restoreDraftLinkState(getStateFromPath(path, options), path),
88
- settingsLinkPage(),
89
- ),
90
- ),
114
+ getStateFromPath: getAppStateFromPath,
115
};
116
117
+function appLinkAction(href: string): NavigationAction {
118
+ const state = getAppStateFromPath(href, linkingConfig);
119
+ if (!state) throw new Error(`Failed to parse the href to a navigation state (${href}).`);
120
+ return appLinking.getActionFromState(state, linkingConfig) ?? CommonActions.reset(state);
121
+}
122
+
123
+function linkToAppPath(href: string): void {
124
+ linkToRootPath(href, appLinkAction);
125
+}
126
+
127
const Navigation = createStaticNavigation(RootStack);
128
129
function handleNavigationStateChange(state: NavigationState | undefined): void {
130
recordWorkspaceSelections(state);
97
- if (state) pruneNewTaskBranchCheckouts(state);
131
presentPendingIncomingShare();
132
+ if (!state) return;
133
+ setAgentNotificationPathname(workspaceLocationFromState(state).pathname);
134
+ recordAppShortcutNavigationState(state);
135
+ pruneNewTaskBranchCheckouts(state);
136
}
137
138
function handleNavigationReady(): void {
139
handleNavigationStateChange(rootNavigationRef.getRootState());
140
+ flushRootNavigationQueue();
141
}
142
143
declare const module: { readonly hot?: FoundationHotModule } | undefined;
@@ -118,6 +156,8 @@ const appServiceDisposers = [
156
installThreadOutboxDelivery(),
157
installComposerAttachmentUploads(),
158
startIncomingShareInbox(),
159
+ installAgentNotificationNavigation(linkToAppPath),
160
+ installAppShortcuts(linkToAppPath),
161
];
162
disposeOnFoundationReplace(typeof module === "undefined" ? undefined : module.hot, () => {
163
for (const dispose of appServiceDisposers) dispose();
apps/mobile/src/Stack.tsx
+11
-7
@@ -24,6 +24,11 @@ import { androidWorkspaceDestinationAnimation } from "./lib/android-workspace-na
24
import { getCompactBrandHeaderOptions } from "./components/CompactBrandTitle";
25
import { WorkspaceConnectionStatusProvider } from "./features/home/WorkspaceConnectionTitle";
26
import { WorkspaceRootScreen } from "./features/workspace/WorkspaceRootScreen";
27
+import {
28
+ recordHomeFocus,
29
+ recordHomeTransitionEnd,
30
+ recordHomeTransitionStart,
31
+} from "./features/home/home-route-visibility";
32
import { AndroidWorkspaceTabsProvider } from "./features/workspace/AndroidWorkspaceTabsProvider";
33
import {
34
PullRequestRouteScreen,
@@ -41,9 +46,7 @@ import {
46
type RenderFailureProps,
47
} from "./components/RenderErrorBoundary";
48
import { ArchivedThreadsRouteScreen } from "./features/archive/ArchivedThreadsRouteScreen";
44
-import { useAgentNotificationNavigation } from "./features/agent-awareness/notificationNavigation";
49
import { ConnectOnboardingRouteScreen } from "./features/cloud/ConnectOnboardingRouteScreen";
46
-import { useConnectOnboardingNavigation } from "./features/cloud/connectOnboardingNavigation";
50
import { AttachmentFileScreen } from "./features/files/AttachmentFileScreen";
51
import { ThreadFilesTreeScreen, ThreadFileScreen } from "./features/files/ThreadFilesRouteScreen";
52
import { AdaptiveWorkspaceLayout } from "./features/layout/AdaptiveWorkspaceLayout";
@@ -138,7 +141,6 @@ import {
141
SettingsLegalDocumentCloseHeaderButton,
142
SettingsLegalDocumentExternalHeaderButton,
143
} from "./features/settings/components/SettingsLegalDocumentRouteScreen";
141
-import { useAppShortcuts } from "./features/shortcuts/useAppShortcuts";
144
import { NATIVE_LIQUID_GLASS_SUPPORTED } from "./native/native-glass";
145
import { deriveLayout } from "./lib/layout";
146
import { useNativeLayoutMetrics } from "./native/native-layout-metrics";
@@ -473,7 +475,7 @@ const SETTINGS_SCREENS = {
475
// iOS 26 header morphing requires one UINavigationBar; nested stacks make the whole screen slide.
476
const THREAD_LINKING_PREFIX = "threads/:environmentId/:threadId";
477
476
-function workspaceLocationFromState(state: NavigationState) {
478
+export function workspaceLocationFromState(state: NavigationState) {
479
const routes = state.routes.filter((route) => !isWorkspaceOverlayRoute(route.name));
480
const effectiveState =
481
routes.length > 0 && routes.length !== state.routes.length
@@ -505,9 +507,6 @@ function RootStackLayout(props: {
507
const routeDraftId = Array.isArray(draftParams?.draftId)
508
? draftParams.draftId[0]
509
: draftParams?.draftId;
508
- useAgentNotificationNavigation(workspaceLocation.pathname);
509
- useConnectOnboardingNavigation();
510
- useAppShortcuts(props.state);
510
511
return (
512
<NewTaskFlowProvider active={isDraftThreadRoute(draftRoute)} routeDraftId={routeDraftId}>
@@ -592,6 +591,11 @@ const RootStackConfig = createWorkspaceStackNavigator({
591
Home: createNativeStackScreen({
592
screen: WorkspaceRootScreen,
593
linking: "",
594
+ listeners: {
595
+ transitionStart: ({ data }) => recordHomeTransitionStart(data.closing),
596
+ transitionEnd: ({ data }) => recordHomeTransitionEnd(data.closing),
597
+ focus: recordHomeFocus,
598
+ },
599
options: {
600
...GLASS_HEADER_OPTIONS,
601
...FIXED_DUO_HEADER,
apps/mobile/src/features/agent-awareness/notificationNavigation.ts
+30
-38
@@ -1,50 +1,42 @@
1
-import { useEffect, useLayoutEffect, useRef } from "react";
1
import * as Notifications from "expo-notifications";
3
-import { useLinkTo } from "@react-navigation/native";
2
3
import { setAndroidThreadOnScreen } from "./androidNotifications";
4
import { foregroundNotificationBehavior } from "./foregroundNotificationBehavior";
5
import { routeAgentNotificationResponseOnce, threadDeepLinkOnScreen } from "./notificationPayload";
6
import { consumeLastAgentNotificationResponse } from "./notificationResponseConsumer";
7
10
-export function useAgentNotificationNavigation(pathname: string): void {
11
- const linkTo = useLinkTo();
12
- const handledResponseIds = useRef(new Set<string>());
13
- const deepLinkOnScreen = useRef<string | null>(null);
14
- useLayoutEffect(() => {
15
- const thread = threadDeepLinkOnScreen(pathname);
16
- deepLinkOnScreen.current = thread;
17
- setAndroidThreadOnScreen(thread);
18
- }, [pathname]);
8
+let deepLinkOnScreen: string | null = null;
9
20
- useEffect(() => {
21
- Notifications.setNotificationHandler({
22
- handleNotification: (notification) =>
23
- Promise.resolve(foregroundNotificationBehavior(notification, deepLinkOnScreen.current)),
24
- });
25
- return () => {
26
- Notifications.setNotificationHandler(null);
27
- };
28
- }, []);
10
+/** Called with the workspace pathname on every root navigation state change. */
11
+export function setAgentNotificationPathname(pathname: string): void {
12
+ deepLinkOnScreen = threadDeepLinkOnScreen(pathname);
13
+ setAndroidThreadOnScreen(deepLinkOnScreen);
14
+}
15
30
- useEffect(() => {
31
- const handleResponse = (response: Notifications.NotificationResponse): void => {
32
- routeAgentNotificationResponseOnce({
33
- handledResponseIds: handledResponseIds.current,
34
- response,
35
- navigate: linkTo,
36
- });
37
- };
16
+/**
17
+ * App-lifetime notification routing: foreground presentation suppresses the
18
+ * thread already on screen, and taps (including the cold-start tap) open the
19
+ * notification's deep link through `navigate`.
20
+ */
21
+export function installAgentNotificationNavigation(navigate: (href: string) => void): () => void {
22
+ const handledResponseIds = new Set<string>();
23
+ Notifications.setNotificationHandler({
24
+ handleNotification: (notification) =>
25
+ Promise.resolve(foregroundNotificationBehavior(notification, deepLinkOnScreen)),
26
+ });
27
39
- const subscription = Notifications.addNotificationResponseReceivedListener(handleResponse);
40
- void consumeLastAgentNotificationResponse({
41
- getLastResponse: () => Notifications.getLastNotificationResponseAsync(),
42
- clearLastResponse: () => Notifications.clearLastNotificationResponseAsync(),
43
- handleResponse,
44
- });
28
+ const handleResponse = (response: Notifications.NotificationResponse): void => {
29
+ routeAgentNotificationResponseOnce({ handledResponseIds, response, navigate });
30
+ };
31
+ const subscription = Notifications.addNotificationResponseReceivedListener(handleResponse);
32
+ void consumeLastAgentNotificationResponse({
33
+ getLastResponse: () => Notifications.getLastNotificationResponseAsync(),
34
+ clearLastResponse: () => Notifications.clearLastNotificationResponseAsync(),
35
+ handleResponse,
36
+ });
37
46
- return () => {
47
- subscription.remove();
48
- };
49
- }, [linkTo]);
38
+ return () => {
39
+ subscription.remove();
40
+ Notifications.setNotificationHandler(null);
41
+ };
42
}
apps/mobile/src/features/cloud/connectOnboarding.test.ts
new
+74
@@ -0,0 +1,74 @@
1
+import { afterEach, describe, expect, it, vi } from "vite-plus/test";
2
+
3
+const navigation = vi.hoisted(() => ({
4
+ navigate: vi.fn(),
5
+ ready: true,
6
+ queue: [] as Array<() => void>,
7
+}));
8
+const optOut = vi.hoisted(() => ({ optedOut: new Set<string>() }));
9
+
10
+vi.mock("../../lib/rootNavigation", () => ({
11
+ rootNavigationRef: navigation,
12
+ whenRootNavigationReady: (navigate: () => void) =>
13
+ navigation.ready ? navigate() : navigation.queue.push(navigate),
14
+}));
15
+vi.mock("./connectOnboardingOptOut", () => ({
16
+ isConnectOnboardingOptedOut: (accountId: string) =>
17
+ Promise.resolve(optOut.optedOut.has(accountId)),
18
+}));
19
+
20
+import { clearConnectOnboardingRequest, requestConnectOnboarding } from "./connectOnboarding";
21
+
22
+afterEach(() => {
23
+ clearConnectOnboardingRequest();
24
+ optOut.optedOut.clear();
25
+ navigation.navigate.mockReset();
26
+ navigation.ready = true;
27
+ navigation.queue.length = 0;
28
+ vi.useRealTimers();
29
+});
30
+
31
+describe("requestConnectOnboarding", () => {
32
+ it("presents the sheet after the settle delay", async () => {
33
+ vi.useFakeTimers();
34
+ requestConnectOnboarding("account-1");
35
+ await vi.advanceTimersByTimeAsync(599);
36
+ expect(navigation.navigate).not.toHaveBeenCalled();
37
+ await vi.advanceTimersByTimeAsync(1);
38
+ expect(navigation.navigate).toHaveBeenCalledExactlyOnceWith("ConnectOnboarding");
39
+ });
40
+
41
+ it("drops a request cleared by sign-out before it fires", async () => {
42
+ vi.useFakeTimers();
43
+ requestConnectOnboarding("account-1");
44
+ clearConnectOnboardingRequest();
45
+ await vi.runAllTimersAsync();
46
+ expect(navigation.navigate).not.toHaveBeenCalled();
47
+ });
48
+
49
+ it("skips accounts that opted out", async () => {
50
+ vi.useFakeTimers();
51
+ optOut.optedOut.add("account-1");
52
+ requestConnectOnboarding("account-1");
53
+ await vi.runAllTimersAsync();
54
+ expect(navigation.navigate).not.toHaveBeenCalled();
55
+ });
56
+
57
+ it("presents once when a newer request replaces a pending one", async () => {
58
+ vi.useFakeTimers();
59
+ requestConnectOnboarding("account-1");
60
+ requestConnectOnboarding("account-2");
61
+ await vi.runAllTimersAsync();
62
+ expect(navigation.navigate).toHaveBeenCalledOnce();
63
+ });
64
+
65
+ it("drops a request cleared while it waits for navigation to be ready", async () => {
66
+ vi.useFakeTimers();
67
+ navigation.ready = false;
68
+ requestConnectOnboarding("account-1");
69
+ await vi.runAllTimersAsync();
70
+ clearConnectOnboardingRequest();
71
+ for (const navigate of navigation.queue.splice(0)) navigate();
72
+ expect(navigation.navigate).not.toHaveBeenCalled();
73
+ });
74
+});
apps/mobile/src/features/cloud/connectOnboarding.ts
+37
-8
@@ -1,17 +1,46 @@
1
-import { Atom } from "effect/reactivity";
1
+import { rootNavigationRef, whenRootNavigationReady } from "../../lib/rootNavigation";
2
+import { isConnectOnboardingOptedOut } from "./connectOnboardingOptOut";
3
3
-import { appAtomRegistry } from "../../state/atom-registry";
4
+// Sign-in happens in its own modal; give its session-state transition a beat to
5
+// settle before presenting another formSheet on top.
6
+const PRESENT_ONBOARDING_DELAY_MS = 600;
7
+
8
+interface PendingRequest {
9
+ readonly accountId: string;
10
+ readonly timer: ReturnType<typeof setTimeout>;
11
+}
12
13
// Retain the account id so sign-out cannot present onboarding for the wrong account.
6
-export const connectOnboardingRequestAtom = Atom.make<string | null>(null).pipe(
7
- Atom.keepAlive,
8
- Atom.withLabel("mobile:connect-onboarding-request"),
9
-);
14
+let pending: PendingRequest | null = null;
15
16
export function requestConnectOnboarding(accountId: string): void {
12
- appAtomRegistry.set(connectOnboardingRequestAtom, accountId);
17
+ clearConnectOnboardingRequest();
18
+ const request: PendingRequest = {
19
+ accountId,
20
+ timer: setTimeout(() => {
21
+ void (async () => {
22
+ const optedOut = await isConnectOnboardingOptedOut(accountId).catch(() => false);
23
+ // A sign-out or a newer sign-in may have replaced this request while
24
+ // the opt-out read was in flight.
25
+ if (pending !== request) return;
26
+ if (optedOut) {
27
+ pending = null;
28
+ return;
29
+ }
30
+ // Stays pending until navigation is ready, so a sign-out meanwhile still cancels it.
31
+ whenRootNavigationReady(() => {
32
+ if (pending !== request) return;
33
+ pending = null;
34
+ rootNavigationRef.navigate("ConnectOnboarding");
35
+ });
36
+ })();
37
+ }, PRESENT_ONBOARDING_DELAY_MS),
38
+ };
39
+ pending = request;
40
}
41
42
export function clearConnectOnboardingRequest(): void {
16
- appAtomRegistry.set(connectOnboardingRequestAtom, null);
43
+ if (pending === null) return;
44
+ clearTimeout(pending.timer);
45
+ pending = null;
46
}
apps/mobile/src/features/cloud/connectOnboardingNavigation.ts
deleted
-41
@@ -1,41 +0,0 @@
1
-import { useAtomValue } from "@effect/atom-react";
2
-import { useNavigation } from "@react-navigation/native";
3
-import { useEffect } from "react";
4
-
5
-import { appAtomRegistry } from "../../state/atom-registry";
6
-import { clearConnectOnboardingRequest, connectOnboardingRequestAtom } from "./connectOnboarding";
7
-import { isConnectOnboardingOptedOut } from "./connectOnboardingOptOut";
8
-
9
-// Sign-in happens in its own modal; give its session-state transition a beat to
10
-// settle before presenting another formSheet on top.
11
-const PRESENT_ONBOARDING_DELAY_MS = 600;
12
-
13
-/** Keep @react-navigation out of non-navigation consumers' import graphs. */
14
-export function useConnectOnboardingNavigation(): void {
15
- const navigation = useNavigation();
16
- const requestedAccountId = useAtomValue(connectOnboardingRequestAtom);
17
-
18
- useEffect(() => {
19
- if (requestedAccountId === null) {
20
- return;
21
- }
22
- let cancelled = false;
23
- const timer = setTimeout(() => {
24
- void (async () => {
25
- const optedOut = await isConnectOnboardingOptedOut(requestedAccountId).catch(() => false);
26
- // Re-check the request atom: sign-out can clear it before this render commits.
27
- if (cancelled || appAtomRegistry.get(connectOnboardingRequestAtom) !== requestedAccountId) {
28
- return;
29
- }
30
- clearConnectOnboardingRequest();
31
- if (!optedOut) {
32
- navigation.navigate("ConnectOnboarding");
33
- }
34
- })();
35
- }, PRESENT_ONBOARDING_DELAY_MS);
36
- return () => {
37
- cancelled = true;
38
- clearTimeout(timer);
39
- };
40
- }, [navigation, requestedAccountId]);
41
-}
apps/mobile/src/features/cloud/connectOnboardingOptOut.ts
+3
-1
@@ -1,6 +1,8 @@
1
import { loadPreferences, updatePreferences } from "../../persistence/imperative";
2
3
-// Keep persistence out of CloudAuthProvider's import graph; it breaks suite loading.
3
+// Lives apart from connectOnboarding.ts so cloudAccountService.ts (which
4
+// imports the request signal) never pulls the persistence adapter into its
5
+// module graph; that breaks CloudAuthProvider.test.ts suite loading.
6
7
export async function isConnectOnboardingOptedOut(accountId: string): Promise<boolean> {
8
const preferences = await loadPreferences();
apps/mobile/src/features/home/home-route-visibility.ts
+46
-28
@@ -1,41 +1,59 @@
1
import { RegistryContext } from "@effect/atom-react";
2
import { useNavigation } from "@react-navigation/native";
3
-import type { NativeStackNavigationProp } from "@react-navigation/native-stack";
4
-import { useCallback, useContext, useEffect, useRef, useState, useSyncExternalStore } from "react";
3
+import { useContext, useRef, useSyncExternalStore } from "react";
4
import type { Atom } from "effect/reactivity";
5
7
-/** Fabric never freezes the route below focus; Home must stop its own work beneath Thread. */
6
+/**
7
+ * Home stays mounted under a pushed Thread, and native-stack never freezes the
8
+ * route directly below the focused one on Fabric, so Home has to stop its own
9
+ * work. The Home screen's static `listeners` (Stack.tsx) drive this store.
10
+ */
11
+let homeVisible: boolean | null = null;
12
+const visibilityListeners = new Set<() => void>();
13
+
14
+function setHomeVisible(next: boolean) {
15
+ if (next === homeVisible) return;
16
+ homeVisible = next;
17
+ for (const listener of visibilityListeners) listener();
18
+}
19
+
20
+function subscribeHomeVisibility(onChange: () => void) {
21
+ visibilityListeners.add(onChange);
22
+ return () => {
23
+ visibilityListeners.delete(onChange);
24
+ // The value describes one Home instance. A later Home can mount under a
25
+ // Thread with no event of its own (Android activity replacement, a cold
26
+ // deep link), so it must fall back to `isFocused()` instead of this one.
27
+ if (visibilityListeners.size === 0) homeVisible = null;
28
+ };
29
+}
30
+
31
+export function recordHomeTransitionStart(closing: boolean): void {
32
+ if (!closing) setHomeVisible(true);
33
+}
34
+
35
+export function recordHomeTransitionEnd(closing: boolean): void {
36
+ if (closing) setHomeVisible(false);
37
+}
38
+
39
+/** Popping a sheet or a deep-linked route above Home has no appear event. */
40
+export function recordHomeFocus(): void {
41
+ setHomeVisible(true);
42
+}
43
+
44
export function useHomeRouteVisible(): boolean {
9
- const navigation =
10
- useNavigation<NativeStackNavigationProp<ReactNavigation.RootParamList, "Home">>();
11
- // A cold deep link mounts Home under its Thread without ever showing it.
12
- const [visible, setVisible] = useState(() => navigation.isFocused());
13
- useEffect(() => {
14
- const show = () => setVisible(true);
15
- const removeTransitionStart = navigation.addListener("transitionStart", ({ data }) => {
16
- if (!data.closing) show();
17
- });
18
- const removeTransitionEnd = navigation.addListener("transitionEnd", ({ data }) => {
19
- if (data.closing) setVisible(false);
20
- });
21
- // Popping a sheet or a deep-linked route above Home has no appear event.
22
- const removeFocus = navigation.addListener("focus", show);
23
- return () => {
24
- removeTransitionStart();
25
- removeTransitionEnd();
26
- removeFocus();
27
- };
28
- }, [navigation]);
29
- return visible;
45
+ const navigation = useNavigation();
46
+ const visible = useSyncExternalStore(subscribeHomeVisibility, () => homeVisible);
47
+ // Before Home's first navigation event: a cold deep link mounts Home under
48
+ // its Thread without ever showing it.
49
+ return visible ?? navigation.isFocused();
50
}
51
52
export function useAtomValueWhileVisible<A>(atom: Atom.Atom<A>, visible: boolean): A {
53
const registry = useContext(RegistryContext);
54
const held = useRef<{ readonly value: A } | null>(null);
35
- const subscribe = useCallback(
36
- (onChange: () => void) => (visible ? registry.subscribe(atom, onChange) : () => undefined),
37
- [registry, atom, visible],
38
- );
55
+ const subscribe = (onChange: () => void) =>
56
+ visible ? registry.subscribe(atom, onChange) : () => undefined;
57
return useSyncExternalStore(subscribe, () => {
58
if (visible || held.current === null) held.current = { value: registry.get(atom) };
59
return held.current.value;
apps/mobile/src/features/shortcuts/appShortcutsRuntime.test.ts
new
+70
@@ -0,0 +1,70 @@
1
+import { describe, expect, it, vi } from "vite-plus/test";
2
+
3
+vi.mock("expo-quick-actions", () => ({}));
4
+vi.mock("react-native", () => ({ Platform: { OS: "android" } }));
5
+vi.mock("../../persistence/imperative", () => ({}));
6
+vi.mock("../../state/atom-registry", () => ({}));
7
+vi.mock("../../state/threads", () => ({ environmentThreadShells: {} }));
8
+vi.mock("./appShortcuts", async () => {
9
+ const { withRecentThreadShortcut } =
10
+ await vi.importActual<typeof import("./appShortcuts")>("./appShortcuts");
11
+ return { withRecentThreadShortcut };
12
+});
13
+
14
+import type { RecentThreadShortcut } from "../../persistence/imperative";
15
+import { createRecentThreadShortcuts } from "./appShortcutsRuntime";
16
+
17
+const thread = (threadId: string, title = threadId): RecentThreadShortcut => ({
18
+ environmentId: "env",
19
+ threadId,
20
+ title,
21
+});
22
+
23
+function setup(load: () => Promise<ReadonlyArray<RecentThreadShortcut>>) {
24
+ const save = vi.fn<(list: ReadonlyArray<RecentThreadShortcut>) => Promise<void>>(() =>
25
+ Promise.resolve(),
26
+ );
27
+ const publish = vi.fn<(list: ReadonlyArray<RecentThreadShortcut>) => Promise<void>>(() =>
28
+ Promise.resolve(),
29
+ );
30
+ return { save, publish, recents: createRecentThreadShortcuts({ load, save, publish }) };
31
+}
32
+
33
+describe("createRecentThreadShortcuts", () => {
34
+ it("waits for the persisted list before recording the open thread", async () => {
35
+ const { save, publish, recents } = setup(() => Promise.resolve([thread("old")]));
36
+ recents.recordActiveThread(thread("new"));
37
+ expect(publish).not.toHaveBeenCalled();
38
+ await recents.loaded;
39
+ await recents.saved();
40
+ expect(publish).toHaveBeenLastCalledWith([thread("new"), thread("old")]);
41
+ expect(save).toHaveBeenLastCalledWith([thread("new"), thread("old")]);
42
+ });
43
+
44
+ it("does not persist the empty fallback after a failed load", async () => {
45
+ using _warn = vi.spyOn(console, "warn").mockImplementation(() => undefined);
46
+ const { save, publish, recents } = setup(() => Promise.reject(new Error("read failed")));
47
+ await recents.loaded;
48
+ await recents.saved();
49
+ expect(publish).toHaveBeenLastCalledWith([]);
50
+ expect(save).not.toHaveBeenCalled();
51
+
52
+ recents.recordActiveThread(thread("a"));
53
+ await recents.saved();
54
+ expect(save).toHaveBeenLastCalledWith([thread("a")]);
55
+ });
56
+
57
+ it("records title changes of the open thread and ignores repeats", async () => {
58
+ const { publish, recents } = setup(() => Promise.resolve([]));
59
+ await recents.loaded;
60
+ recents.recordActiveThread(thread("a", ""));
61
+ recents.recordActiveThread(thread("a", "Named"));
62
+ recents.recordActiveThread(thread("a", "Named"));
63
+ recents.recordActiveThread(null);
64
+ expect(publish.mock.calls.map(([list]) => list)).toEqual([
65
+ [],
66
+ [thread("a", "")],
67
+ [thread("a", "Named")],
68
+ ]);
69
+ });
70
+});
apps/mobile/src/features/shortcuts/appShortcutsRuntime.ts
new
+149
@@ -0,0 +1,149 @@
1
+import * as QuickActions from "expo-quick-actions";
2
+import { Platform } from "react-native";
3
+import type { NavigationState } from "@react-navigation/native";
4
+import type { ScopedThreadRef } from "@t3tools/contracts";
5
+import { Atom } from "effect/reactivity";
6
+
7
+import {
8
+ loadRecentThreadShortcuts,
9
+ saveRecentThreadShortcuts,
10
+ type RecentThreadShortcut,
11
+} from "../../persistence/imperative";
12
+import { appAtomRegistry } from "../../state/atom-registry";
13
+import { environmentThreadShells } from "../../state/threads";
14
+import {
15
+ activeThreadRef,
16
+ buildShortcutActions,
17
+ shortcutHref,
18
+ withRecentThreadShortcut,
19
+} from "./appShortcuts";
20
+
21
+export interface RecentThreadShortcutsDependencies {
22
+ readonly load: () => Promise<ReadonlyArray<RecentThreadShortcut>>;
23
+ readonly save: (recents: ReadonlyArray<RecentThreadShortcut>) => Promise<void>;
24
+ readonly publish: (recents: ReadonlyArray<RecentThreadShortcut>) => Promise<void>;
25
+}
26
+
27
+/**
28
+ * Keeps the launcher's recent-thread list. Recording waits for the persisted
29
+ * list so the first thread opened after a cold start cannot clobber older
30
+ * entries, and a failed load never persists its empty fallback over valid
31
+ * history until a real thread open makes the in-memory list the new truth.
32
+ */
33
+export function createRecentThreadShortcuts(dependencies: RecentThreadShortcutsDependencies) {
34
+ let recents: ReadonlyArray<RecentThreadShortcut> | null = null;
35
+ let persistable = false;
36
+ let active: RecentThreadShortcut | null = null;
37
+ // Serialize saves so older lists cannot overwrite newer ones.
38
+ let saveQueue: Promise<unknown> = Promise.resolve();
39
+
40
+ const commit = (next: ReadonlyArray<RecentThreadShortcut>) => {
41
+ recents = next;
42
+ if (persistable) {
43
+ saveQueue = saveQueue.then(
44
+ () =>
45
+ dependencies.save(next).catch((error: unknown) => {
46
+ console.warn("[app-shortcuts] failed to persist recent threads", error);
47
+ }),
48
+ () => undefined,
49
+ );
50
+ }
51
+ void dependencies.publish(next).catch((error: unknown) => {
52
+ console.warn("[app-shortcuts] failed to update launcher shortcuts", error);
53
+ });
54
+ };
55
+
56
+ const withActive = (list: ReadonlyArray<RecentThreadShortcut>) => {
57
+ if (active === null) return list;
58
+ const next = withRecentThreadShortcut(list, active);
59
+ if (next !== list) persistable = true;
60
+ return next;
61
+ };
62
+
63
+ const loaded = dependencies.load().then(
64
+ (threads) => {
65
+ persistable = true;
66
+ commit(withActive(threads));
67
+ },
68
+ (error: unknown) => {
69
+ console.warn("[app-shortcuts] failed to load recent threads", error);
70
+ commit(withActive([]));
71
+ },
72
+ );
73
+
74
+ return {
75
+ loaded,
76
+ /** Resolves once every save issued so far has finished. */
77
+ saved: () => saveQueue,
78
+ recordActiveThread(next: RecentThreadShortcut | null): void {
79
+ active = next;
80
+ if (recents === null || next === null) return;
81
+ const updated = withActive(recents);
82
+ if (updated !== recents) commit(updated);
83
+ },
84
+ };
85
+}
86
+
87
+const activeThreadRefAtom = Atom.make<ScopedThreadRef | null>(null).pipe(
88
+ Atom.keepAlive,
89
+ Atom.withLabel("mobile:app-shortcuts-active-thread-ref"),
90
+);
91
+
92
+const activeThreadShortcutAtom = Atom.make((get): RecentThreadShortcut | null => {
93
+ const ref = get(activeThreadRefAtom);
94
+ if (ref === null) return null;
95
+ const title = get(environmentThreadShells.threadShellAtom(ref))?.title ?? "";
96
+ return { environmentId: ref.environmentId, threadId: ref.threadId, title };
97
+}).pipe(
98
+ Atom.withEquality(
99
+ (left: RecentThreadShortcut | null, right: RecentThreadShortcut | null) =>
100
+ left === right ||
101
+ (left !== null &&
102
+ right !== null &&
103
+ left.environmentId === right.environmentId &&
104
+ left.threadId === right.threadId &&
105
+ left.title === right.title),
106
+ ),
107
+);
108
+
109
+/** Wired to the root navigation container's state changes. */
110
+export function recordAppShortcutNavigationState(state: NavigationState): void {
111
+ // Launcher shortcuts are Android-only; iOS never subscribes to thread shells.
112
+ if (Platform.OS !== "android") return;
113
+ const next = activeThreadRef(state);
114
+ const current = appAtomRegistry.get(activeThreadRefAtom);
115
+ if (next?.environmentId === current?.environmentId && next?.threadId === current?.threadId) {
116
+ return;
117
+ }
118
+ appAtomRegistry.set(activeThreadRefAtom, next);
119
+}
120
+
121
+/**
122
+ * App-lifetime quick actions. `navigate` must queue until navigation is ready:
123
+ * a cold-start shortcut arrives as the launch action, and pushing it over the
124
+ * initial Home route makes back return home instead of exiting the app.
125
+ */
126
+export function installAppShortcuts(navigate: (href: string) => void): () => void {
127
+ const initialHref = QuickActions.initial ? shortcutHref(QuickActions.initial) : null;
128
+ if (initialHref !== null) navigate(initialHref);
129
+ const subscription = QuickActions.addListener((action) => {
130
+ const href = shortcutHref(action);
131
+ if (href !== null) navigate(href);
132
+ });
133
+ if (Platform.OS !== "android") return () => subscription.remove();
134
+
135
+ const recents = createRecentThreadShortcuts({
136
+ load: loadRecentThreadShortcuts,
137
+ save: saveRecentThreadShortcuts,
138
+ publish: (list) => QuickActions.setItems(buildShortcutActions(list)),
139
+ });
140
+ const unsubscribe = appAtomRegistry.subscribe(
141
+ activeThreadShortcutAtom,
142
+ (active) => recents.recordActiveThread(active),
143
+ { immediate: true },
144
+ );
145
+ return () => {
146
+ subscription.remove();
147
+ unsubscribe();
148
+ };
149
+}
apps/mobile/src/features/shortcuts/useAppShortcuts.ts
deleted
-125
@@ -1,125 +0,0 @@
1
-import * as QuickActions from "expo-quick-actions";
2
-import { useEffect, useMemo, useRef, useState } from "react";
3
-import { Platform } from "react-native";
4
-import { useLinkTo, type NavigationState } from "@react-navigation/native";
5
-
6
-import {
7
- loadRecentThreadShortcuts,
8
- saveRecentThreadShortcuts,
9
- type RecentThreadShortcut,
10
-} from "../../persistence/imperative";
11
-import { useThreadShell } from "../../state/entities";
12
-import {
13
- activeThreadRef,
14
- buildShortcutActions,
15
- shortcutHref,
16
- withRecentThreadShortcut,
17
-} from "./appShortcuts";
18
-
19
-export function useAppShortcuts(state: NavigationState): void {
20
- useShortcutNavigation();
21
- useRecentThreadShortcutSync(state);
22
-}
23
-
24
-function useShortcutNavigation(): void {
25
- const linkTo = useLinkTo();
26
- const handledInitialAction = useRef(false);
27
-
28
- useEffect(() => {
29
- // Handle the launch action before listeners; push over Home so Back returns there.
30
- if (!handledInitialAction.current) {
31
- handledInitialAction.current = true;
32
- const initialHref = QuickActions.initial ? shortcutHref(QuickActions.initial) : null;
33
- if (initialHref !== null) {
34
- linkTo(initialHref);
35
- }
36
- }
37
-
38
- const subscription = QuickActions.addListener((action) => {
39
- const href = shortcutHref(action);
40
- if (href !== null) {
41
- linkTo(href);
42
- }
43
- });
44
- return () => subscription.remove();
45
- }, [linkTo]);
46
-}
47
-
48
-function useRecentThreadShortcutSync(state: NavigationState): void {
49
- // iOS subscriptions for Android-only shortcuts would re-render every screen on active-thread updates.
50
- const threadRef = useMemo(
51
- () => (Platform.OS === "android" ? activeThreadRef(state) : null),
52
- [state],
53
- );
54
- const threadShell = useThreadShell(threadRef);
55
- // Wait for persisted recents before recording visits, or cold starts overwrite older entries.
56
- const [recents, setRecents] = useState<ReadonlyArray<RecentThreadShortcut> | null>(null);
57
- // Do not persist failed-load fallbacks; only a real visit makes the list authoritative.
58
- const persistableRef = useRef(false);
59
- // Serialize saves so older lists cannot overwrite newer ones.
60
- const saveQueueRef = useRef<Promise<unknown>>(Promise.resolve());
61
-
62
- useEffect(() => {
63
- if (Platform.OS !== "android") {
64
- return;
65
- }
66
-
67
- let cancelled = false;
68
- void loadRecentThreadShortcuts()
69
- .then((threads) => {
70
- if (!cancelled) {
71
- persistableRef.current = true;
72
- setRecents(threads);
73
- }
74
- })
75
- .catch((error) => {
76
- console.warn("[app-shortcuts] failed to load recent threads", error);
77
- if (!cancelled) {
78
- setRecents([]);
79
- }
80
- });
81
- return () => {
82
- cancelled = true;
83
- };
84
- }, []);
85
-
86
- const loaded = recents !== null;
87
- const environmentId = threadRef?.environmentId ?? null;
88
- const threadId = threadRef?.threadId ?? null;
89
- const title = threadShell?.title ?? "";
90
- useEffect(() => {
91
- if (!loaded || environmentId === null || threadId === null) {
92
- return;
93
- }
94
-
95
- setRecents((current) => {
96
- if (current === null) {
97
- return current;
98
- }
99
- const next = withRecentThreadShortcut(current, { environmentId, threadId, title });
100
- if (next !== current) {
101
- persistableRef.current = true;
102
- }
103
- return next;
104
- });
105
- }, [loaded, environmentId, threadId, title]);
106
-
107
- useEffect(() => {
108
- if (recents === null) {
109
- return;
110
- }
111
-
112
- if (persistableRef.current) {
113
- saveQueueRef.current = saveQueueRef.current.then(
114
- () =>
115
- saveRecentThreadShortcuts(recents).catch((error) => {
116
- console.warn("[app-shortcuts] failed to persist recent threads", error);
117
- }),
118
- () => undefined,
119
- );
120
- }
121
- void QuickActions.setItems(buildShortcutActions(recents)).catch((error) => {
122
- console.warn("[app-shortcuts] failed to update launcher shortcuts", error);
123
- });
124
- }, [recents]);
125
-}
apps/mobile/src/lib/rootNavigation.test.ts
+51
-1
@@ -7,10 +7,21 @@ vi.mock("@react-navigation/native", () => ({
7
isReady() {
8
return this.current?.isReady() ?? false;
9
},
10
+ dispatched: [] as Array<unknown>,
11
+ dispatch(action: unknown) {
12
+ this.dispatched.push(action);
13
+ },
14
+ getRootState: () => ({ key: "root" }),
15
}),
16
}));
17
13
-const { attachRootNavigation, rootNavigationRef } = await import("./rootNavigation");
18
+const {
19
+ attachRootNavigation,
20
+ flushRootNavigationQueue,
21
+ linkToRootPath,
22
+ rootNavigationRef,
23
+ whenRootNavigationReady,
24
+} = await import("./rootNavigation");
25
26
function fakeContainer() {
27
return { isReady: () => true } as NavigationContainerRef<ReactNavigation.RootParamList>;
@@ -29,3 +40,42 @@ it("keeps the newer container when an older root unmounts after it attached", ()
40
detachCurrent();
41
expect(rootNavigationRef.current).toBeNull();
42
});
43
+
44
+it("holds navigation until the container is ready, then runs it once", () => {
45
+ const navigate = vi.fn();
46
+ const failing = vi.fn(() => {
47
+ throw new Error("unknown route");
48
+ });
49
+ const logged = vi.spyOn(console, "error").mockImplementation(() => undefined);
50
+ whenRootNavigationReady(failing);
51
+ whenRootNavigationReady(navigate);
52
+ expect(navigate).not.toHaveBeenCalled();
53
+
54
+ const detach = attachRootNavigation(fakeContainer());
55
+ flushRootNavigationQueue();
56
+ flushRootNavigationQueue();
57
+ expect(failing).toHaveBeenCalledOnce();
58
+ expect(navigate).toHaveBeenCalledOnce();
59
+ expect(logged).toHaveBeenCalledOnce();
60
+
61
+ whenRootNavigationReady(navigate);
62
+ expect(navigate).toHaveBeenCalledTimes(2);
63
+ detach();
64
+ logged.mockRestore();
65
+});
66
+
67
+it("rejects an href without a leading slash, as useLinkTo does", () => {
68
+ const toAction = vi.fn(() => ({ type: "NAVIGATE" }));
69
+ const detach = attachRootNavigation(fakeContainer());
70
+ const { dispatched } = rootNavigationRef as unknown as { dispatched: Array<unknown> };
71
+
72
+ expect(() => linkToRootPath("threads/env/t1", toAction)).toThrow(
73
+ "The href must start with '/' (threads/env/t1).",
74
+ );
75
+ expect(toAction).not.toHaveBeenCalled();
76
+
77
+ linkToRootPath("/threads/env/t1", toAction);
78
+ expect(toAction).toHaveBeenCalledExactlyOnceWith("/threads/env/t1");
79
+ expect(dispatched).toEqual([{ target: "root", type: "NAVIGATE" }]);
80
+ detach();
81
+});
apps/mobile/src/lib/rootNavigation.ts
+39
-1
@@ -1,11 +1,13 @@
1
import {
2
createNavigationContainerRef,
3
+ type NavigationAction,
4
type NavigationContainerRef,
5
} from "@react-navigation/native";
6
7
/**
8
* The app's single navigation container. Work that outlives a screen (a draft
8
- * route's branch checkout) navigates through it.
9
+ * route's branch checkout, notification taps, quick actions, Connect
10
+ * onboarding) navigates through it instead of mounting hooks in the navigator.
11
*/
12
export const rootNavigationRef = createNavigationContainerRef<ReactNavigation.RootParamList>();
13
@@ -22,3 +24,39 @@ export function attachRootNavigation(
24
if (rootNavigationRef.current === navigation) rootNavigationRef.current = null;
25
};
26
}
27
+
28
+const pendingUntilReady: Array<() => void> = [];
29
+
30
+/** Runs `navigate` now if the container is ready, otherwise once it becomes ready. */
31
+export function whenRootNavigationReady(navigate: () => void): void {
32
+ if (rootNavigationRef.isReady()) {
33
+ navigate();
34
+ return;
35
+ }
36
+ pendingUntilReady.push(navigate);
37
+}
38
+
39
+/** Wired to the container's `onReady`. */
40
+export function flushRootNavigationQueue(): void {
41
+ for (const navigate of pendingUntilReady.splice(0)) {
42
+ try {
43
+ navigate();
44
+ } catch (error) {
45
+ console.error("[navigation] queued navigation failed", error);
46
+ }
47
+ }
48
+}
49
+
50
+/**
51
+ * `useLinkTo` for app services that live outside the navigator: the same
52
+ * leading-'/' guard, then the href's action dispatched at the root once ready.
53
+ */
54
+export function linkToRootPath(href: string, toAction: (href: string) => NavigationAction): void {
55
+ if (!href.startsWith("/")) throw new Error(`The href must start with '/' (${href}).`);
56
+ whenRootNavigationReady(() => {
57
+ rootNavigationRef.dispatch({
58
+ target: rootNavigationRef.getRootState()?.key,
59
+ ...toAction(href),
60
+ });
61
+ });
62
+}
scripts/effect-budget.json
-1
@@ -88,7 +88,6 @@
88
"apps/mobile/src/features/settings/components/BranchNamingSettings.tsx": 1,
89
"apps/mobile/src/features/settings/components/SettingsLegalDocumentRouteScreen.tsx": 1,
90
"apps/mobile/src/features/sharing/IncomingShareProvider.tsx": 4,
91
- "apps/mobile/src/features/shortcuts/useAppShortcuts.ts": 4,
91
"apps/mobile/src/features/showcase/ShowcaseCaptureCoordinator.tsx": 11,
92
"apps/mobile/src/features/terminal/NativeTerminalSurface.tsx": 4,
93
"apps/mobile/src/features/terminal/ThreadTerminalRouteScreen.tsx": 14,