@devries-cameron20 / t3code Mirror · read-only / commits / d2ab13b095
Fork 0

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

Mirrored from https://github.com/Camo67/t3code.git

Synced Nov 22, 14:30 UTC

refactor(mobile): share imports run outside the new-task screen (#25793)

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

Julius Marminge committed Oct 27, 2026 at 01:44 UTC d2ab13b09537faa003621b52ce2a31fc13ae650e
6 files changed +972 -321
apps/mobile/src/App.tsx
+2
@@ -26,6 +26,7 @@ import { CloudAuthProvider } from "./features/cloud/CloudAuthProvider";
26 import { prepareNativeShowcaseCapture } from "./features/showcase/nativeShowcaseScene";
27 import {
28 presentPendingIncomingShare,
29 + pruneIncomingShareImports,
30 startIncomingShareInbox,
31 } from "./features/sharing/IncomingShareProvider";
32 import {
@@ -133,6 +134,7 @@ function handleNavigationStateChange(state: NavigationState | undefined): void {
134 setAgentNotificationPathname(workspaceLocationFromState(state).pathname);
135 recordAppShortcutNavigationState(state);
136 pruneNewTaskBranchCheckouts(state);
137 + pruneIncomingShareImports(state);
138 }
139
140 function handleNavigationReady(): void {
apps/mobile/src/features/sharing/IncomingShareProvider.tsx
+74 -3
@@ -1,7 +1,7 @@
1 import * as Dialog from "../../components/ui/Dialog";
2 import Constants from "expo-constants";
3 import * as Crypto from "expo-crypto";
4 -import { PROVIDER_SEND_TURN_MAX_FILE_BYTES } from "@t3tools/contracts";
4 +import { EnvironmentId, PROVIDER_SEND_TURN_MAX_FILE_BYTES } from "@t3tools/contracts";
5 import {
6 clearSharedPayloads,
7 getResolvedSharedPayloadsAsync,
@@ -11,10 +11,12 @@ import {
11 } from "expo-sharing";
12 import { useSyncExternalStore } from "react";
13 import { Platform } from "react-native";
14 +import { CommonActions } from "@react-navigation/native";
15
16 import {
17 buildIncomingShareDraft,
18 isShareFileUriUnderOwnedRoots,
19 + selectIncomingShareAttachmentsForServer,
20 type IncomingShareDestination,
21 type IncomingShareDraft,
22 } from "./incoming-share-model";
@@ -26,6 +28,16 @@ import { coalescedRun } from "../../lib/coalescedRun";
28 import { rootNavigationRef } from "../../lib/rootNavigation";
29 import { selectWorkspaceDetail } from "../workspace/workspace-detail-selection";
30 import { isDraftThreadRoute } from "../threads/thread-route-state";
31 +import { makeIncomingShareImports } from "../threads/incomingShareImport";
32 +import { liveNewTaskFlowKeys } from "../threads/new-task-flow-state";
33 +import { appAtomRegistry } from "../../state/atom-registry";
34 +import { serverEnvironment } from "../../state/server";
35 +import {
36 + getComposerDraftSnapshot,
37 + mergeComposerDraftContent,
38 + scheduleUnusedComposerAttachmentCleanup,
39 + undoComposerDraftMerge,
40 +} from "../../state/use-composer-drafts";
41 import {
42 EMPTY_INCOMING_SHARE_PRESENTATION_STATE,
43 transitionIncomingSharePresentation,
@@ -282,6 +294,67 @@ async function releaseShareReservation(
294 publish(await incomingShareInbox.releaseReservation(shareId, expectedDestination));
295 }
296
297 +/** Moves shares into new-task drafts; see makeIncomingShareImports. */
298 +export const incomingShareImports = makeIncomingShareImports({
299 + registry: appAtomRegistry,
300 + getShare: (shareId) => snapshot.drafts.find((draft) => draft.id === shareId) ?? null,
301 + reserve: reserveShare,
302 + release: releaseShareReservation,
303 + consume: consumeShare,
304 + readDraft: getComposerDraftSnapshot,
305 + undoMerge: undoComposerDraftMerge,
306 + mergeIntoDraft: mergeComposerDraftContent,
307 + selectAttachments: (share, environmentId) =>
308 + selectIncomingShareAttachmentsForServer({
309 + attachments: share.attachments,
310 + serverConfig: appAtomRegistry.get(
311 + serverEnvironment.configValueAtom(EnvironmentId.make(environmentId)),
312 + ),
313 + }),
314 + releaseUnusedAttachments: scheduleUnusedComposerAttachmentCleanup,
315 + onWarnings: (warnings) => {
316 + Dialog.alert("Some shared content was skipped", warnings.join("\n"));
317 + },
318 + onImportFailure: (target, error) => {
319 + Dialog.alert(
320 + "Could not import shared content",
321 + error instanceof Error ? error.message : "The shared content could not be saved.",
322 + [
323 + {
324 + text: "Cancel import",
325 + style: "cancel",
326 + onPress: () => void incomingShareImports.cancel(target),
327 + },
328 + { text: "Retry", onPress: () => incomingShareImports.retry(target) },
329 + ],
330 + { cancelable: false },
331 + );
332 + },
333 + onCancelFailure: (target, error) => {
334 + Dialog.alert(
335 + "Could not cancel import",
336 + error instanceof Error ? error.message : "The shared content could not be restored safely.",
337 + [
338 + { text: "Retry import", onPress: () => incomingShareImports.retry(target) },
339 + { text: "Retry cancel", onPress: () => void incomingShareImports.cancel(target) },
340 + ],
341 + { cancelable: false },
342 + );
343 + },
344 + leave: (target) => {
345 + rootNavigationRef.dispatch({
346 + ...CommonActions.goBack(),
347 + source: target.routeKey,
348 + target: rootNavigationRef.getRootState()?.key,
349 + });
350 + },
351 +});
352 +
353 +/** Abandons the share imports of draft routes that left the stack. */
354 +export function pruneIncomingShareImports(state: Parameters<typeof liveNewTaskFlowKeys>[0]) {
355 + void incomingShareImports.prune(liveNewTaskFlowKeys(state));
356 +}
357 +
358 export function useIncomingShare() {
359 const { drafts, isLoading } = useSyncExternalStore(
360 subscribeIncomingShares,
@@ -291,8 +364,6 @@ export function useIncomingShare() {
364 pendingShare: drafts[0] ?? null,
365 isLoading,
366 getShare: (shareId: string) => drafts.find((draft) => draft.id === shareId) ?? null,
294 - reserveShare,
367 releaseShareReservation,
296 - consumeShare,
368 };
369 }
apps/mobile/src/features/threads/NewTaskDraftScreen.tsx
+75 -295
@@ -25,8 +25,9 @@ import {
25 useIsFocused,
26 useNavigation,
27 usePreventRemove,
28 + useRoute,
29 } from "@react-navigation/native";
29 -import { useEffect, useEffectEvent, useRef, useState } from "react";
30 +import { useEffect, useRef, useState } from "react";
31 import { Platform, Pressable, View } from "react-native";
32 import { ScreenScrollView as ScrollView } from "../../components/ui/ScreenScrollView";
33 import { KeyboardController } from "react-native-keyboard-controller";
@@ -58,11 +59,8 @@ import { makeTurnCommandMetadata } from "../../lib/commandMetadata";
59 import {
60 clearComposerDraftContent,
61 getComposerDraftSnapshot,
61 - mergeComposerDraftContent,
62 - restoreComposerDraftSnapshot,
62 updateComposerDraftSettings,
63 scheduleUnusedComposerAttachmentCleanup,
65 - type ComposerDraft,
64 waitForComposerDraftsLoaded,
65 } from "../../state/use-composer-drafts";
66 import { useEnvironmentServerConfig, useProjects } from "../../state/entities";
@@ -92,10 +90,10 @@ import {
90 resolveNewTaskBranchLabel,
91 resolveNewTaskWorkspaceLabel,
92 } from "./new-task-context-presentation";
95 -import { useIncomingShare } from "../sharing/IncomingShareProvider";
96 -import { selectIncomingShareAttachmentsForServer } from "../sharing/incoming-share-model";
93 +import { incomingShareImports, useIncomingShare } from "../sharing/IncomingShareProvider";
94 +import { idleShareFlagAtom, idleShareImportPhaseAtom } from "./incomingShareImport";
95 +import { newTaskFlowKey } from "./new-task-flow-state";
96 import { appAtomRegistry } from "../../state/atom-registry";
98 -import { serverEnvironment } from "../../state/server";
97
98 import { readEnvironmentScope, useEnvironmentScope } from "../../state/session";
99
@@ -161,13 +159,9 @@ export function NewTaskDraftScreen(props: {
159 const navigation = useNavigation();
160 const isFocused = useIsFocused();
161 const goBack = useWorkspaceBackNavigation("threads");
164 - const {
165 - consumeShare,
166 - getShare,
167 - isLoading: isIncomingShareInboxLoading,
168 - releaseShareReservation,
169 - reserveShare,
170 - } = useIncomingShare();
162 + const currentRoute = useRoute();
163 + const flowKey = newTaskFlowKey(currentRoute);
164 + const { getShare, isLoading: isIncomingShareInboxLoading } = useIncomingShare();
165 const { projectScopes, selectedProject, selectedProjectKey, setProject } = flow;
166 // selectedProject falls back to the environment's first project; remember only a chosen one.
167 useRememberThreadProject(
@@ -275,26 +269,7 @@ export function NewTaskDraftScreen(props: {
269 const queuesInsteadOfStarting = !environmentConnected || attachmentsUploading;
270 const promptInputRef = useRef<ComposerEditorHandle>(null);
271 const loadedBranchesProjectKeyRef = useRef<string | null>(null);
278 - const [importingShareKey, setImportingShareKey] = useState<string | null>(null);
279 - const [isCancellingShareImport, setIsCancellingShareImport] = useState(false);
280 - const [cancelledIncomingShareId, setCancelledIncomingShareId] = useState<string | null>(null);
272 const [isReturningToProjectPicker, setIsReturningToProjectPicker] = useState(false);
282 - const [shareImportAttempt, setShareImportAttempt] = useState(0);
283 - const startedShareImportKeyRef = useRef<string | null>(null);
284 - const cancellingShareImportKeyRef = useRef<string | null>(null);
285 - const shareImportDraftBackupRef = useRef(new Map<string, ComposerDraft>());
286 - const activeShareImportTokenRef = useRef<symbol | null>(null);
287 - const shareImportMountedRef = useRef(true);
288 - // The share import resumes after awaits; this reads the screen's current
289 - // draft and share at that point without re-running the import effect.
290 - const isCurrentShareImport = useEffectEvent(
291 - (draftKey: string, shareId: string) =>
292 - flow.draftKey === draftKey && props.incomingShareId === shareId,
293 - );
294 - const isImportingShare = importingShareKey !== null;
295 - const alertedUnavailableIncomingShareIdRef = useRef<string | null>(null);
296 - // Remember consumed shares locally: send clears the receipt before navigation and can trigger a missing-content render.
297 - const [consumedIncomingShareId, setConsumedIncomingShareId] = useState<string | null>(null);
273 const incomingShare = props.incomingShareId ? getShare(props.incomingShareId) : null;
274 const requestedInitialProjectAvailable = Boolean(
275 props.initialProjectRef?.environmentId &&
@@ -311,11 +286,67 @@ export function NewTaskDraftScreen(props: {
286 incomingShare?.attachments.some((attachment) => attachment.type === "file") &&
287 selectedEnvironmentServerConfig === null,
288 );
289 + const routeImportedShare = useAtomValue(
290 + flowKey !== undefined && props.incomingShareId
291 + ? incomingShareImports.importedAtom(flowKey, props.incomingShareId)
292 + : idleShareFlagAtom,
293 + );
294 + const hasImportedIncomingShare = Boolean(
295 + props.incomingShareId &&
296 + (routeImportedShare ||
297 + (flow.draftKey &&
298 + getComposerDraftSnapshot(flow.draftKey).importedShareIds?.includes(props.incomingShareId))),
299 + );
300 + const isIncomingShareUnavailable = Boolean(
301 + props.incomingShareId &&
302 + !isIncomingShareInboxLoading &&
303 + !incomingShare &&
304 + !hasImportedIncomingShare,
305 + );
306 + const shareImportTarget = (() => {
307 + if (!props.incomingShareId || flowKey === undefined || !flow.draftKey) return null;
308 + if (!selectedProject || !incomingShare || isIncomingShareAwaitingServerConfig) return null;
309 + const initialEnvironmentId = props.initialProjectRef?.environmentId;
310 + const initialProjectId = props.initialProjectRef?.projectId;
311 + if (
312 + initialEnvironmentId &&
313 + initialProjectId &&
314 + (selectedProject.environmentId !== initialEnvironmentId ||
315 + selectedProject.id !== initialProjectId)
316 + ) {
317 + return null;
318 + }
319 + return {
320 + flowKey,
321 + routeKey: currentRoute.key,
322 + draftKey: flow.draftKey,
323 + destination: {
324 + environmentId: String(selectedProject.environmentId),
325 + projectId: String(selectedProject.id),
326 + },
327 + shareId: incomingShare.id,
328 + };
329 + })();
330 + const shareImportPhase = useAtomValue(
331 + shareImportTarget === null
332 + ? idleShareImportPhaseAtom
333 + : incomingShareImports.phaseAtom(shareImportTarget),
334 + );
335 + // Locks on the route, not the target: the target turns null when server config
336 + // drops or the project stops matching, while the import keeps writing the draft.
337 + const isImportingShare = useAtomValue(
338 + flowKey === undefined ? idleShareFlagAtom : incomingShareImports.inFlightAtom(flowKey),
339 + );
340 const isIncomingShareTransferPending = Boolean(
315 - incomingShare &&
316 - cancelledIncomingShareId !== props.incomingShareId &&
317 - !isIncomingShareAwaitingServerConfig,
341 + incomingShare && shareImportPhase !== "cancelled" && !isIncomingShareAwaitingServerConfig,
342 );
343 + // A failed import waits in a modal alert, and a cancel finishes its undo even
344 + // after the route leaves, so neither holds the route: the cancel can leave as
345 + // soon as it is done.
346 + const isIncomingShareHoldingRoute =
347 + isIncomingShareTransferPending &&
348 + shareImportPhase !== "failed" &&
349 + shareImportPhase !== "cancelling";
350 const contextImports = useAtomValue(composerContextImportsAtom);
351 const isImportingContext = flow.draftKey ? contextImports[flow.draftKey] === true : false;
352 const isComposerInteractionLocked =
@@ -334,32 +365,13 @@ export function NewTaskDraftScreen(props: {
365 ? selectedProject?.workspaceRoot
366 : (flow.selectedWorktreePath ?? selectedProject?.workspaceRoot)) || null;
367 const preventRemove =
337 - (isIncomingShareTransferPending && !isProjectPickerReturnActive) ||
338 - isCancellingShareImport ||
339 - flow.submitting;
368 + (isIncomingShareHoldingRoute && !isProjectPickerReturnActive) || flow.submitting;
369 usePreventRemove(preventRemove, () => undefined);
341 - const hasImportedIncomingShare = Boolean(
342 - props.incomingShareId &&
343 - (consumedIncomingShareId === props.incomingShareId ||
344 - (flow.draftKey &&
345 - getComposerDraftSnapshot(flow.draftKey).importedShareIds?.includes(props.incomingShareId))),
346 - );
347 - const isIncomingShareUnavailable = Boolean(
348 - props.incomingShareId &&
349 - !isIncomingShareInboxLoading &&
350 - !incomingShare &&
351 - !hasImportedIncomingShare,
352 - );
370 const isIncomingShareReady =
371 !props.incomingShareId ||
372 (hasImportedIncomingShare && !incomingShare) ||
373 isIncomingShareUnavailable;
374 const appliedInitialProjectKeyRef = useRef<string | null>(null);
358 - useEffect(() => {
359 - if (cancelledIncomingShareId === props.incomingShareId) {
360 - navigation.goBack();
361 - }
362 - }, [cancelledIncomingShareId, navigation, props.incomingShareId]);
375 useEffect(() => {
376 if (!isReturningToProjectPicker) {
377 return;
@@ -382,19 +394,6 @@ export function NewTaskDraftScreen(props: {
394 props.incomingShareId,
395 requestedInitialProjectAvailable,
396 ]);
385 - useEffect(() => {
386 - if (!shareImportMountedRef.current) {
387 - startedShareImportKeyRef.current = null;
388 - }
389 - shareImportMountedRef.current = true;
390 - return () => {
391 - appliedInitialProjectKeyRef.current = null;
392 - shareImportMountedRef.current = false;
393 - activeShareImportTokenRef.current = null;
394 - cancellingShareImportKeyRef.current = null;
395 - };
396 - }, []);
397 -
397 const { openDraft } = flow;
398 // Cold launches load drafts and projects separately; wait for hydration and retry while shells load.
399 const attemptedDraftIdRef = useRef<string | null>(null);
@@ -541,232 +540,6 @@ export function NewTaskDraftScreen(props: {
540 loadBranches();
541 }, [loadBranches, selectedProject]);
542
544 - useEffect(() => {
545 - const shareId = props.incomingShareId;
546 - const draftKey = flow.draftKey;
547 - const destinationProject = selectedProject;
548 - const initialEnvironmentId = props.initialProjectRef?.environmentId;
549 - const initialProjectId = props.initialProjectRef?.projectId;
550 - const selectedProjectMatchesRoute =
551 - !initialEnvironmentId ||
552 - !initialProjectId ||
553 - (destinationProject?.environmentId === initialEnvironmentId &&
554 - destinationProject.id === initialProjectId);
555 - if (
556 - !shareId ||
557 - !draftKey ||
558 - !destinationProject ||
559 - !selectedProjectMatchesRoute ||
560 - cancelledIncomingShareId === shareId
561 - ) {
562 - return;
563 - }
564 - const importKey = `${shareId}:${draftKey}`;
565 - if (
566 - startedShareImportKeyRef.current === importKey ||
567 - cancellingShareImportKeyRef.current === importKey
568 - ) {
569 - return;
570 - }
571 -
572 - if (!incomingShare) {
573 - if (isIncomingShareUnavailable && alertedUnavailableIncomingShareIdRef.current !== shareId) {
574 - alertedUnavailableIncomingShareIdRef.current = shareId;
575 - Dialog.alert(
576 - "Shared content unavailable",
577 - "The shared content is no longer in the inbox. You can continue editing this task draft.",
578 - );
579 - }
580 - return;
581 - }
582 -
583 - if (
584 - incomingShare.attachments.some((attachment) => attachment.type === "file") &&
585 - selectedEnvironmentServerConfig === null
586 - ) {
587 - return;
588 - }
589 -
590 - if (alertedUnavailableIncomingShareIdRef.current === shareId) {
591 - alertedUnavailableIncomingShareIdRef.current = null;
592 - }
593 - startedShareImportKeyRef.current = importKey;
594 - const draftBackup =
595 - shareImportDraftBackupRef.current.get(importKey) ?? getComposerDraftSnapshot(draftKey);
596 - shareImportDraftBackupRef.current.set(importKey, draftBackup);
597 - const importToken = Symbol(importKey);
598 - let didReserveShare = false;
599 - let didConsumeShare = false;
600 - let needsDraftRestore = false;
601 - activeShareImportTokenRef.current = importToken;
602 - // oxlint-disable-next-line react/set-state-in-effect -- Publishes the share import started by this effect before its async work runs.
603 - setImportingShareKey(importKey);
604 - void (async () => {
605 - await reserveShare(shareId, {
606 - environmentId: String(destinationProject.environmentId),
607 - projectId: String(destinationProject.id),
608 - });
609 - didReserveShare = true;
610 - if (
611 - !shareImportMountedRef.current ||
612 - activeShareImportTokenRef.current !== importToken ||
613 - !isCurrentShareImport(draftKey, shareId)
614 - ) {
615 - return;
616 - }
617 - const selectedAttachments = selectIncomingShareAttachmentsForServer({
618 - attachments: incomingShare.attachments,
619 - serverConfig: appAtomRegistry.get(
620 - serverEnvironment.configValueAtom(destinationProject.environmentId),
621 - ),
622 - });
623 - if (selectedAttachments.status === "pending") {
624 - throw new Error("Server attachment support is still loading.");
625 - }
626 - needsDraftRestore = true;
627 - const { skippedAttachmentCount } = await mergeComposerDraftContent(draftKey, {
628 - text: incomingShare.text,
629 - attachments: selectedAttachments.attachments,
630 - sourceShareId: shareId,
631 - });
632 - if (
633 - !shareImportMountedRef.current ||
634 - activeShareImportTokenRef.current !== importToken ||
635 - !isCurrentShareImport(draftKey, shareId)
636 - ) {
637 - // Durable reservations resume interrupted transfers only in this project, avoiding duplicate draft copies.
638 - return;
639 - }
640 - await consumeShare(shareId);
641 - didConsumeShare = true;
642 - setConsumedIncomingShareId(shareId);
643 - // Release skipped files after consumption even on unmount; sweeping re-checks new owners.
644 - const retainedAttachmentIds = new Set(
645 - getComposerDraftSnapshot(draftKey).attachments.map((attachment) => attachment.id),
646 - );
647 - scheduleUnusedComposerAttachmentCleanup(
648 - incomingShare.attachments.filter((attachment) => !retainedAttachmentIds.has(attachment.id)),
649 - );
650 - if (!shareImportMountedRef.current || activeShareImportTokenRef.current !== importToken) {
651 - return;
652 - }
653 - const warnings = [...incomingShare.warnings, ...selectedAttachments.warnings];
654 - if (skippedAttachmentCount > 0) {
655 - warnings.push(
656 - `${skippedAttachmentCount} shared file${skippedAttachmentCount === 1 ? " was" : "s were"} skipped because this draft reached the attachment limit.`,
657 - );
658 - }
659 - if (warnings.length > 0) {
660 - Dialog.alert("Some shared content was skipped", warnings.join("\n"));
661 - }
662 - shareImportDraftBackupRef.current.delete(importKey);
663 - })()
664 - .catch((error) => {
665 - if (!shareImportMountedRef.current || activeShareImportTokenRef.current !== importToken) {
666 - return;
667 - }
668 - Dialog.alert(
669 - "Could not import shared content",
670 - error instanceof Error ? error.message : "The shared content could not be saved.",
671 - [
672 - {
673 - text: "Cancel import",
674 - style: "cancel",
675 - onPress: () => {
676 - const cancelImport = async (): Promise<void> => {
677 - if (!shareImportMountedRef.current) {
678 - return;
679 - }
680 - // Latch before restoring: atom publication can re-run import before React commits cancellation.
681 - cancellingShareImportKeyRef.current = importKey;
682 - setIsCancellingShareImport(true);
683 - try {
684 - if (needsDraftRestore) {
685 - // Sweep restored attachments only after inbox consumption; unconsumed inbox entries still own them.
686 - const mergedAttachments = getComposerDraftSnapshot(draftKey).attachments;
687 - await restoreComposerDraftSnapshot(draftKey, draftBackup);
688 - needsDraftRestore = false;
689 - if (didConsumeShare) {
690 - scheduleUnusedComposerAttachmentCleanup(mergedAttachments);
691 - }
692 - }
693 - if (didReserveShare) {
694 - await releaseShareReservation(shareId, {
695 - environmentId: String(destinationProject.environmentId),
696 - projectId: String(destinationProject.id),
697 - });
698 - }
699 - shareImportDraftBackupRef.current.delete(importKey);
700 - if (shareImportMountedRef.current) {
701 - setIsCancellingShareImport(false);
702 - setCancelledIncomingShareId(shareId);
703 - }
704 - } catch (cancelError) {
705 - if (!shareImportMountedRef.current) {
706 - return;
707 - }
708 - Dialog.alert(
709 - "Could not cancel import",
710 - cancelError instanceof Error
711 - ? cancelError.message
712 - : "The shared content could not be restored safely.",
713 - [
714 - {
715 - text: "Retry import",
716 - onPress: () => {
717 - cancellingShareImportKeyRef.current = null;
718 - setIsCancellingShareImport(false);
719 - setShareImportAttempt((attempt) => attempt + 1);
720 - },
721 - },
722 - {
723 - text: "Retry cancel",
724 - onPress: () => void cancelImport(),
725 - },
726 - ],
727 - { cancelable: false },
728 - );
729 - }
730 - };
731 - void cancelImport();
732 - },
733 - },
734 - {
735 - text: "Retry",
736 - onPress: () => setShareImportAttempt((attempt) => attempt + 1),
737 - },
738 - ],
739 - { cancelable: false },
740 - );
741 - })
742 - .finally(() => {
743 - if (startedShareImportKeyRef.current === importKey) {
744 - startedShareImportKeyRef.current = null;
745 - }
746 - if (shareImportMountedRef.current && activeShareImportTokenRef.current === importToken) {
747 - activeShareImportTokenRef.current = null;
748 - setImportingShareKey(null);
749 - }
750 - });
751 - }, [
752 - consumeShare,
753 - cancelledIncomingShareId,
754 - flow.draftKey,
755 - // oxlint-disable-next-line react/exhaustive-effect-dependencies -- hasImportedIncomingShare reflects the draft store; a change re-checks whether the share still needs importing.
756 - hasImportedIncomingShare,
757 - incomingShare,
758 - isIncomingShareInboxLoading,
759 - isIncomingShareUnavailable,
760 - props.incomingShareId,
761 - props.initialProjectRef?.environmentId,
762 - props.initialProjectRef?.projectId,
763 - releaseShareReservation,
764 - reserveShare,
765 - selectedEnvironmentServerConfig,
766 - selectedProject,
767 - shareImportAttempt,
768 - ]);
769 -
543 const selectedEnvironmentLabel =
544 flow.environments.find(
545 (environment) => environment.environmentId === flow.selectedEnvironmentId,
@@ -973,6 +746,11 @@ export function NewTaskDraftScreen(props: {
746 onChooseEnvironment={() => openContextPicker("NewTaskEnvironment")}
747 />
748 );
749 + const shareUnavailableNotice = isIncomingShareUnavailable ? (
750 + <Text textRole="footnote" className="text-center text-foreground-muted">
751 + The shared content is no longer in the inbox. You can continue editing this task draft.
752 + </Text>
753 + ) : null;
754 const hero = flow.isScratchDraft ? (
755 <View className="items-center gap-2 px-6" testID="new-task-hero">
756 <Text className="text-center text-2xl font-t3-medium tracking-tight text-foreground">
@@ -990,6 +768,7 @@ export function NewTaskDraftScreen(props: {
768 />
769 {environmentControl}
770 </View>
771 + {shareUnavailableNotice}
772 </View>
773 ) : (
774 <View className="items-center gap-6 px-6" testID="new-task-hero">
@@ -1019,6 +798,7 @@ export function NewTaskDraftScreen(props: {
798 </View>
799
800 {environmentControl}
801 + {shareUnavailableNotice}
802 </View>
803 );
804 // The nested hero scroll view does not receive UIKit's automatic navigation inset in split columns.
apps/mobile/src/features/threads/incomingShareImport.test.ts new
+413
@@ -0,0 +1,413 @@
1 +import { AtomRegistry } from "effect/reactivity";
2 +import { describe, expect, it, vi } from "vite-plus/test";
3 +
4 +import type { DraftComposerAttachment } from "../../lib/composerImages";
5 +import type { IncomingShareDraft } from "../sharing/incoming-share-model";
6 +import { undoComposerDraftMergeState, type ComposerDraft } from "../../state/use-composer-drafts";
7 +import {
8 + makeIncomingShareImports,
9 + type ShareImportDeps,
10 + type ShareImportPhase,
11 + type ShareImportTarget,
12 + transitionShareImport,
13 +} from "./incomingShareImport";
14 +
15 +const destination = { environmentId: "env-1", projectId: "project-1" };
16 +const edited: ComposerDraft = { text: "typed after the undo", attachments: [] };
17 +
18 +/** The draft store's own undo, applied to the test's draft map. */
19 +function undoInto(
20 + drafts: Map<string, ComposerDraft>,
21 + draftKey: string,
22 + snapshot: ComposerDraft,
23 + merged: ComposerDraft,
24 +): void {
25 + const next = undoComposerDraftMergeState(Object.fromEntries(drafts), draftKey, snapshot, merged);
26 + drafts.clear();
27 + for (const [key, draft] of Object.entries(next)) drafts.set(key, draft);
28 +}
29 +
30 +function mergeInto(
31 + drafts: Map<string, ComposerDraft>,
32 + draftKey: string,
33 + content: {
34 + readonly text: string;
35 + readonly attachments: ReadonlyArray<DraftComposerAttachment>;
36 + },
37 +): void {
38 + const existing = drafts.get(draftKey) ?? { text: "", attachments: [] };
39 + drafts.set(draftKey, {
40 + text: `${existing.text}\n${content.text}`,
41 + attachments: [...existing.attachments, ...content.attachments],
42 + });
43 +}
44 +
45 +function fileAttachment(id: string): DraftComposerAttachment {
46 + return {
47 + id,
48 + type: "file",
49 + name: `${id}.txt`,
50 + mimeType: "text/plain",
51 + sizeBytes: 4,
52 + fileUri: `file:///${id}.txt`,
53 + };
54 +}
55 +
56 +function share(attachments: ReadonlyArray<DraftComposerAttachment> = []): IncomingShareDraft {
57 + return {
58 + schemaVersion: 1,
59 + id: "share-1",
60 + createdAt: "2026-01-01T00:00:00.000Z",
61 + text: "shared text",
62 + attachments,
63 + warnings: [],
64 + };
65 +}
66 +
67 +function importTarget(overrides: Partial<ShareImportTarget> = {}): ShareImportTarget {
68 + return {
69 + flowKey: "flow-a",
70 + routeKey: "route-a",
71 + draftKey: "draft-a",
72 + destination,
73 + shareId: "share-1",
74 + ...overrides,
75 + };
76 +}
77 +
78 +function setup(overrides: Partial<ShareImportDeps> = {}) {
79 + const drafts = new Map<string, ComposerDraft>([["draft-a", { text: "mine", attachments: [] }]]);
80 + const inbox = new Map<string, IncomingShareDraft>([["share-1", share()]]);
81 + const calls: Array<string> = [];
82 + const registry = overrides.registry ?? AtomRegistry.make();
83 + const deps: ShareImportDeps = {
84 + registry,
85 + getShare: (shareId) => inbox.get(shareId) ?? null,
86 + reserve: vi.fn(async () => {
87 + calls.push("reserve");
88 + }),
89 + release: vi.fn(async () => {
90 + calls.push("release");
91 + }),
92 + consume: vi.fn(async () => {
93 + calls.push("consume");
94 + }),
95 + readDraft: (draftKey) => drafts.get(draftKey) ?? { text: "", attachments: [] },
96 + undoMerge: vi.fn(async (draftKey, snapshot, merged) => {
97 + calls.push("undo");
98 + undoInto(drafts, draftKey, snapshot, merged);
99 + }),
100 + mergeIntoDraft: vi.fn(async (draftKey, content) => {
101 + calls.push("merge");
102 + mergeInto(drafts, draftKey, content);
103 + return { skippedAttachmentCount: 0 };
104 + }),
105 + selectAttachments: (incoming) => ({
106 + status: "ready",
107 + attachments: incoming.attachments,
108 + warnings: [],
109 + }),
110 + releaseUnusedAttachments: vi.fn(),
111 + onWarnings: vi.fn(),
112 + onImportFailure: vi.fn(),
113 + onCancelFailure: vi.fn(),
114 + leave: vi.fn(),
115 + ...overrides,
116 + };
117 + const imports = makeIncomingShareImports(deps);
118 + const watch = (target: ShareImportTarget) => {
119 + const atom = imports.phaseAtom(target);
120 + const unmount = registry.mount(atom);
121 + registry.get(atom);
122 + return { phase: (): ShareImportPhase => registry.get(atom), unmount };
123 + };
124 + return { imports, deps, drafts, inbox, calls, watch, registry };
125 +}
126 +
127 +describe("transitionShareImport", () => {
128 + it("only cancels or retries from a failure, and keeps terminal phases terminal", () => {
129 + expect(transitionShareImport("attaching", "cancel")).toBe("attaching");
130 + expect(transitionShareImport("failed", "start")).toBe("reserving");
131 + expect(transitionShareImport("cancelling", "cancelFailed")).toBe("failed");
132 + expect(transitionShareImport("done", "start")).toBe("done");
133 + expect(transitionShareImport("cancelled", "start")).toBe("cancelled");
134 + });
135 +});
136 +
137 +describe("incoming share imports", () => {
138 + it("reserves, attaches and consumes once, releasing files the draft did not keep", async () => {
139 + const kept = fileAttachment("kept");
140 + const skipped = fileAttachment("skipped");
141 + const { deps, calls, drafts, inbox, imports, watch } = setup({
142 + selectAttachments: () => ({ status: "ready", attachments: [kept], warnings: ["too big"] }),
143 + });
144 + inbox.set("share-1", share([kept, skipped]));
145 + const target = importTarget();
146 + const watched = watch(target);
147 +
148 + expect(watched.phase()).toBe("reserving");
149 + await imports.settled(target);
150 + expect(watched.phase()).toBe("done");
151 +
152 + expect(calls).toEqual(["reserve", "merge", "consume"]);
153 + expect(drafts.get("draft-a")?.attachments).toEqual([kept]);
154 + expect(deps.releaseUnusedAttachments).toHaveBeenCalledWith([skipped]);
155 + expect(deps.onWarnings).toHaveBeenCalledWith(["too big"]);
156 + });
157 +
158 + it("runs once when its atom node is removed and rebuilt", async () => {
159 + const { imports, deps } = setup();
160 + const tasks: Array<() => void> = [];
161 + const registry = AtomRegistry.make({
162 + scheduleTask: (task) => {
163 + tasks.push(task);
164 + return () => undefined;
165 + },
166 + });
167 + const atom = imports.phaseAtom(importTarget());
168 +
169 + registry.get(atom);
170 + tasks.splice(0).forEach((task) => task());
171 + expect(registry.getNodes().size).toBe(0);
172 + const unmount = registry.mount(atom);
173 + await imports.settled(importTarget());
174 + expect(registry.get(atom)).toBe("done");
175 + unmount();
176 +
177 + expect(deps.reserve).toHaveBeenCalledTimes(1);
178 + expect(deps.consume).toHaveBeenCalledTimes(1);
179 + });
180 +
181 + it("cancel after a failed consume restores the draft, releases the reservation and leaves", async () => {
182 + const { deps, calls, drafts, watch, imports } = setup({
183 + consume: vi.fn(async () => {
184 + throw new Error("disk full");
185 + }),
186 + });
187 + const target = importTarget();
188 + const watched = watch(target);
189 + await imports.settled(target);
190 + expect(watched.phase()).toBe("failed");
191 + expect(deps.onImportFailure).toHaveBeenCalledWith(target, new Error("disk full"));
192 +
193 + await imports.cancel(target);
194 +
195 + expect(watched.phase()).toBe("cancelled");
196 + expect(calls).toEqual(["reserve", "merge", "undo", "release"]);
197 + expect(drafts.get("draft-a")).toEqual({ text: "mine", attachments: [] });
198 + // Unconsumed: the inbox still owns the files.
199 + expect(deps.releaseUnusedAttachments).not.toHaveBeenCalled();
200 + expect(deps.leave).toHaveBeenCalledWith(target);
201 + });
202 +
203 + it("a failed cancel can be retried and keeps the original backup", async () => {
204 + let releaseAttempts = 0;
205 + const { deps, drafts, watch, imports } = setup({
206 + consume: vi.fn(async () => {
207 + throw new Error("disk full");
208 + }),
209 + release: vi.fn(async () => {
210 + releaseAttempts += 1;
211 + if (releaseAttempts === 1) throw new Error("locked");
212 + }),
213 + });
214 + const target = importTarget();
215 + const watched = watch(target);
216 + await imports.settled(target);
217 + expect(watched.phase()).toBe("failed");
218 +
219 + await imports.cancel(target);
220 + expect(watched.phase()).toBe("failed");
221 + expect(deps.onCancelFailure).toHaveBeenCalledWith(target, new Error("locked"));
222 + expect(deps.leave).not.toHaveBeenCalled();
223 +
224 + await imports.cancel(target);
225 + expect(watched.phase()).toBe("cancelled");
226 + expect(deps.undoMerge).toHaveBeenCalledTimes(1);
227 + expect(drafts.get("draft-a")).toEqual({ text: "mine", attachments: [] });
228 + expect(deps.leave).toHaveBeenCalledTimes(1);
229 + });
230 +
231 + it("stops before consuming once its route leaves the stack", async () => {
232 + const mergeStarted = Promise.withResolvers<void>();
233 + const merged = Promise.withResolvers<{ readonly skippedAttachmentCount: number }>();
234 + const { deps, imports, watch } = setup({
235 + mergeIntoDraft: () => {
236 + mergeStarted.resolve();
237 + return merged.promise;
238 + },
239 + });
240 + const watched = watch(importTarget());
241 + await mergeStarted.promise;
242 + expect(watched.phase()).toBe("attaching");
243 +
244 + const pruned = imports.prune(new Set(["flow-b"]));
245 + merged.resolve({ skippedAttachmentCount: 0 });
246 + await pruned;
247 +
248 + expect(deps.consume).not.toHaveBeenCalled();
249 + expect(deps.onImportFailure).not.toHaveBeenCalled();
250 + watched.unmount();
251 + });
252 +
253 + const userChanges = [
254 + ["edited", (drafts: Map<string, ComposerDraft>) => drafts.set("draft-a", edited), edited],
255 + ["deleted", (drafts: Map<string, ComposerDraft>) => drafts.delete("draft-a"), undefined],
256 + ] as const;
257 +
258 + it.each(userChanges)(
259 + "a retried cancel keeps a draft the user %s after the undo was shown",
260 + async (_change, change, expected) => {
261 + let undoAttempts = 0;
262 + const { deps, drafts, watch, imports } = setup({
263 + consume: vi.fn(async () => {
264 + throw new Error("disk full");
265 + }),
266 + // Like undoComposerDraftMerge: publishes, then fails to persist.
267 + undoMerge: vi.fn(
268 + async (draftKey: string, snapshot: ComposerDraft, merged: ComposerDraft) => {
269 + undoAttempts += 1;
270 + undoInto(drafts, draftKey, snapshot, merged);
271 + if (undoAttempts === 1) throw new Error("write failed");
272 + },
273 + ),
274 + });
275 + const target = importTarget();
276 + const watched = watch(target);
277 + await imports.settled(target);
278 + await imports.cancel(target);
279 + expect(deps.onCancelFailure).toHaveBeenCalledWith(target, new Error("write failed"));
280 +
281 + change(drafts);
282 + await imports.cancel(target);
283 +
284 + expect(watched.phase()).toBe("cancelled");
285 + expect(drafts.get("draft-a")).toEqual(expected);
286 + expect(deps.release).toHaveBeenCalledTimes(1);
287 + },
288 + );
289 +
290 + it("cancel undoes the import after an upload finished on its attachment", async () => {
291 + const file = fileAttachment("file");
292 + const { drafts, inbox, watch, imports } = setup({
293 + consume: vi.fn(async () => {
294 + throw new Error("disk full");
295 + }),
296 + });
297 + inbox.set("share-1", share([file]));
298 + const target = importTarget();
299 + watch(target);
300 + await imports.settled(target);
301 +
302 + const merged = drafts.get("draft-a");
303 + drafts.set("draft-a", {
304 + text: merged?.text ?? "",
305 + attachments: [{ ...file, uploadedAttachmentId: "uploaded-1" }],
306 + });
307 + await imports.cancel(target);
308 +
309 + expect(drafts.get("draft-a")).toEqual({ text: "mine", attachments: [] });
310 + });
311 +
312 + it.each(userChanges)(
313 + "cancel keeps a draft the user %s after a merge that published but failed to persist",
314 + async (_change, change, expected) => {
315 + const { drafts, watch, imports } = setup({
316 + // Like mergeComposerDraftContent: publishes, then fails to persist.
317 + mergeIntoDraft: vi.fn(async (draftKey, content) => {
318 + mergeInto(drafts, draftKey, content);
319 + throw new Error("write failed");
320 + }),
321 + });
322 + const target = importTarget();
323 + const watched = watch(target);
324 + await imports.settled(target);
325 + expect(watched.phase()).toBe("failed");
326 +
327 + change(drafts);
328 + await imports.cancel(target);
329 +
330 + expect(watched.phase()).toBe("cancelled");
331 + expect(drafts.get("draft-a")).toEqual(expected);
332 + },
333 + );
334 +
335 + it("cancel after a merge that published but failed to persist removes the merged share", async () => {
336 + const { drafts, watch, imports } = setup({
337 + mergeIntoDraft: vi.fn(async (draftKey, content) => {
338 + mergeInto(drafts, draftKey, content);
339 + throw new Error("write failed");
340 + }),
341 + });
342 + const target = importTarget();
343 + watch(target);
344 + await imports.settled(target);
345 +
346 + await imports.cancel(target);
347 +
348 + expect(drafts.get("draft-a")).toEqual({ text: "mine", attachments: [] });
349 + });
350 +
351 + it("a failed import keeps its cancel after its route left, and reports a failed undo", async () => {
352 + const { calls, deps, imports, watch } = setup({
353 + consume: vi.fn(async () => {
354 + throw new Error("disk full");
355 + }),
356 + release: vi.fn(async () => {
357 + throw new Error("locked");
358 + }),
359 + });
360 + const target = importTarget();
361 + const watched = watch(target);
362 + await imports.settled(target);
363 + expect(watched.phase()).toBe("failed");
364 + watched.unmount();
365 + await imports.prune(new Set());
366 +
367 + await imports.cancel(target);
368 +
369 + expect(calls).toEqual(["reserve", "merge", "undo"]);
370 + expect(deps.onCancelFailure).toHaveBeenCalledWith(target, new Error("locked"));
371 + expect(deps.leave).not.toHaveBeenCalled();
372 + });
373 +
374 + it("a route switching drafts abandons the in-flight import", async () => {
375 + const reserved = Promise.withResolvers<void>();
376 + const { deps, imports, watch } = setup({
377 + reserve: vi.fn().mockReturnValueOnce(reserved.promise).mockResolvedValue(undefined),
378 + });
379 + watch(importTarget()).unmount();
380 + const secondTarget = importTarget({ draftKey: "draft-b" });
381 + const second = watch(secondTarget);
382 + reserved.resolve();
383 +
384 + await imports.settled(secondTarget);
385 + expect(second.phase()).toBe("done");
386 + expect(deps.mergeIntoDraft).toHaveBeenCalledTimes(1);
387 + expect(deps.mergeIntoDraft).toHaveBeenCalledWith("draft-b", expect.anything());
388 + });
389 +
390 + it("stays in flight for its route after the screen stops rendering its target", async () => {
391 + const mergeStarted = Promise.withResolvers<void>();
392 + const merged = Promise.withResolvers<{ readonly skippedAttachmentCount: number }>();
393 + const { imports, registry, watch } = setup({
394 + mergeIntoDraft: () => {
395 + mergeStarted.resolve();
396 + return merged.promise;
397 + },
398 + });
399 + const inFlight = imports.inFlightAtom("flow-a");
400 + const unmountInFlight = registry.mount(inFlight);
401 + const target = importTarget();
402 + const watched = watch(target);
403 + await mergeStarted.promise;
404 +
405 + watched.unmount();
406 + expect(registry.get(inFlight)).toBe(true);
407 +
408 + merged.resolve({ skippedAttachmentCount: 0 });
409 + await imports.settled(target);
410 + expect(registry.get(inFlight)).toBe(false);
411 + unmountInFlight();
412 + });
413 +});
apps/mobile/src/features/threads/incomingShareImport.ts new
+408
@@ -0,0 +1,408 @@
1 +import { Atom, type AtomRegistry } from "effect/reactivity";
2 +
3 +import type { DraftComposerAttachment } from "../../lib/composerImages";
4 +import type { ComposerDraft } from "../../state/use-composer-drafts";
5 +import type {
6 + IncomingShareDestination,
7 + IncomingShareDraft,
8 + selectIncomingShareAttachmentsForServer,
9 +} from "../sharing/incoming-share-model";
10 +
11 +export type ShareImportPhase =
12 + | "idle"
13 + | "reserving"
14 + | "attaching"
15 + | "consuming"
16 + | "done"
17 + | "failed"
18 + | "cancelling"
19 + | "cancelled";
20 +
21 +export type ShareImportEvent =
22 + | "start"
23 + | "reserved"
24 + | "attached"
25 + | "consumed"
26 + | "failed"
27 + | "cancel"
28 + | "cancelFailed"
29 + | "cancelled";
30 +
31 +const TRANSITIONS: Readonly<
32 + Record<ShareImportPhase, Partial<Record<ShareImportEvent, ShareImportPhase>>>
33 +> = {
34 + idle: { start: "reserving" },
35 + reserving: { reserved: "attaching", failed: "failed" },
36 + attaching: { attached: "consuming", failed: "failed" },
37 + consuming: { consumed: "done", failed: "failed" },
38 + done: {},
39 + // "start" from failed is a retry.
40 + failed: { start: "reserving", cancel: "cancelling" },
41 + cancelling: { cancelled: "cancelled", cancelFailed: "failed" },
42 + cancelled: {},
43 +};
44 +
45 +/** Events that do not apply to the current phase leave it unchanged. */
46 +export function transitionShareImport(
47 + phase: ShareImportPhase,
48 + event: ShareImportEvent,
49 +): ShareImportPhase {
50 + return TRANSITIONS[phase][event] ?? phase;
51 +}
52 +
53 +function isShareImportInFlight(phase: ShareImportPhase): boolean {
54 + return phase === "reserving" || phase === "attaching" || phase === "consuming";
55 +}
56 +
57 +/**
58 + * One draft route importing one share into one draft. Plain data, compared
59 + * structurally, so the screen can build it on every render.
60 + */
61 +export interface ShareImportTarget {
62 + /** The draft route's flow key; the import is abandoned once it leaves the stack. */
63 + readonly flowKey: string;
64 + readonly routeKey: string;
65 + readonly draftKey: string;
66 + readonly destination: IncomingShareDestination;
67 + readonly shareId: string;
68 +}
69 +
70 +export interface ShareImportDeps {
71 + readonly registry: AtomRegistry.AtomRegistry;
72 + /** The share as the inbox holds it now. */
73 + readonly getShare: (shareId: string) => IncomingShareDraft | null;
74 + readonly reserve: (shareId: string, destination: IncomingShareDestination) => Promise<void>;
75 + readonly release: (shareId: string, destination: IncomingShareDestination) => Promise<void>;
76 + readonly consume: (shareId: string) => Promise<void>;
77 + readonly readDraft: (draftKey: string) => ComposerDraft;
78 + /**
79 + * Restores `snapshot` if the draft still equals `merged`; otherwise removes only
80 + * what the merge added, keeping later edits.
81 + */
82 + readonly undoMerge: (
83 + draftKey: string,
84 + snapshot: ComposerDraft,
85 + merged: ComposerDraft,
86 + ) => Promise<void>;
87 + readonly mergeIntoDraft: (
88 + draftKey: string,
89 + content: {
90 + readonly text: string;
91 + readonly attachments: ReadonlyArray<DraftComposerAttachment>;
92 + readonly sourceShareId: string;
93 + },
94 + ) => Promise<{ readonly skippedAttachmentCount: number }>;
95 + readonly selectAttachments: (
96 + share: IncomingShareDraft,
97 + environmentId: string,
98 + ) => ReturnType<typeof selectIncomingShareAttachmentsForServer>;
99 + /** Sweeps files no draft retained; the sweep re-checks ownership. */
100 + readonly releaseUnusedAttachments: (attachments: ReadonlyArray<DraftComposerAttachment>) => void;
101 + readonly onWarnings: (warnings: ReadonlyArray<string>) => void;
102 + readonly onImportFailure: (target: ShareImportTarget, error: unknown) => void;
103 + /** Reported even after the route left: the undo is still incomplete. */
104 + readonly onCancelFailure: (target: ShareImportTarget, error: unknown) => void;
105 + /** Leaves the draft route once its import is cancelled. */
106 + readonly leave: (target: ShareImportTarget) => void;
107 +}
108 +
109 +interface Entry {
110 + readonly target: ShareImportTarget;
111 + phase: ShareImportPhase;
112 + readonly controller: AbortController;
113 + /** Set when another draft of the same route took over before this import finished. */
114 + superseded: boolean;
115 + /** Set when the route left while a failed import still waits for retry or cancel. */
116 + detached: boolean;
117 + run: Promise<void>;
118 + /** The draft before the first attempt merged into it; cancel restores it. */
119 + backup: ComposerDraft | null;
120 + /** The draft as the last merge published it; cancel undoes against it. */
121 + merged: ComposerDraft | null;
122 + reservedFor: IncomingShareDestination | null;
123 + consumed: boolean;
124 + needsRestore: boolean;
125 + readonly listeners: Set<() => void>;
126 +}
127 +
128 +function keyOf(target: ShareImportTarget): string {
129 + return JSON.stringify([
130 + target.flowKey,
131 + target.routeKey,
132 + target.draftKey,
133 + target.destination.environmentId,
134 + target.destination.projectId,
135 + target.shareId,
136 + ]);
137 +}
138 +
139 +interface ImportedShare {
140 + readonly flowKey: string;
141 + readonly shareId: string;
142 +}
143 +
144 +/**
145 + * Share imports for draft routes. Imports do durable writes, so each is tied to
146 + * its target, not an atom node that can be rebuilt. Reading a target's phase atom
147 + * starts its import at most once; alerts, navigation and notifications all
148 + * follow an await, never run inside the read.
149 + */
150 +export function makeIncomingShareImports(deps: ShareImportDeps) {
151 + const entries = new Map<string, Entry>();
152 + // Shares each route already moved into a draft. Sending clears the draft's
153 + // import receipt a frame before the route leaves, so the route needs its
154 + // own record to tell "imported" from "vanished".
155 + const importedAtom = Atom.make<ReadonlyArray<ImportedShare>>([]).pipe(
156 + Atom.keepAlive,
157 + Atom.withLabel("mobile:incoming-share-imported"),
158 + );
159 + const isImportedAtom = Atom.family((key: string) =>
160 + Atom.make((get) =>
161 + get(importedAtom).some(
162 + (imported) => JSON.stringify([imported.flowKey, imported.shareId]) === key,
163 + ),
164 + ).pipe(Atom.withLabel("mobile:incoming-share-imported:route")),
165 + );
166 + // One flow key per running attempt, abandoned ones included: an abandoned
167 + // attempt can still be inside a draft write when the screen's target goes away.
168 + const runningAtom = Atom.make<ReadonlyArray<string>>([]).pipe(
169 + Atom.keepAlive,
170 + Atom.withLabel("mobile:incoming-share-import-running"),
171 + );
172 + const isRunningAtom = Atom.family((flowKey: string) =>
173 + Atom.make((get) => get(runningAtom).includes(flowKey)).pipe(
174 + Atom.withLabel("mobile:incoming-share-import-running:route"),
175 + ),
176 + );
177 +
178 + function notify(entry: Entry): void {
179 + // Listeners rebuild their node, which re-registers them; iterate a copy.
180 + for (const listener of Array.from(entry.listeners)) listener();
181 + }
182 +
183 + function advance(entry: Entry, event: ShareImportEvent): void {
184 + const next = transitionShareImport(entry.phase, event);
185 + if (next === entry.phase) return;
186 + entry.phase = next;
187 + notify(entry);
188 + }
189 +
190 + function settle(key: string, entry: Entry): void {
191 + if (entry.detached && entries.get(key) === entry) entries.delete(key);
192 + }
193 +
194 + async function runImport(key: string, entry: Entry): Promise<void> {
195 + const { signal } = entry.controller;
196 + const { shareId, destination, draftKey } = entry.target;
197 + // A phase atom node of a superseded import may still be cached; rebuilding
198 + // it lets a route that switches back start over instead of showing the
199 + // abandoned import's last phase.
200 + const stopped = () => {
201 + if (!signal.aborted) return false;
202 + if (entry.superseded) notify(entry);
203 + return true;
204 + };
205 + try {
206 + await deps.reserve(shareId, destination);
207 + entry.reservedFor = destination;
208 + // The durable reservation makes an interrupted transfer resume only in
209 + // this project instead of copying into a second project draft.
210 + if (stopped()) return;
211 + advance(entry, "reserved");
212 + const share = deps.getShare(shareId);
213 + if (!share) throw new Error("The shared content is no longer in the inbox.");
214 + const selected = deps.selectAttachments(share, destination.environmentId);
215 + if (selected.status === "pending") {
216 + throw new Error("Server attachment support is still loading.");
217 + }
218 + entry.needsRestore = true;
219 + let skippedAttachmentCount: number;
220 + try {
221 + ({ skippedAttachmentCount } = await deps.mergeIntoDraft(draftKey, {
222 + text: share.text,
223 + attachments: selected.attachments,
224 + sourceShareId: shareId,
225 + }));
226 + } finally {
227 + // The merge publishes before it persists, so read it back even when
228 + // persisting rejects.
229 + entry.merged = deps.readDraft(draftKey);
230 + }
231 + if (stopped()) return;
232 + advance(entry, "attached");
233 + await deps.consume(shareId);
234 + entry.consumed = true;
235 + // The consumed inbox draft was the last owner of files that never made
236 + // it into the composer draft (unsupported server, oversize, limit
237 + // skips). Release them even when the route left meanwhile.
238 + const retainedIds = new Set(
239 + deps.readDraft(draftKey).attachments.map((attachment) => attachment.id),
240 + );
241 + deps.releaseUnusedAttachments(
242 + share.attachments.filter((attachment) => !retainedIds.has(attachment.id)),
243 + );
244 + deps.registry.set(importedAtom, [
245 + ...deps.registry.get(importedAtom),
246 + { flowKey: entry.target.flowKey, shareId },
247 + ]);
248 + advance(entry, "consumed");
249 + entry.backup = null;
250 + settle(key, entry);
251 + if (stopped()) return;
252 + const warnings = [...share.warnings, ...selected.warnings];
253 + if (skippedAttachmentCount > 0) {
254 + warnings.push(
255 + `${skippedAttachmentCount} shared file${skippedAttachmentCount === 1 ? " was" : "s were"} skipped because this draft reached the attachment limit.`,
256 + );
257 + }
258 + if (warnings.length > 0) deps.onWarnings(warnings);
259 + } catch (error) {
260 + if (stopped()) return;
261 + advance(entry, "failed");
262 + deps.onImportFailure(entry.target, error);
263 + }
264 + }
265 +
266 + function begin(key: string, entry: Entry): void {
267 + entry.backup ??= deps.readDraft(entry.target.draftKey);
268 + advance(entry, "start");
269 + const { flowKey } = entry.target;
270 + deps.registry.set(runningAtom, [...deps.registry.get(runningAtom), flowKey]);
271 + entry.run = runImport(key, entry).finally(() => {
272 + const running = [...deps.registry.get(runningAtom)];
273 + running.splice(running.indexOf(flowKey), 1);
274 + deps.registry.set(runningAtom, running);
275 + });
276 + }
277 +
278 + function abandon(key: string, entry: Entry): void {
279 + entry.controller.abort();
280 + entries.delete(key);
281 + }
282 +
283 + function start(target: ShareImportTarget): Entry {
284 + const key = keyOf(target);
285 + const existing = entries.get(key);
286 + if (existing) return existing;
287 + // A route imports into one draft at a time; a superseded import stops at
288 + // its next step and no longer reports failures.
289 + for (const [otherKey, other] of entries) {
290 + if (other.target.flowKey === target.flowKey && isShareImportInFlight(other.phase)) {
291 + other.superseded = true;
292 + abandon(otherKey, other);
293 + }
294 + }
295 + const entry: Entry = {
296 + target,
297 + phase: "idle",
298 + controller: new AbortController(),
299 + superseded: false,
300 + detached: false,
301 + run: Promise.resolve(),
302 + backup: null,
303 + merged: null,
304 + reservedFor: null,
305 + consumed: false,
306 + needsRestore: false,
307 + listeners: new Set(),
308 + };
309 + entries.set(key, entry);
310 + begin(key, entry);
311 + return entry;
312 + }
313 +
314 + async function cancel(target: ShareImportTarget): Promise<void> {
315 + const key = keyOf(target);
316 + const entry = entries.get(key);
317 + if (!entry || entry.phase !== "failed") return;
318 + const { draftKey, shareId } = entry.target;
319 + advance(entry, "cancel");
320 + // Cancelling finishes even if the route leaves meanwhile: it only undoes
321 + // durable writes this import made.
322 + try {
323 + if (entry.needsRestore && entry.backup) {
324 + // The draft can change while a failed import waits for an answer, by the
325 + // user or an upload finishing, and a retried undo runs after its own
326 + // publish. Undoing against the merged draft keeps those changes.
327 + const merged = entry.merged ?? entry.backup;
328 + await deps.undoMerge(draftKey, entry.backup, merged);
329 + entry.needsRestore = false;
330 + // Sweep the share's merged-in files only once the inbox entry was
331 + // consumed: before that, the inbox still owns them for a later import.
332 + // The sweep skips files a draft still holds.
333 + if (entry.consumed) deps.releaseUnusedAttachments(merged.attachments);
334 + }
335 + if (entry.reservedFor) {
336 + await deps.release(shareId, entry.reservedFor);
337 + entry.reservedFor = null;
338 + }
339 + advance(entry, "cancelled");
340 + if (entry.detached) settle(key, entry);
341 + else deps.leave(entry.target);
342 + } catch (error) {
343 + advance(entry, "cancelFailed");
344 + deps.onCancelFailure(entry.target, error);
345 + }
346 + }
347 +
348 + return {
349 + phaseAtom: Atom.family((target: ShareImportTarget) =>
350 + Atom.make((get): ShareImportPhase => {
351 + const entry = start(target);
352 + const rebuild = () => get.refreshSelf();
353 + entry.listeners.add(rebuild);
354 + get.addFinalizer(() => entry.listeners.delete(rebuild));
355 + return entry.phase;
356 + }).pipe(Atom.withLabel("mobile:incoming-share-import")),
357 + ),
358 + /**
359 + * Whether an import for this route is still running, including one whose
360 + * target the screen no longer renders.
361 + */
362 + inFlightAtom: isRunningAtom,
363 + /** Resolves once the target's current attempt stops. */
364 + settled(target: ShareImportTarget): Promise<void> {
365 + return entries.get(keyOf(target))?.run ?? Promise.resolve();
366 + },
367 + /** Whether this route already moved the share into one of its drafts. */
368 + importedAtom(flowKey: string, shareId: string) {
369 + return isImportedAtom(JSON.stringify([flowKey, shareId]));
370 + },
371 + retry(target: ShareImportTarget): void {
372 + const key = keyOf(target);
373 + const entry = entries.get(key);
374 + if (!entry || entry.phase !== "failed") return;
375 + begin(key, entry);
376 + },
377 + cancel,
378 + /**
379 + * Abandons the imports of draft routes that are no longer on the stack.
380 + * A failed import keeps its retry and cancel until the user answers.
381 + * Resolves once the abandoned imports have stopped.
382 + */
383 + prune(liveFlowKeys: ReadonlySet<string>): Promise<void> {
384 + const stopping: Array<Promise<void>> = [];
385 + for (const [key, entry] of entries) {
386 + if (liveFlowKeys.has(entry.target.flowKey)) continue;
387 + if (entry.phase === "failed" || entry.phase === "cancelling") {
388 + entry.detached = true;
389 + } else {
390 + abandon(key, entry);
391 + stopping.push(entry.run);
392 + }
393 + }
394 + const imported = deps.registry.get(importedAtom);
395 + const kept = imported.filter((share) => liveFlowKeys.has(share.flowKey));
396 + if (kept.length !== imported.length) deps.registry.set(importedAtom, kept);
397 + return Promise.all(stopping).then(() => undefined);
398 + },
399 + };
400 +}
401 +
402 +export const idleShareImportPhaseAtom = Atom.make<ShareImportPhase>("idle").pipe(
403 + Atom.withLabel("mobile:incoming-share-import:idle"),
404 +);
405 +
406 +export const idleShareFlagAtom = Atom.make(false).pipe(
407 + Atom.withLabel("mobile:incoming-share-flag:idle"),
408 +);
apps/mobile/src/state/use-composer-drafts.ts
-23
@@ -1716,29 +1716,6 @@ export async function mergeComposerDraftContent(
1716 return { skippedAttachmentCount };
1717 }
1718
1719 -export async function restoreComposerDraftSnapshot(
1720 - draftKey: string,
1721 - snapshot: ComposerDraft,
1722 -): Promise<void> {
1723 - ensureComposerDraftsLoaded();
1724 - if (loadPromise !== null) {
1725 - await loadPromise;
1726 - }
1727 - if (persistTimer !== null) {
1728 - clearTimeout(persistTimer);
1729 - persistTimer = null;
1730 - }
1731 - const next = restoreComposerDraftSnapshotState(
1732 - appAtomRegistry.get(composerDraftsAtom),
1733 - draftKey,
1734 - snapshot,
1735 - );
1736 - appAtomRegistry.set(composerDraftsAtom, next);
1737 - await persistenceQueue.run(() =>
1738 - writePersistedComposerState(next, appAtomRegistry.get(stickyComposerModelSelectionAtom)),
1739 - );
1740 -}
1741 -
1719 export function sameComposerDraftState(a: ComposerDraft, b: ComposerDraft): boolean {
1720 return (
1721 a.text === b.text &&