Skip to content
TypeScript

refactor(mobile): notifications, quick actions and Connect onboarding navigate through the root ref (#25769)

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