Open History to see the last commit
1import { errorDisplayMessage } from "@t3tools/client-runtime/errors";
2import * as Dialog from "../../components/ui/Dialog";
3import { m } from "../../i18n/messages";
4import Constants from "expo-constants";
5import * as Crypto from "expo-crypto";
6import { EnvironmentId, PROVIDER_SEND_TURN_MAX_FILE_BYTES } from "@t3tools/contracts";
7import {
8 clearSharedPayloads,
9 getResolvedSharedPayloadsAsync,
10 getSharedPayloads,
11 type ResolvedSharePayload,
12 type SharePayload,
13} from "expo-sharing";
14import { msg } from "gt-react-native";
15import { Atom } from "effect/reactivity";
16import { useSyncExternalStore } from "react";
17import { Platform } from "react-native";
18import { CommonActions } from "@react-navigation/native";
19
20import {
21 buildIncomingShareDraft,
22 isOwnedShareFileUri,
23 selectIncomingShareAttachmentsForServer,
24 type IncomingShareDestination,
25 type IncomingShareDraft,
26} from "./incoming-share-model";
27import { createIncomingSharePayloadReader } from "./incoming-share-native";
28import { IncomingShareInbox } from "./incoming-share-inbox";
29import { persistComposerAttachmentFile } from "../../lib/composerImages";
30import { subscribeAppActive } from "../../lib/appState";
31import { coalescedRun } from "../../lib/coalescedRun";
32import { rootNavigationRef } from "../../lib/rootNavigation";
33import { selectWorkspaceDetail } from "../layout/workspace/workspace-detail-selection";
34import { isDraftThreadRoute } from "../threads/thread-route-state";
35import { makeIncomingShareImports } from "../threads/incomingShareImport";
36import { liveNewTaskFlowKeys, newTaskFlowKey } from "../threads/new-task-flow-state";
37import { appAtomRegistry } from "../../state/atom-registry";
38import { serverEnvironment } from "../../state/server";
39import {
40 getComposerDraftSnapshot,
41 mergeComposerDraftContent,
42 scheduleUnusedComposerAttachmentCleanup,
43 undoComposerDraftMerge,
44} from "../../state/use-composer-drafts";
45import {
46 EMPTY_INCOMING_SHARE_PRESENTATION_STATE,
47 transitionIncomingSharePresentation,
48} from "./incoming-share-presentation";
49import {
50 loadIncomingShareDrafts,
51 removeIncomingShareDraft,
52 writeIncomingShareDraft,
53} from "./incoming-share-storage";
54
55function receiveSharingEnabled(): boolean {
56 if (Platform.OS === "android") {
57 return true;
58 }
59 if (Platform.OS !== "ios") {
60 return false;
61 }
62 return Constants.expoConfig?.extra?.iosPersonalTeamBuild !== true;
63}
64
65const getIncomingSharePayloads = createIncomingSharePayloadReader({
66 platform: Platform.OS,
67 readPayloads: getSharedPayloads,
68});
69
70async function resolvedPayloadsForFiles(): Promise<ReadonlyArray<ResolvedSharePayload>> {
71 try {
72 return await getResolvedSharedPayloadsAsync();
73 } catch (error) {
74 // Raw iOS copied file URLs remain usable; Android's File API can read content URIs when resolution fails.
75 console.warn("[incoming-share] could not resolve shared file metadata", error);
76 return [];
77 }
78}
79
80async function incomingShareIdForPayloads(payloads: ReadonlyArray<SharePayload>): Promise<string> {
81 const fingerprint = JSON.stringify(
82 payloads.map((payload) => ({
83 shareType: payload.shareType,
84 mimeType: payload.mimeType ?? null,
85 value: payload.value,
86 })),
87 );
88 const digest = await Crypto.digestStringAsync(Crypto.CryptoDigestAlgorithm.SHA256, fingerprint);
89 return `share-${digest}`;
90}
91
92async function readBase64(uri: string): Promise<string> {
93 const { File } = await import("expo-file-system");
94 return new File(uri).base64();
95}
96
97async function readFileSize(uri: string): Promise<number | null> {
98 const { File } = await import("expo-file-system");
99 return new File(uri).size ?? null;
100}
101
102/** `persisted` marks a copy this app saved itself, which needs no ownership check. */
103async function removeOwnedFile(uri: string, persisted = false): Promise<void> {
104 if (!uri.startsWith("file:")) {
105 return;
106 }
107 try {
108 const { File, Paths } = await import("expo-file-system");
109 // Delete only app-owned files; iOS open-in-place shares can reference the sender's original.
110 const owned =
111 persisted ||
112 isOwnedShareFileUri(uri, {
113 platform: Platform.OS,
114 cacheUri: Paths.cache.uri,
115 otherRootUris: [
116 Paths.document.uri,
117 ...Object.values(Paths.appleSharedContainers ?? {}).map((directory) => directory.uri),
118 ],
119 });
120 if (!owned) {
121 return;
122 }
123 const file = new File(uri);
124 if (file.exists) {
125 file.delete();
126 }
127 } catch (error) {
128 console.warn("[incoming-share] could not remove temporary shared file", error);
129 }
130}
131
132async function removeReplayedPayloadFiles(payloads: ReadonlyArray<SharePayload>): Promise<void> {
133 const uris = new Set<string>();
134 for (const payload of payloads) {
135 if (["image", "file", "audio", "video"].includes(payload.shareType)) {
136 uris.add(payload.value);
137 }
138 }
139 if (uris.size === 0) {
140 return;
141 }
142 const resolvedPayloads = payloads.some((payload) =>
143 ["file", "audio", "video"].includes(payload.shareType),
144 )
145 ? []
146 : await resolvedPayloadsForFiles();
147 for (const payload of resolvedPayloads) {
148 if (["image", "file", "audio", "video"].includes(payload.shareType) && payload.contentUri) {
149 uris.add(payload.contentUri);
150 }
151 }
152 await Promise.all([...uris].map((uri) => removeOwnedFile(uri)));
153}
154
155// Share the queue across remounts so lifecycle notifications cannot ingest one handoff twice.
156const incomingShareInbox = new IncomingShareInbox({
157 loadDrafts: loadIncomingShareDrafts,
158 writeDraft: writeIncomingShareDraft,
159 removeDraft: removeIncomingShareDraft,
160 getPayloads: getIncomingSharePayloads,
161 clearPayloads: clearSharedPayloads,
162 buildDraft: async ({ payloads, id, createdAt }) => {
163 const cleanupUris = new Set<string>();
164 const persistedUris = new Set<string>();
165 const hasGenericFilePayload = payloads.some((payload) =>
166 ["file", "audio", "video"].includes(payload.shareType),
167 );
168 const resolvedPayloads =
169 !hasGenericFilePayload && payloads.some((payload) => payload.shareType === "image")
170 ? await resolvedPayloadsForFiles()
171 : [];
172 const draft = await buildIncomingShareDraft({
173 payloads,
174 resolvedPayloads,
175 fileReader: {
176 readBase64,
177 persistFile: async (uri, name) => {
178 const persistedUri = await persistComposerAttachmentFile(
179 uri,
180 name,
181 PROVIDER_SEND_TURN_MAX_FILE_BYTES,
182 );
183 persistedUris.add(persistedUri);
184 return persistedUri;
185 },
186 readSize: readFileSize,
187 removeOwnedFile: (uri) => {
188 cleanupUris.add(uri);
189 },
190 },
191 id,
192 createdAt,
193 });
194 return {
195 draft,
196 cleanup: async () => {
197 await Promise.all(
198 [...cleanupUris].map((uri) => removeOwnedFile(uri, persistedUris.has(uri))),
199 );
200 },
201 rollback: async () => {
202 await Promise.all([...persistedUris].map((uri) => removeOwnedFile(uri, true)));
203 },
204 };
205 },
206 cleanupReplayedPayloads: removeReplayedPayloadFiles,
207 idForPayloads: incomingShareIdForPayloads,
208 now: () => new Date().toISOString(),
209 onClearError: (error) => {
210 console.warn("[incoming-share] could not acknowledge native payload", error);
211 },
212 onCleanupError: (error) => {
213 console.warn("[incoming-share] could not remove temporary shared file", error);
214 },
215});
216
217interface IncomingShareSnapshot {
218 readonly drafts: ReadonlyArray<IncomingShareDraft>;
219 readonly isLoading: boolean;
220}
221
222let snapshot: IncomingShareSnapshot = { drafts: [], isLoading: true };
223const snapshotListeners = new Set<() => void>();
224let presentation = EMPTY_INCOMING_SHARE_PRESENTATION_STATE;
225
226// A share that arrives while a new-task draft is on screen goes into that draft, by its flow key.
227const handedSharesAtom = Atom.make<Readonly<Record<string, string>>>({}).pipe(
228 Atom.keepAlive,
229 Atom.withLabel("mobile:incoming-share-handed"),
230);
231
232/** The share handed to the open draft of `flowKey`, if any. */
233export const handedShareIdAtom = Atom.family((flowKey: string) =>
234 Atom.make((get) => get(handedSharesAtom)[flowKey] ?? null).pipe(
235 Atom.withLabel("mobile:incoming-share-handed:flow"),
236 ),
237);
238
239export const noHandedShareIdAtom = Atom.make<string | null>(null).pipe(
240 Atom.withLabel("mobile:incoming-share-handed:none"),
241);
242
243function isPendingShare(shareId: string | undefined): boolean {
244 return shareId !== undefined && snapshot.drafts.some((draft) => draft.id === shareId);
245}
246
247/** Hands the oldest pending share to the draft on screen once that draft's own imports finished. */
248function handPendingShareToOpenDraft(route: { readonly key: string; readonly params?: object }) {
249 const pendingShareId = snapshot.drafts[0]?.id;
250 const flowKey = newTaskFlowKey(route);
251 if (pendingShareId === undefined || flowKey === undefined) return;
252 const draft = (route.params as { draft?: { incomingShareId?: string | string[] } }).draft;
253 const routeShareId = Array.isArray(draft?.incomingShareId)
254 ? draft.incomingShareId[0]
255 : draft?.incomingShareId;
256 const handed = appAtomRegistry.get(handedSharesAtom);
257 if (isPendingShare(routeShareId) || isPendingShare(handed[flowKey])) return;
258 if (Object.values(handed).includes(pendingShareId)) return;
259 appAtomRegistry.set(handedSharesAtom, { ...handed, [flowKey]: pendingShareId });
260}
261
262function publish(drafts: ReadonlyArray<IncomingShareDraft>) {
263 snapshot = { drafts, isLoading: false };
264 for (const listener of snapshotListeners) listener();
265 presentPendingIncomingShare();
266}
267
268function subscribeIncomingShares(onChange: () => void) {
269 snapshotListeners.add(onChange);
270 return () => {
271 snapshotListeners.delete(onChange);
272 };
273}
274
275function getIncomingShareSnapshot() {
276 return snapshot;
277}
278
279function reportRefreshFailure(cause: unknown) {
280 console.warn(
281 "[incoming-share] refresh failed",
282 cause,
283 cause instanceof Error ? cause.cause : null,
284 );
285 const error =
286 cause instanceof Error ? cause : new Error(m(msg("Could not import shared content.")));
287 Dialog.alert(m(msg("Could not import shared content")), error.message, [
288 { text: m(msg("Dismiss")), style: "cancel" },
289 { text: m(msg("Retry")), onPress: () => void refreshIncomingShares() },
290 ]);
291}
292
293// A resume while a refresh runs may carry a native handoff that refresh already
294// passed, so it queues one more refresh instead of joining the running one.
295const refreshIncomingShares = coalescedRun(async () => {
296 const enabled = receiveSharingEnabled();
297 try {
298 publish(await incomingShareInbox.refresh({ ingestNative: enabled }));
299 } catch (cause) {
300 const persisted = await incomingShareInbox.refresh({ ingestNative: false }).catch(() => null);
301 publish(persisted ?? snapshot.drafts);
302 reportRefreshFailure(cause);
303 }
304});
305
306/**
307 * Opens the oldest pending share as a new-task draft unless the user already
308 * dismissed it. Runs whenever the inbox or the root navigation state changes.
309 */
310export function presentPendingIncomingShare(): void {
311 if (!rootNavigationRef.isReady()) return;
312 const state = rootNavigationRef.getRootState();
313 if (!state) return;
314 const route = state.routes[state.index];
315 if (route && isDraftThreadRoute(route)) handPendingShareToOpenDraft(route);
316 const transition = transitionIncomingSharePresentation(presentation, {
317 isShareSheetPresented: isDraftThreadRoute(state.routes[state.index]),
318 pendingShareId: snapshot.drafts[0]?.id ?? null,
319 });
320 presentation = transition.state;
321 if (!transition.shareIdToPresent) return;
322 rootNavigationRef.dispatch(
323 selectWorkspaceDetail({
324 name: "Thread",
325 params: { draft: { incomingShareId: transition.shareIdToPresent } },
326 }),
327 );
328}
329
330/** App-lifetime: loads the inbox and re-ingests native handoffs on every resume. */
331export function startIncomingShareInbox(): () => void {
332 void refreshIncomingShares();
333 return receiveSharingEnabled()
334 ? subscribeAppActive(() => void refreshIncomingShares())
335 : () => {};
336}
337
338async function consumeShare(shareId: string) {
339 publish(await incomingShareInbox.consume(shareId));
340}
341
342async function reserveShare(shareId: string, destination: IncomingShareDestination) {
343 publish(await incomingShareInbox.reserve(shareId, destination));
344}
345
346async function releaseShareReservation(
347 shareId: string,
348 expectedDestination: IncomingShareDestination,
349) {
350 publish(await incomingShareInbox.releaseReservation(shareId, expectedDestination));
351}
352
353/** Moves shares into new-task drafts; see makeIncomingShareImports. */
354export const incomingShareImports = makeIncomingShareImports({
355 registry: appAtomRegistry,
356 getShare: (shareId) => snapshot.drafts.find((draft) => draft.id === shareId) ?? null,
357 reserve: reserveShare,
358 release: releaseShareReservation,
359 consume: consumeShare,
360 readDraft: getComposerDraftSnapshot,
361 undoMerge: undoComposerDraftMerge,
362 mergeIntoDraft: mergeComposerDraftContent,
363 selectAttachments: (share, environmentId) =>
364 selectIncomingShareAttachmentsForServer({
365 attachments: share.attachments,
366 serverConfig: appAtomRegistry.get(
367 serverEnvironment.configValueAtom(EnvironmentId.make(environmentId)),
368 ),
369 }),
370 releaseUnusedAttachments: scheduleUnusedComposerAttachmentCleanup,
371 onWarnings: (warnings) => {
372 Dialog.alert(m(msg("Some shared content was skipped")), warnings.join("\n"));
373 },
374 onImportFailure: (target, error) => {
375 Dialog.alert(
376 m(msg("Could not import shared content")),
377 error instanceof Error
378 ? (errorDisplayMessage(error, m) ?? error.message)
379 : m(msg("The shared content could not be saved.")),
380 [
381 {
382 text: m(msg("Cancel import")),
383 style: "cancel",
384 onPress: () => void incomingShareImports.cancel(target),
385 },
386 { text: m(msg("Retry")), onPress: () => incomingShareImports.retry(target) },
387 ],
388 { cancelable: false },
389 );
390 },
391 onCancelFailure: (target, error) => {
392 Dialog.alert(
393 m(msg("Could not cancel import")),
394 error instanceof Error
395 ? (errorDisplayMessage(error, m) ?? error.message)
396 : m(msg("The shared content could not be restored safely.")),
397 [
398 { text: m(msg("Retry import")), onPress: () => incomingShareImports.retry(target) },
399 { text: m(msg("Retry cancel")), onPress: () => void incomingShareImports.cancel(target) },
400 ],
401 { cancelable: false },
402 );
403 },
404 leave: (target) => {
405 rootNavigationRef.dispatch({
406 ...CommonActions.goBack(),
407 source: target.routeKey,
408 target: rootNavigationRef.getRootState()?.key,
409 });
410 },
411});
412
413/** Abandons the share imports of draft routes that left the stack. */
414export function pruneIncomingShareImports(state: Parameters<typeof liveNewTaskFlowKeys>[0]) {
415 const live = liveNewTaskFlowKeys(state);
416 void incomingShareImports.prune(live);
417 const handed = appAtomRegistry.get(handedSharesAtom);
418 if (Object.keys(handed).some((flowKey) => !live.has(flowKey))) {
419 appAtomRegistry.set(
420 handedSharesAtom,
421 Object.fromEntries(Object.entries(handed).filter(([flowKey]) => live.has(flowKey))),
422 );
423 }
424}
425
426export function useIncomingShare() {
427 const { drafts, isLoading } = useSyncExternalStore(
428 subscribeIncomingShares,
429 getIncomingShareSnapshot,
430 );
431 return {
432 pendingShare: drafts[0] ?? null,
433 isLoading,
434 getShare: (shareId: string) => drafts.find((draft) => draft.id === shareId) ?? null,
435 releaseShareReservation,
436 };
437}