@devries-cameron20 / t3code-1 / commits / 2ad853ab21
Fork 0

The best way to control Claude Code, Codex and more from any computer or phone

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

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>

Julius Marminge committed Oct 26, 2026 at 23:03 UTC 2ad853ab211935a414cdf3c2f5004db635ae04bc
6 files changed +209 -193
apps/mobile/src/App.tsx
+13 -10
@@ -21,7 +21,10 @@ import { ThreadArrangementHost } from "./features/threads/ThreadArrangementSheet
21 import * as Dialog from "./components/ui/Dialog";
22 import { CloudAuthProvider } from "./features/cloud/CloudAuthProvider";
23 import { prepareNativeShowcaseCapture } from "./features/showcase/nativeShowcaseScene";
24 -import { IncomingShareProvider } from "./features/sharing/IncomingShareProvider";
24 +import {
25 + presentPendingIncomingShare,
26 + startIncomingShareInbox,
27 +} from "./features/sharing/IncomingShareProvider";
28 import {
29 AppearancePreferencesProvider,
30 installAppearanceRuntime,
@@ -92,6 +95,7 @@ const Navigation = createStaticNavigation(RootStack);
95 function handleNavigationStateChange(state: NavigationState | undefined): void {
96 recordWorkspaceSelections(state);
97 if (state) pruneNewTaskBranchCheckouts(state);
98 + presentPendingIncomingShare();
99 }
100
101 function handleNavigationReady(): void {
@@ -113,6 +117,7 @@ const appServiceDisposers = [
117 installPermissionUpdateNotice(),
118 installThreadOutboxDelivery(),
119 installComposerAttachmentUploads(),
120 + startIncomingShareInbox(),
121 ];
122 disposeOnFoundationReplace(typeof module === "undefined" ? undefined : module.hot, () => {
123 for (const dispose of appServiceDisposers) dispose();
@@ -155,15 +160,13 @@ function AppContent() {
160 {/* native-stack needs the theme's dark flag to select dark native headers. */}
161 <GlobalVoiceInputControl>
162 <NativeLayoutMetricsProvider>
158 - <IncomingShareProvider>
159 - <Navigation
160 - ref={attachRootNavigation}
161 - linking={appLinking}
162 - onReady={handleNavigationReady}
163 - theme={navigationTheme}
164 - onStateChange={handleNavigationStateChange}
165 - />
166 - </IncomingShareProvider>
163 + <Navigation
164 + ref={attachRootNavigation}
165 + linking={appLinking}
166 + onReady={handleNavigationReady}
167 + theme={navigationTheme}
168 + onStateChange={handleNavigationStateChange}
169 + />
170 <Dialog.Host />
171 <ThreadArrangementHost />
172 <ProjectChipIconRasterizer />
apps/mobile/src/Stack.tsx
+2 -29
@@ -15,7 +15,7 @@ import {
15 createNativeStackScreen,
16 type NativeStackNavigationOptions,
17 } from "@react-navigation/native-stack";
18 -import { useEffect, useRef, type ReactNode } from "react";
18 +import type { ReactNode } from "react";
19 import { Platform, Pressable, ScrollView, StyleSheet, useWindowDimensions } from "react-native";
20 import { useResolveClassNames } from "uniwind";
21
@@ -139,20 +139,12 @@ import {
139 SettingsLegalDocumentExternalHeaderButton,
140 } from "./features/settings/components/SettingsLegalDocumentRouteScreen";
141 import { useAppShortcuts } from "./features/shortcuts/useAppShortcuts";
142 -import { useIncomingShare } from "./features/sharing/IncomingShareProvider";
143 -import {
144 - EMPTY_INCOMING_SHARE_PRESENTATION_STATE,
145 - transitionIncomingSharePresentation,
146 -} from "./features/sharing/incoming-share-presentation";
142 import { NATIVE_LIQUID_GLASS_SUPPORTED } from "./native/native-glass";
143 import { deriveLayout } from "./lib/layout";
144 import { useNativeLayoutMetrics } from "./native/native-layout-metrics";
145 import { nativeHeaderScrollEdgeEffects } from "./native/StackHeader";
146 import { HORIZONTAL_FORM_SHEET_OPTIONS, formSheetDetents } from "./native/sheet-surface";
152 -import {
153 - selectWorkspaceDetail,
154 - workspaceDetailRouter,
155 -} from "./features/workspace/workspace-detail-selection";
147 +import { workspaceDetailRouter } from "./features/workspace/workspace-detail-selection";
148
149 const HEADER_SCROLL_EDGE_EFFECTS = nativeHeaderScrollEdgeEffects(Platform.OS, Platform.Version);
150
@@ -498,9 +490,6 @@ function RootStackLayout(props: {
490 readonly children: React.ReactNode;
491 readonly state: NavigationState;
492 }) {
501 - const navigation = useNavigation();
502 - const { pendingShare } = useIncomingShare();
503 - const sharePresentationRef = useRef(EMPTY_INCOMING_SHARE_PRESENTATION_STATE);
493 const path = getPathFromState(props.state, navigationPathConfig);
494 const pathname = path.startsWith("/") ? path : `/${path}`;
495 const workspaceLocation = workspaceLocationFromState(props.state);
@@ -519,22 +508,6 @@ function RootStackLayout(props: {
508 useAgentNotificationNavigation(workspaceLocation.pathname);
509 useConnectOnboardingNavigation();
510 useAppShortcuts(props.state);
522 - useEffect(() => {
523 - const transition = transitionIncomingSharePresentation(sharePresentationRef.current, {
524 - isShareSheetPresented: isDraftThreadRoute(props.state.routes[props.state.index]),
525 - pendingShareId: pendingShare?.id ?? null,
526 - });
527 - sharePresentationRef.current = transition.state;
528 - if (!transition.shareIdToPresent) {
529 - return;
530 - }
531 - navigation.dispatch(
532 - selectWorkspaceDetail({
533 - name: "Thread",
534 - params: { draft: { incomingShareId: transition.shareIdToPresent } },
535 - }),
536 - );
537 - }, [navigation, pendingShare, props.state]);
511
512 return (
513 <NewTaskFlowProvider active={isDraftThreadRoute(draftRoute)} routeDraftId={routeDraftId}>
apps/mobile/src/features/sharing/IncomingShareProvider.tsx
+103 -154
@@ -9,8 +9,8 @@ import {
9 type ResolvedSharePayload,
10 type SharePayload,
11 } from "expo-sharing";
12 -import React, { useCallback, useEffect, useEffectEvent, useMemo, useRef, useState } from "react";
13 -import { AppState, Platform } from "react-native";
12 +import { useSyncExternalStore } from "react";
13 +import { Platform } from "react-native";
14
15 import {
16 buildIncomingShareDraft,
@@ -21,28 +21,21 @@ import {
21 import { createIncomingSharePayloadReader } from "./incoming-share-native";
22 import { IncomingShareInbox } from "./incoming-share-inbox";
23 import { persistComposerAttachmentFile } from "../../lib/composerImages";
24 +import { subscribeAppActive } from "../../lib/appState";
25 +import { coalescedRun } from "../../lib/coalescedRun";
26 +import { rootNavigationRef } from "../../lib/rootNavigation";
27 +import { selectWorkspaceDetail } from "../workspace/workspace-detail-selection";
28 +import { isDraftThreadRoute } from "../threads/thread-route-state";
29 +import {
30 + EMPTY_INCOMING_SHARE_PRESENTATION_STATE,
31 + transitionIncomingSharePresentation,
32 +} from "./incoming-share-presentation";
33 import {
34 loadIncomingShareDrafts,
35 removeIncomingShareDraft,
36 writeIncomingShareDraft,
37 } from "./incoming-share-storage";
38
30 -type IncomingShareContextValue = {
31 - readonly pendingShare: IncomingShareDraft | null;
32 - readonly isLoading: boolean;
33 - readonly error: Error | null;
34 - readonly getShare: (shareId: string) => IncomingShareDraft | null;
35 - readonly reserveShare: (shareId: string, destination: IncomingShareDestination) => Promise<void>;
36 - readonly releaseShareReservation: (
37 - shareId: string,
38 - expectedDestination: IncomingShareDestination,
39 - ) => Promise<void>;
40 - readonly consumeShare: (shareId: string) => Promise<void>;
41 - readonly refresh: () => Promise<void>;
42 -};
43 -
44 -const IncomingShareContext = React.createContext<IncomingShareContextValue | null>(null);
45 -
39 function receiveSharingEnabled(): boolean {
40 if (Platform.OS === "android") {
41 return true;
@@ -197,153 +190,109 @@ const incomingShareInbox = new IncomingShareInbox({
190 },
191 });
192
200 -export function IncomingShareProvider(props: React.PropsWithChildren) {
201 - const enabled = receiveSharingEnabled();
202 - const [drafts, setDrafts] = useState<ReadonlyArray<IncomingShareDraft>>([]);
203 - const [isLoading, setIsLoading] = useState(true);
204 - const [error, setError] = useState<Error | null>(null);
205 - const refreshPromiseRef = useRef<Promise<void> | null>(null);
206 - const mountedRef = useRef(false);
193 +interface IncomingShareSnapshot {
194 + readonly drafts: ReadonlyArray<IncomingShareDraft>;
195 + readonly isLoading: boolean;
196 +}
197
208 - useEffect(() => {
209 - mountedRef.current = true;
210 - return () => {
211 - mountedRef.current = false;
212 - };
213 - }, []);
198 +let snapshot: IncomingShareSnapshot = { drafts: [], isLoading: true };
199 +const snapshotListeners = new Set<() => void>();
200 +let presentation = EMPTY_INCOMING_SHARE_PRESENTATION_STATE;
201
215 - const refresh = useCallback(async () => {
216 - if (refreshPromiseRef.current) {
217 - return refreshPromiseRef.current;
218 - }
202 +function publish(drafts: ReadonlyArray<IncomingShareDraft>) {
203 + snapshot = { drafts, isLoading: false };
204 + for (const listener of snapshotListeners) listener();
205 + presentPendingIncomingShare();
206 +}
207
220 - const operation = (async () => {
221 - try {
222 - const snapshot = await incomingShareInbox.refresh({ ingestNative: enabled });
223 - if (mountedRef.current) {
224 - setDrafts(snapshot);
225 - setError(null);
226 - }
227 - } catch (cause) {
228 - const persisted = await incomingShareInbox
229 - .refresh({ ingestNative: false })
230 - .catch(() => null);
231 - if (mountedRef.current) {
232 - if (persisted) {
233 - setDrafts(persisted);
234 - }
235 - setError(cause instanceof Error ? cause : new Error("Could not import shared content."));
236 - }
237 - }
238 - })().finally(() => {
239 - refreshPromiseRef.current = null;
240 - });
208 +function subscribeIncomingShares(onChange: () => void) {
209 + snapshotListeners.add(onChange);
210 + return () => {
211 + snapshotListeners.delete(onChange);
212 + };
213 +}
214
242 - refreshPromiseRef.current = operation;
243 - return operation;
244 - }, [enabled]);
215 +function getIncomingShareSnapshot() {
216 + return snapshot;
217 +}
218
246 - useEffect(() => {
247 - void refresh().finally(() => {
248 - if (mountedRef.current) {
249 - setIsLoading(false);
250 - }
251 - });
252 - }, [refresh]);
219 +function reportRefreshFailure(cause: unknown) {
220 + const error = cause instanceof Error ? cause : new Error("Could not import shared content.");
221 + Dialog.alert("Could not import shared content", error.message, [
222 + { text: "Dismiss", style: "cancel" },
223 + { text: "Retry", onPress: () => void refreshIncomingShares() },
224 + ]);
225 +}
226
254 - const refreshOnAppActive = useEffectEvent(() => {
255 - void refresh();
256 - });
227 +// A resume while a refresh runs may carry a native handoff that refresh already
228 +// passed, so it queues one more refresh instead of joining the running one.
229 +const refreshIncomingShares = coalescedRun(async () => {
230 + const enabled = receiveSharingEnabled();
231 + try {
232 + publish(await incomingShareInbox.refresh({ ingestNative: enabled }));
233 + } catch (cause) {
234 + const persisted = await incomingShareInbox.refresh({ ingestNative: false }).catch(() => null);
235 + publish(persisted ?? snapshot.drafts);
236 + reportRefreshFailure(cause);
237 + }
238 +});
239
258 - useEffect(() => {
259 - if (!enabled) {
260 - return;
261 - }
262 - const subscription = AppState.addEventListener("change", (state) => {
263 - if (state === "active") {
264 - refreshOnAppActive();
265 - }
266 - });
267 - return () => subscription.remove();
268 - }, [enabled]);
240 +/**
241 + * Opens the oldest pending share as a new-task draft unless the user already
242 + * dismissed it. Runs whenever the inbox or the root navigation state changes.
243 + */
244 +export function presentPendingIncomingShare(): void {
245 + if (!rootNavigationRef.isReady()) return;
246 + const state = rootNavigationRef.getRootState();
247 + if (!state) return;
248 + const transition = transitionIncomingSharePresentation(presentation, {
249 + isShareSheetPresented: isDraftThreadRoute(state.routes[state.index]),
250 + pendingShareId: snapshot.drafts[0]?.id ?? null,
251 + });
252 + presentation = transition.state;
253 + if (!transition.shareIdToPresent) return;
254 + rootNavigationRef.dispatch(
255 + selectWorkspaceDetail({
256 + name: "Thread",
257 + params: { draft: { incomingShareId: transition.shareIdToPresent } },
258 + }),
259 + );
260 +}
261
270 - useEffect(() => {
271 - if (!error) {
272 - return;
273 - }
274 - Dialog.alert("Could not import shared content", error.message, [
275 - { text: "Dismiss", style: "cancel", onPress: () => setError(null) },
276 - {
277 - text: "Retry",
278 - onPress: () => {
279 - setError(null);
280 - void refresh();
281 - },
282 - },
283 - ]);
284 - }, [error, refresh]);
262 +/** App-lifetime: loads the inbox and re-ingests native handoffs on every resume. */
263 +export function startIncomingShareInbox(): () => void {
264 + void refreshIncomingShares();
265 + return receiveSharingEnabled()
266 + ? subscribeAppActive(() => void refreshIncomingShares())
267 + : () => {};
268 +}
269
286 - const consumeShare = useCallback(async (shareId: string) => {
287 - const snapshot = await incomingShareInbox.consume(shareId);
288 - if (mountedRef.current) {
289 - setDrafts(snapshot);
290 - }
291 - }, []);
292 - const reserveShare = useCallback(
293 - async (shareId: string, destination: IncomingShareDestination) => {
294 - const snapshot = await incomingShareInbox.reserve(shareId, destination);
295 - if (mountedRef.current) {
296 - setDrafts(snapshot);
297 - }
298 - },
299 - [],
300 - );
301 - const releaseShareReservation = useCallback(
302 - async (shareId: string, expectedDestination: IncomingShareDestination) => {
303 - const snapshot = await incomingShareInbox.releaseReservation(shareId, expectedDestination);
304 - if (mountedRef.current) {
305 - setDrafts(snapshot);
306 - }
307 - },
308 - [],
309 - );
310 - const getShare = useCallback(
311 - (shareId: string) => drafts.find((draft) => draft.id === shareId) ?? null,
312 - [drafts],
313 - );
270 +async function consumeShare(shareId: string) {
271 + publish(await incomingShareInbox.consume(shareId));
272 +}
273
315 - const value = useMemo<IncomingShareContextValue>(
316 - () => ({
317 - pendingShare: drafts[0] ?? null,
318 - isLoading,
319 - error,
320 - getShare,
321 - releaseShareReservation,
322 - reserveShare,
323 - consumeShare,
324 - refresh,
325 - }),
326 - [
327 - consumeShare,
328 - drafts,
329 - error,
330 - getShare,
331 - isLoading,
332 - refresh,
333 - releaseShareReservation,
334 - reserveShare,
335 - ],
336 - );
274 +async function reserveShare(shareId: string, destination: IncomingShareDestination) {
275 + publish(await incomingShareInbox.reserve(shareId, destination));
276 +}
277
338 - return (
339 - <IncomingShareContext.Provider value={value}>{props.children}</IncomingShareContext.Provider>
340 - );
278 +async function releaseShareReservation(
279 + shareId: string,
280 + expectedDestination: IncomingShareDestination,
281 +) {
282 + publish(await incomingShareInbox.releaseReservation(shareId, expectedDestination));
283 }
284
343 -export function useIncomingShare(): IncomingShareContextValue {
344 - const value = React.use(IncomingShareContext);
345 - if (value === null) {
346 - throw new Error("useIncomingShare must be used within IncomingShareProvider.");
347 - }
348 - return value;
285 +export function useIncomingShare() {
286 + const { drafts, isLoading } = useSyncExternalStore(
287 + subscribeIncomingShares,
288 + getIncomingShareSnapshot,
289 + );
290 + return {
291 + pendingShare: drafts[0] ?? null,
292 + isLoading,
293 + getShare: (shareId: string) => drafts.find((draft) => draft.id === shareId) ?? null,
294 + reserveShare,
295 + releaseShareReservation,
296 + consumeShare,
297 + };
298 }
apps/mobile/src/lib/appState.ts
+8
@@ -12,6 +12,14 @@ export function isAppActive(): boolean {
12 return AppState.currentState === "active";
13 }
14
15 +/** Runs `onActive` each time the app returns to the foreground. */
16 +export function subscribeAppActive(onActive: Listener): () => void {
17 + const subscription = AppState.addEventListener("change", (state) => {
18 + if (state === "active") onActive();
19 + });
20 + return () => subscription.remove();
21 +}
22 +
23 export function useAppActive(): boolean {
24 return useSyncExternalStore(subscribeAppState, isAppActive);
25 }
apps/mobile/src/lib/coalescedRun.test.ts new
+57
@@ -0,0 +1,57 @@
1 +import { describe, expect, it, vi } from "vite-plus/test";
2 +
3 +import { coalescedRun } from "./coalescedRun";
4 +
5 +function deferredRuns() {
6 + const runs: Array<PromiseWithResolvers<void>> = [];
7 + const run = () => {
8 + const next = Promise.withResolvers<void>();
9 + runs.push(next);
10 + return next.promise;
11 + };
12 + return { runs, run };
13 +}
14 +
15 +describe("coalescedRun", () => {
16 + it("queues one more run for calls made while a run is in flight", async () => {
17 + const { runs, run } = deferredRuns();
18 + const refresh = coalescedRun(run);
19 +
20 + const first = refresh();
21 + const second = refresh();
22 + const third = refresh();
23 + expect(third).toBe(second);
24 + expect(runs).toHaveLength(1);
25 +
26 + runs[0]!.resolve();
27 + await first;
28 + await vi.waitFor(() => expect(runs).toHaveLength(2));
29 +
30 + runs[1]!.resolve();
31 + await second;
32 + expect(runs).toHaveLength(2);
33 + });
34 +
35 + it("hands a queued run's failure to the call that asked for it", async () => {
36 + const { runs, run } = deferredRuns();
37 + const refresh = coalescedRun(run);
38 +
39 + const first = refresh();
40 + const second = refresh();
41 + runs[0]!.resolve();
42 + await first;
43 + await vi.waitFor(() => expect(runs).toHaveLength(2));
44 + runs[1]!.reject(new Error("read failed"));
45 + await expect(second).rejects.toThrow("read failed");
46 + });
47 +
48 + it("runs once per call when calls do not overlap", async () => {
49 + let count = 0;
50 + const refresh = coalescedRun(async () => {
51 + count += 1;
52 + });
53 + await refresh();
54 + await refresh();
55 + expect(count).toBe(2);
56 + });
57 +});
apps/mobile/src/lib/coalescedRun.ts new
+26
@@ -0,0 +1,26 @@
1 +/**
2 + * Runs `run` at most once at a time. A call made while a run is in flight
3 + * queues one more run after it and returns that queued run, so input that
4 + * arrives mid-run (a native share handed over on resume) is still read, and
5 + * the caller that asked for it sees how it ended.
6 + */
7 +export function coalescedRun(run: () => Promise<void>): () => Promise<void> {
8 + let inFlight: Promise<void> | null = null;
9 + let queued: Promise<void> | null = null;
10 + const start = (): Promise<void> => {
11 + if (inFlight) {
12 + queued ??= inFlight
13 + .catch(() => undefined)
14 + .then(() => {
15 + queued = null;
16 + return start();
17 + });
18 + return queued;
19 + }
20 + inFlight = run().finally(() => {
21 + inFlight = null;
22 + });
23 + return inFlight;
24 + };
25 + return start;
26 +}