Skip to content
TypeScript

refactor(mobile): the share inbox is a module store, presented from navigation state (#25744)

Julius Marminge2ad853ab2119
diff --git a/apps/mobile/src/App.tsx b/apps/mobile/src/App.tsx
index 3ade5d940fd..579aea37bfa 100644
--- a/apps/mobile/src/App.tsx
+++ b/apps/mobile/src/App.tsx
@@ -21,7 +21,10 @@ import { ThreadArrangementHost } from "./features/threads/ThreadArrangementSheet
import * as Dialog from "./components/ui/Dialog";
import { CloudAuthProvider } from "./features/cloud/CloudAuthProvider";
import { prepareNativeShowcaseCapture } from "./features/showcase/nativeShowcaseScene";
-import { IncomingShareProvider } from "./features/sharing/IncomingShareProvider";
+import {
+ presentPendingIncomingShare,
+ startIncomingShareInbox,
+} from "./features/sharing/IncomingShareProvider";
import {
AppearancePreferencesProvider,
installAppearanceRuntime,
@@ -92,6 +95,7 @@ const Navigation = createStaticNavigation(RootStack);
function handleNavigationStateChange(state: NavigationState | undefined): void {
recordWorkspaceSelections(state);
if (state) pruneNewTaskBranchCheckouts(state);
+ presentPendingIncomingShare();
}
function handleNavigationReady(): void {
@@ -113,6 +117,7 @@ const appServiceDisposers = [
installPermissionUpdateNotice(),
installThreadOutboxDelivery(),
installComposerAttachmentUploads(),
+ startIncomingShareInbox(),
];
disposeOnFoundationReplace(typeof module === "undefined" ? undefined : module.hot, () => {
for (const dispose of appServiceDisposers) dispose();
@@ -155,15 +160,13 @@ function AppContent() {
{/* native-stack needs the theme's dark flag to select dark native headers. */}
<GlobalVoiceInputControl>
<NativeLayoutMetricsProvider>
- <IncomingShareProvider>
- <Navigation
- ref={attachRootNavigation}
- linking={appLinking}
- onReady={handleNavigationReady}
- theme={navigationTheme}
- onStateChange={handleNavigationStateChange}
- />
- </IncomingShareProvider>
+ <Navigation
+ ref={attachRootNavigation}
+ linking={appLinking}
+ onReady={handleNavigationReady}
+ theme={navigationTheme}
+ onStateChange={handleNavigationStateChange}
+ />
<Dialog.Host />
<ThreadArrangementHost />
<ProjectChipIconRasterizer />
diff --git a/apps/mobile/src/Stack.tsx b/apps/mobile/src/Stack.tsx
index 74a8600f1e3..7312807c55e 100644
--- a/apps/mobile/src/Stack.tsx
+++ b/apps/mobile/src/Stack.tsx
@@ -15,7 +15,7 @@ import {
createNativeStackScreen,
type NativeStackNavigationOptions,
} from "@react-navigation/native-stack";
-import { useEffect, useRef, type ReactNode } from "react";
+import type { ReactNode } from "react";
import { Platform, Pressable, ScrollView, StyleSheet, useWindowDimensions } from "react-native";
import { useResolveClassNames } from "uniwind";
@@ -139,20 +139,12 @@ import {
SettingsLegalDocumentExternalHeaderButton,
} from "./features/settings/components/SettingsLegalDocumentRouteScreen";
import { useAppShortcuts } from "./features/shortcuts/useAppShortcuts";
-import { useIncomingShare } from "./features/sharing/IncomingShareProvider";
-import {
- EMPTY_INCOMING_SHARE_PRESENTATION_STATE,
- transitionIncomingSharePresentation,
-} from "./features/sharing/incoming-share-presentation";
import { NATIVE_LIQUID_GLASS_SUPPORTED } from "./native/native-glass";
import { deriveLayout } from "./lib/layout";
import { useNativeLayoutMetrics } from "./native/native-layout-metrics";
import { nativeHeaderScrollEdgeEffects } from "./native/StackHeader";
import { HORIZONTAL_FORM_SHEET_OPTIONS, formSheetDetents } from "./native/sheet-surface";
-import {
- selectWorkspaceDetail,
- workspaceDetailRouter,
-} from "./features/workspace/workspace-detail-selection";
+import { workspaceDetailRouter } from "./features/workspace/workspace-detail-selection";
const HEADER_SCROLL_EDGE_EFFECTS = nativeHeaderScrollEdgeEffects(Platform.OS, Platform.Version);
@@ -498,9 +490,6 @@ function RootStackLayout(props: {
readonly children: React.ReactNode;
readonly state: NavigationState;
}) {
- const navigation = useNavigation();
- const { pendingShare } = useIncomingShare();
- const sharePresentationRef = useRef(EMPTY_INCOMING_SHARE_PRESENTATION_STATE);
const path = getPathFromState(props.state, navigationPathConfig);
const pathname = path.startsWith("/") ? path : `/${path}`;
const workspaceLocation = workspaceLocationFromState(props.state);
@@ -519,22 +508,6 @@ function RootStackLayout(props: {
useAgentNotificationNavigation(workspaceLocation.pathname);
useConnectOnboardingNavigation();
useAppShortcuts(props.state);
- useEffect(() => {
- const transition = transitionIncomingSharePresentation(sharePresentationRef.current, {
- isShareSheetPresented: isDraftThreadRoute(props.state.routes[props.state.index]),
- pendingShareId: pendingShare?.id ?? null,
- });
- sharePresentationRef.current = transition.state;
- if (!transition.shareIdToPresent) {
- return;
- }
- navigation.dispatch(
- selectWorkspaceDetail({
- name: "Thread",
- params: { draft: { incomingShareId: transition.shareIdToPresent } },
- }),
- );
- }, [navigation, pendingShare, props.state]);
return (
<NewTaskFlowProvider active={isDraftThreadRoute(draftRoute)} routeDraftId={routeDraftId}>
diff --git a/apps/mobile/src/features/sharing/IncomingShareProvider.tsx b/apps/mobile/src/features/sharing/IncomingShareProvider.tsx
index 62425e49af6..23b34d362be 100644
--- a/apps/mobile/src/features/sharing/IncomingShareProvider.tsx
+++ b/apps/mobile/src/features/sharing/IncomingShareProvider.tsx
@@ -9,8 +9,8 @@ import {
type ResolvedSharePayload,
type SharePayload,
} from "expo-sharing";
-import React, { useCallback, useEffect, useEffectEvent, useMemo, useRef, useState } from "react";
-import { AppState, Platform } from "react-native";
+import { useSyncExternalStore } from "react";
+import { Platform } from "react-native";
import {
buildIncomingShareDraft,
@@ -21,28 +21,21 @@ import {
import { createIncomingSharePayloadReader } from "./incoming-share-native";
import { IncomingShareInbox } from "./incoming-share-inbox";
import { persistComposerAttachmentFile } from "../../lib/composerImages";
+import { subscribeAppActive } from "../../lib/appState";
+import { coalescedRun } from "../../lib/coalescedRun";
+import { rootNavigationRef } from "../../lib/rootNavigation";
+import { selectWorkspaceDetail } from "../workspace/workspace-detail-selection";
+import { isDraftThreadRoute } from "../threads/thread-route-state";
+import {
+ EMPTY_INCOMING_SHARE_PRESENTATION_STATE,
+ transitionIncomingSharePresentation,
+} from "./incoming-share-presentation";
import {
loadIncomingShareDrafts,
removeIncomingShareDraft,
writeIncomingShareDraft,
} from "./incoming-share-storage";
-type IncomingShareContextValue = {
- readonly pendingShare: IncomingShareDraft | null;
- readonly isLoading: boolean;
- readonly error: Error | null;
- readonly getShare: (shareId: string) => IncomingShareDraft | null;
- readonly reserveShare: (shareId: string, destination: IncomingShareDestination) => Promise<void>;
- readonly releaseShareReservation: (
- shareId: string,
- expectedDestination: IncomingShareDestination,
- ) => Promise<void>;
- readonly consumeShare: (shareId: string) => Promise<void>;
- readonly refresh: () => Promise<void>;
-};
-
-const IncomingShareContext = React.createContext<IncomingShareContextValue | null>(null);
-
function receiveSharingEnabled(): boolean {
if (Platform.OS === "android") {
return true;
@@ -197,153 +190,109 @@ const incomingShareInbox = new IncomingShareInbox({
},
});
-export function IncomingShareProvider(props: React.PropsWithChildren) {
- const enabled = receiveSharingEnabled();
- const [drafts, setDrafts] = useState<ReadonlyArray<IncomingShareDraft>>([]);
- const [isLoading, setIsLoading] = useState(true);
- const [error, setError] = useState<Error | null>(null);
- const refreshPromiseRef = useRef<Promise<void> | null>(null);
- const mountedRef = useRef(false);
+interface IncomingShareSnapshot {
+ readonly drafts: ReadonlyArray<IncomingShareDraft>;
+ readonly isLoading: boolean;
+}
- useEffect(() => {
- mountedRef.current = true;
- return () => {
- mountedRef.current = false;
- };
- }, []);
+let snapshot: IncomingShareSnapshot = { drafts: [], isLoading: true };
+const snapshotListeners = new Set<() => void>();
+let presentation = EMPTY_INCOMING_SHARE_PRESENTATION_STATE;
- const refresh = useCallback(async () => {
- if (refreshPromiseRef.current) {
- return refreshPromiseRef.current;
- }
+function publish(drafts: ReadonlyArray<IncomingShareDraft>) {
+ snapshot = { drafts, isLoading: false };
+ for (const listener of snapshotListeners) listener();
+ presentPendingIncomingShare();
+}
- const operation = (async () => {
- try {
- const snapshot = await incomingShareInbox.refresh({ ingestNative: enabled });
- if (mountedRef.current) {
- setDrafts(snapshot);
- setError(null);
- }
- } catch (cause) {
- const persisted = await incomingShareInbox
- .refresh({ ingestNative: false })
- .catch(() => null);
- if (mountedRef.current) {
- if (persisted) {
- setDrafts(persisted);
- }
- setError(cause instanceof Error ? cause : new Error("Could not import shared content."));
- }
- }
- })().finally(() => {
- refreshPromiseRef.current = null;
- });
+function subscribeIncomingShares(onChange: () => void) {
+ snapshotListeners.add(onChange);
+ return () => {
+ snapshotListeners.delete(onChange);
+ };
+}
- refreshPromiseRef.current = operation;
- return operation;
- }, [enabled]);
+function getIncomingShareSnapshot() {
+ return snapshot;
+}
- useEffect(() => {
- void refresh().finally(() => {
- if (mountedRef.current) {
- setIsLoading(false);
- }
- });
- }, [refresh]);
+function reportRefreshFailure(cause: unknown) {
+ const error = cause instanceof Error ? cause : new Error("Could not import shared content.");
+ Dialog.alert("Could not import shared content", error.message, [
+ { text: "Dismiss", style: "cancel" },
+ { text: "Retry", onPress: () => void refreshIncomingShares() },
+ ]);
+}
- const refreshOnAppActive = useEffectEvent(() => {
- void refresh();
- });
+// A resume while a refresh runs may carry a native handoff that refresh already
+// passed, so it queues one more refresh instead of joining the running one.
+const refreshIncomingShares = coalescedRun(async () => {
+ const enabled = receiveSharingEnabled();
+ try {
+ publish(await incomingShareInbox.refresh({ ingestNative: enabled }));
+ } catch (cause) {
+ const persisted = await incomingShareInbox.refresh({ ingestNative: false }).catch(() => null);
+ publish(persisted ?? snapshot.drafts);
+ reportRefreshFailure(cause);
+ }
+});
- useEffect(() => {
- if (!enabled) {
- return;
- }
- const subscription = AppState.addEventListener("change", (state) => {
- if (state === "active") {
- refreshOnAppActive();
- }
- });
- return () => subscription.remove();
- }, [enabled]);
+/**
+ * Opens the oldest pending share as a new-task draft unless the user already
+ * dismissed it. Runs whenever the inbox or the root navigation state changes.
+ */
+export function presentPendingIncomingShare(): void {
+ if (!rootNavigationRef.isReady()) return;
+ const state = rootNavigationRef.getRootState();
+ if (!state) return;
+ const transition = transitionIncomingSharePresentation(presentation, {
+ isShareSheetPresented: isDraftThreadRoute(state.routes[state.index]),
+ pendingShareId: snapshot.drafts[0]?.id ?? null,
+ });
+ presentation = transition.state;
+ if (!transition.shareIdToPresent) return;
+ rootNavigationRef.dispatch(
+ selectWorkspaceDetail({
+ name: "Thread",
+ params: { draft: { incomingShareId: transition.shareIdToPresent } },
+ }),
+ );
+}
- useEffect(() => {
- if (!error) {
- return;
- }
- Dialog.alert("Could not import shared content", error.message, [
- { text: "Dismiss", style: "cancel", onPress: () => setError(null) },
- {
- text: "Retry",
- onPress: () => {
- setError(null);
- void refresh();
- },
- },
- ]);
- }, [error, refresh]);
+/** App-lifetime: loads the inbox and re-ingests native handoffs on every resume. */
+export function startIncomingShareInbox(): () => void {
+ void refreshIncomingShares();
+ return receiveSharingEnabled()
+ ? subscribeAppActive(() => void refreshIncomingShares())
+ : () => {};
+}
- const consumeShare = useCallback(async (shareId: string) => {
- const snapshot = await incomingShareInbox.consume(shareId);
- if (mountedRef.current) {
- setDrafts(snapshot);
- }
- }, []);
- const reserveShare = useCallback(
- async (shareId: string, destination: IncomingShareDestination) => {
- const snapshot = await incomingShareInbox.reserve(shareId, destination);
- if (mountedRef.current) {
- setDrafts(snapshot);
- }
- },
- [],
- );
- const releaseShareReservation = useCallback(
- async (shareId: string, expectedDestination: IncomingShareDestination) => {
- const snapshot = await incomingShareInbox.releaseReservation(shareId, expectedDestination);
- if (mountedRef.current) {
- setDrafts(snapshot);
- }
- },
- [],
- );
- const getShare = useCallback(
- (shareId: string) => drafts.find((draft) => draft.id === shareId) ?? null,
- [drafts],
- );
+async function consumeShare(shareId: string) {
+ publish(await incomingShareInbox.consume(shareId));
+}
- const value = useMemo<IncomingShareContextValue>(
- () => ({
- pendingShare: drafts[0] ?? null,
- isLoading,
- error,
- getShare,
- releaseShareReservation,
- reserveShare,
- consumeShare,
- refresh,
- }),
- [
- consumeShare,
- drafts,
- error,
- getShare,
- isLoading,
- refresh,
- releaseShareReservation,
- reserveShare,
- ],
- );
+async function reserveShare(shareId: string, destination: IncomingShareDestination) {
+ publish(await incomingShareInbox.reserve(shareId, destination));
+}
- return (
- <IncomingShareContext.Provider value={value}>{props.children}</IncomingShareContext.Provider>
- );
+async function releaseShareReservation(
+ shareId: string,
+ expectedDestination: IncomingShareDestination,
+) {
+ publish(await incomingShareInbox.releaseReservation(shareId, expectedDestination));
}
-export function useIncomingShare(): IncomingShareContextValue {
- const value = React.use(IncomingShareContext);
- if (value === null) {
- throw new Error("useIncomingShare must be used within IncomingShareProvider.");
- }
- return value;
+export function useIncomingShare() {
+ const { drafts, isLoading } = useSyncExternalStore(
+ subscribeIncomingShares,
+ getIncomingShareSnapshot,
+ );
+ return {
+ pendingShare: drafts[0] ?? null,
+ isLoading,
+ getShare: (shareId: string) => drafts.find((draft) => draft.id === shareId) ?? null,
+ reserveShare,
+ releaseShareReservation,
+ consumeShare,
+ };
}
diff --git a/apps/mobile/src/lib/appState.ts b/apps/mobile/src/lib/appState.ts
index e3c3cbc9337..8e1b5dfa9b4 100644
--- a/apps/mobile/src/lib/appState.ts
+++ b/apps/mobile/src/lib/appState.ts
@@ -12,6 +12,14 @@ export function isAppActive(): boolean {
return AppState.currentState === "active";
}
+/** Runs `onActive` each time the app returns to the foreground. */
+export function subscribeAppActive(onActive: Listener): () => void {
+ const subscription = AppState.addEventListener("change", (state) => {
+ if (state === "active") onActive();
+ });
+ return () => subscription.remove();
+}
+
export function useAppActive(): boolean {
return useSyncExternalStore(subscribeAppState, isAppActive);
}
diff --git a/apps/mobile/src/lib/coalescedRun.test.ts b/apps/mobile/src/lib/coalescedRun.test.ts
new file mode 100644
index 00000000000..b409da5d3c2
--- /dev/null
+++ b/apps/mobile/src/lib/coalescedRun.test.ts
@@ -0,0 +1,57 @@
+import { describe, expect, it, vi } from "vite-plus/test";
+
+import { coalescedRun } from "./coalescedRun";
+
+function deferredRuns() {
+ const runs: Array<PromiseWithResolvers<void>> = [];
+ const run = () => {
+ const next = Promise.withResolvers<void>();
+ runs.push(next);
+ return next.promise;
+ };
+ return { runs, run };
+}
+
+describe("coalescedRun", () => {
+ it("queues one more run for calls made while a run is in flight", async () => {
+ const { runs, run } = deferredRuns();
+ const refresh = coalescedRun(run);
+
+ const first = refresh();
+ const second = refresh();
+ const third = refresh();
+ expect(third).toBe(second);
+ expect(runs).toHaveLength(1);
+
+ runs[0]!.resolve();
+ await first;
+ await vi.waitFor(() => expect(runs).toHaveLength(2));
+
+ runs[1]!.resolve();
+ await second;
+ expect(runs).toHaveLength(2);
+ });
+
+ it("hands a queued run's failure to the call that asked for it", async () => {
+ const { runs, run } = deferredRuns();
+ const refresh = coalescedRun(run);
+
+ const first = refresh();
+ const second = refresh();
+ runs[0]!.resolve();
+ await first;
+ await vi.waitFor(() => expect(runs).toHaveLength(2));
+ runs[1]!.reject(new Error("read failed"));
+ await expect(second).rejects.toThrow("read failed");
+ });
+
+ it("runs once per call when calls do not overlap", async () => {
+ let count = 0;
+ const refresh = coalescedRun(async () => {
+ count += 1;
+ });
+ await refresh();
+ await refresh();
+ expect(count).toBe(2);
+ });
+});
diff --git a/apps/mobile/src/lib/coalescedRun.ts b/apps/mobile/src/lib/coalescedRun.ts
new file mode 100644
index 00000000000..72a32cc6865
--- /dev/null
+++ b/apps/mobile/src/lib/coalescedRun.ts
@@ -0,0 +1,26 @@
+/**
+ * Runs `run` at most once at a time. A call made while a run is in flight
+ * queues one more run after it and returns that queued run, so input that
+ * arrives mid-run (a native share handed over on resume) is still read, and
+ * the caller that asked for it sees how it ended.
+ */
+export function coalescedRun(run: () => Promise<void>): () => Promise<void> {
+ let inFlight: Promise<void> | null = null;
+ let queued: Promise<void> | null = null;
+ const start = (): Promise<void> => {
+ if (inFlight) {
+ queued ??= inFlight
+ .catch(() => undefined)
+ .then(() => {
+ queued = null;
+ return start();
+ });
+ return queued;
+ }
+ inFlight = run().finally(() => {
+ inFlight = null;
+ });
+ return inFlight;
+ };
+ return start;
+}