Open-source Grok Bot alternative for named AI teammates. Local-first desktop, web, and mobile clients with per-bot tools, instructions, and memory. Independent fork of T3 Code.
Add native mobile share target support (#4021)
Julius Marmingefdca15471d92
diff --git a/apps/mobile/README.md b/apps/mobile/README.mdindex 552216bf3..0eb865cb7 100644--- a/apps/mobile/README.md+++ b/apps/mobile/README.md@@ -35,8 +35,8 @@ vp run ios:dev```If your Xcode account only has a Personal Team, use a bundle identifier you control and opt into the-reduced-capability local build. Personal Team builds omit the widget extension, push entitlement, and-native Sign in with Apple entitlement; builds without this opt-in are unchanged.+reduced-capability local build. Personal Team builds omit the widget and share extensions, push+entitlement, and native Sign in with Apple entitlement; builds without this opt-in are unchanged.```bashT3CODE_IOS_PERSONAL_TEAM=1 \diff --git a/apps/mobile/app.config.ts b/apps/mobile/app.config.tsindex e543a8d4a..c27be2e35 100644--- a/apps/mobile/app.config.ts+++ b/apps/mobile/app.config.ts@@ -84,6 +84,9 @@ function resolveAppVariant(value: string | undefined): AppVariant {}const variant = VARIANT_CONFIG[APP_VARIANT];+const iosBundleIdentifier = isIosPersonalTeamBuild+ ? personalTeamBundleIdentifier!+ : variant.iosBundleIdentifier;const dmSansFonts = {regular: "@expo-google-fonts/dm-sans/400Regular/DMSans_400Regular.ttf",@@ -94,8 +97,8 @@ const dmSansFonts = {const widgetsPlugin: NonNullable<ExpoConfig["plugins"]>[number] = ["expo-widgets",{- bundleIdentifier: `${variant.iosBundleIdentifier}.widgets`,- groupIdentifier: `group.${variant.iosBundleIdentifier}`,+ bundleIdentifier: `${iosBundleIdentifier}.widgets`,+ groupIdentifier: `group.${iosBundleIdentifier}`,enablePushNotifications: true,// Agent activity can update many times an hour; without the// frequent-updates entitlement iOS throttles the update budget sooner.@@ -111,6 +114,30 @@ const widgetsPlugin: NonNullable<ExpoConfig["plugins"]>[number] = [},];+const sharingPlugin: NonNullable<ExpoConfig["plugins"]>[number] = [+ "expo-sharing",+ {+ ios: {+ // Personal Teams cannot sign App Groups or extension targets. Keep the+ // reduced-capability local build usable while release builds expose the+ // real system share target.+ enabled: !isIosPersonalTeamBuild,+ extensionBundleIdentifier: `${iosBundleIdentifier}.sharing`,+ appGroupId: `group.${iosBundleIdentifier}`,+ activationRule: {+ supportsText: true,+ supportsWebUrlWithMaxCount: 1,+ supportsImageWithMaxCount: 8,+ },+ },+ android: {+ enabled: true,+ singleShareMimeTypes: ["text/plain", "image/*"],+ multipleShareMimeTypes: ["image/*"],+ },+ },+];+// These aliases match the fonts' PostScript names on iOS. Register the same// names on Android so React Native and the native composer use one set of// family names without waiting for runtime font loading.@@ -140,7 +167,7 @@ const config: ExpoConfig = {ios: {icon: variant.assets.iosIcon,supportsTablet: true,- bundleIdentifier: variant.iosBundleIdentifier,+ bundleIdentifier: iosBundleIdentifier,// Pin code signing to the T3 Tools team so non-interactive `expo run:ios`// does not fall back to a personal team (which cannot sign app groups,// Sign in with Apple, or push notification entitlements).@@ -202,6 +229,9 @@ const config: ExpoConfig = {],"expo-secure-store","expo-sqlite",+ ...(isIosPersonalTeamBuild+ ? [sharingPlugin]+ : ["./plugins/withShareExtensionDisplayName.cjs", sharingPlugin]),["expo-notifications",{diff --git a/apps/mobile/package.json b/apps/mobile/package.jsonindex 1f87560c8..5c5046cc5 100644--- a/apps/mobile/package.json+++ b/apps/mobile/package.json@@ -91,6 +91,7 @@"expo-paste-input": "^0.1.15","expo-quick-actions": "^6.0.2","expo-secure-store": "~56.0.4",+ "expo-sharing": "~56.0.18","expo-splash-screen": "~56.0.10","expo-sqlite": "~56.0.5","expo-symbols": "~56.0.6",diff --git a/apps/mobile/plugins/withShareExtensionDisplayName.cjs b/apps/mobile/plugins/withShareExtensionDisplayName.cjsnew file mode 100644index 000000000..27c57925e--- /dev/null+++ b/apps/mobile/plugins/withShareExtensionDisplayName.cjs@@ -0,0 +1,93 @@+"use strict";++// expo-sharing intentionally uses a fixed target name and also uses that+// internal target name as CFBundleDisplayName. Brand the extension while+// leaving its initially-empty signing team intact: Expo uses that state to+// select ios.appleTeamId and enable first-time profile provisioning.+//+// ORDERING: list this plugin BEFORE expo-sharing. Expo runs same-type mods in+// reverse registration order, so this executes after the extension exists.++const fs = require("fs");+const path = require("path");+const { withDangerousMod, withXcodeProject } = require("expo/config-plugins");++const TARGET_NAME = "expo-sharing-extension";++function stripComments(section) {+ return Object.fromEntries(+ Object.entries(section ?? {}).filter(([key]) => !key.endsWith("_comment")),+ );+}++function findByName(section, name) {+ return Object.entries(stripComments(section)).find(([, value]) => value?.name === name) ?? null;+}++function escapeXml(value) {+ return value+ .replaceAll("&", "&")+ .replaceAll("<", "<")+ .replaceAll(">", ">")+ .replaceAll('"', """)+ .replaceAll("'", "'");+}++function withDisplayNamePlist(config, displayName) {+ return withDangerousMod(config, [+ "ios",+ (cfg) => {+ const plistPath = path.join(cfg.modRequest.platformProjectRoot, TARGET_NAME, "Info.plist");+ if (!fs.existsSync(plistPath)) {+ throw new Error(+ `${TARGET_NAME}/Info.plist was not generated. Register withShareExtensionDisplayName before expo-sharing.`,+ );+ }+ const source = fs.readFileSync(plistPath, "utf8");+ const displayNamePattern = /(<key>CFBundleDisplayName<\/key>\s*<string>)[^<]*(<\/string>)/;+ if (!displayNamePattern.test(source)) {+ throw new Error(`Could not update CFBundleDisplayName in ${plistPath}.`);+ }+ const next = source.replace(displayNamePattern, `$1${escapeXml(displayName)}$2`);+ if (next !== source) {+ fs.writeFileSync(plistPath, next);+ }+ return cfg;+ },+ ]);+}++function withExtensionDisplayNameBuildSetting(config, displayName) {+ return withXcodeProject(config, (cfg) => {+ const objects = cfg.modResults.hash.project.objects;+ const targetEntry = findByName(objects.PBXNativeTarget, TARGET_NAME);+ if (!targetEntry) {+ throw new Error(+ `${TARGET_NAME} Xcode target was not generated. Register withShareExtensionDisplayName before expo-sharing.`,+ );+ }+ const target = targetEntry[1];+ const configurationList = stripComments(objects.XCConfigurationList)[+ target.buildConfigurationList+ ];+ if (!configurationList) {+ throw new Error(`Could not find build configurations for ${TARGET_NAME}.`);+ }+ const buildConfigurations = stripComments(objects.XCBuildConfiguration);+ for (const reference of configurationList.buildConfigurations ?? []) {+ const buildConfiguration = buildConfigurations[reference.value];+ if (buildConfiguration?.buildSettings) {+ buildConfiguration.buildSettings.INFOPLIST_KEY_CFBundleDisplayName = `"${displayName}"`;+ }+ }+ return cfg;+ });+}++module.exports = function withShareExtensionDisplayName(config) {+ const displayName = config.name;+ return withExtensionDisplayNameBuildSetting(+ withDisplayNamePlist(config, displayName),+ displayName,+ );+};diff --git a/apps/mobile/src/App.tsx b/apps/mobile/src/App.tsxindex c76d30100..1f198c33b 100644--- a/apps/mobile/src/App.tsx+++ b/apps/mobile/src/App.tsx@@ -11,6 +11,7 @@ import { createStaticNavigation, DarkTheme, DefaultTheme } from "@react-navigatiimport { RegistryContext } from "@effect/atom-react";import { ConfirmDialogHost } from "./components/ConfirmDialogHost";import { CloudAuthProvider } from "./features/cloud/CloudAuthProvider";+import { IncomingShareProvider } from "./features/sharing/IncomingShareProvider";import { AppearancePreferencesProvider } from "./features/settings/appearance/AppearancePreferencesProvider";import { RootStack } from "./Stack";import { appAtomRegistry } from "./state/atom-registry";@@ -26,7 +27,10 @@ const appLinking = {// <scheme>://expo-development-client/?url=<packager> — that URL addresses// the launcher, not app navigation. Without this filter it falls through// to the NotFound wildcard route on every dev launch.- filter: (url: string) => !url.includes("expo-development-client"),+ // expo-sharing uses a private lifecycle URL only to wake the app. The+ // persisted share inbox below owns navigation once the payload is durable.+ filter: (url: string) =>+ !url.includes("expo-development-client") && !url.includes("://expo-sharing"),};const Navigation = createStaticNavigation(RootStack);@@ -58,10 +62,12 @@ export default function App() {the system is in dark mode. */}{/* Blur target for Android dropdown backdrops — see appBlurTarget.ts. */}<BlurTargetView ref={appBlurTargetRef} style={{ flex: 1 }}>- <Navigation- linking={appLinking}- theme={colorScheme === "dark" ? DarkTheme : DefaultTheme}- />+ <IncomingShareProvider>+ <Navigation+ linking={appLinking}+ theme={colorScheme === "dark" ? DarkTheme : DefaultTheme}+ />+ </IncomingShareProvider><ConfirmDialogHost /></BlurTargetView>{/* Anchored-menu overlays render here — in-window, so thediff --git a/apps/mobile/src/Stack.tsx b/apps/mobile/src/Stack.tsxindex 3837e5dde..9d66839e0 100644--- a/apps/mobile/src/Stack.tsx+++ b/apps/mobile/src/Stack.tsx@@ -10,6 +10,7 @@ import {createNativeStackScreen,type NativeStackNavigationOptions,} from "@react-navigation/native-stack";+import { useEffect, useRef } from "react";import { DynamicColorIOS, Platform, Pressable, ScrollView, StyleSheet } from "react-native";import { useResolveClassNames } from "uniwind";@@ -52,6 +53,11 @@ import {SettingsLegalDocumentExternalHeaderButton,} from "./features/settings/components/SettingsLegalDocumentRouteScreen";import { useAppShortcuts } from "./features/shortcuts/useAppShortcuts";+import { useIncomingShare } from "./features/sharing/IncomingShareProvider";+import {+ EMPTY_INCOMING_SHARE_PRESENTATION_STATE,+ transitionIncomingSharePresentation,+} from "./features/sharing/incoming-share-presentation";import { nativeHeaderScrollEdgeEffects } from "./native/StackHeader";import { useThreadOutboxDrain } from "./state/use-thread-outbox-drain";@@ -275,12 +281,30 @@ function RootStackLayout(props: {readonly children: React.ReactNode;readonly state: NavigationState;}) {+ const navigation = useNavigation();+ const { pendingShare } = useIncomingShare();+ const sharePresentationRef = useRef(EMPTY_INCOMING_SHARE_PRESENTATION_STATE);useAgentNotificationNavigation();useThreadOutboxDrain();// Presents the T3 Connect onboarding sheet after an in-session sign-in.useConnectOnboardingNavigation();// Launcher app shortcuts: routes shortcut taps and tracks opened threads.useAppShortcuts(props.state);+ useEffect(() => {+ const topRouteName = props.state.routes[props.state.index]?.name;+ const transition = transitionIncomingSharePresentation(sharePresentationRef.current, {+ isShareSheetPresented: topRouteName === "NewTaskSheet",+ pendingShareId: pendingShare?.id ?? null,+ });+ sharePresentationRef.current = transition.state;+ if (!transition.shareIdToPresent) {+ return;+ }+ navigation.navigate("NewTaskSheet", {+ screen: "NewTask",+ params: { incomingShareId: transition.shareIdToPresent },+ });+ }, [navigation, pendingShare, props.state]);// Full pathname (sheets included) for keyboard-command scoping; the// workspace layout only reacts to the underlying non-overlay route.const path = getPathFromState(props.state, navigationPathConfig);diff --git a/apps/mobile/src/features/sharing/IncomingShareProvider.tsx b/apps/mobile/src/features/sharing/IncomingShareProvider.tsxnew file mode 100644index 000000000..04d371e5d--- /dev/null+++ b/apps/mobile/src/features/sharing/IncomingShareProvider.tsx@@ -0,0 +1,310 @@+import Constants from "expo-constants";+import * as Crypto from "expo-crypto";+import {+ clearSharedPayloads,+ getResolvedSharedPayloadsAsync,+ getSharedPayloads,+ type ResolvedSharePayload,+ type SharePayload,+} from "expo-sharing";+import React, { useCallback, useEffect, useEffectEvent, useMemo, useRef, useState } from "react";+import { Alert, AppState, Platform } from "react-native";++import {+ buildIncomingShareDraft,+ type IncomingShareDestination,+ type IncomingShareDraft,+} from "./incoming-share-model";+import { IncomingShareInbox } from "./incoming-share-inbox";+import {+ loadIncomingShareDrafts,+ removeIncomingShareDraft,+ writeIncomingShareDraft,+} from "./incoming-share-storage";++type IncomingShareContextValue = {+ readonly pendingShare: IncomingShareDraft | null;+ readonly isLoading: boolean;+ readonly error: Error | null;+ readonly getShare: (shareId: string) => IncomingShareDraft | null;+ readonly reserveShare: (shareId: string, destination: IncomingShareDestination) => Promise<void>;+ readonly releaseShareReservation: (+ shareId: string,+ expectedDestination: IncomingShareDestination,+ ) => Promise<void>;+ readonly consumeShare: (shareId: string) => Promise<void>;+ readonly refresh: () => Promise<void>;+};++const IncomingShareContext = React.createContext<IncomingShareContextValue | null>(null);++function receiveSharingEnabled(): boolean {+ if (Platform.OS === "android") {+ return true;+ }+ if (Platform.OS !== "ios") {+ return false;+ }+ return Constants.expoConfig?.extra?.iosPersonalTeamBuild !== true;+}++async function resolvedPayloadsForImages(): Promise<ReadonlyArray<ResolvedSharePayload>> {+ try {+ return await getResolvedSharedPayloadsAsync();+ } catch (error) {+ // iOS already gives the containing app a copied file:// URL, so raw+ // payloads remain usable. Android normally resolves content:// into a+ // private cache file; its modern File API can still read the raw URI when+ // resolution fails.+ console.warn("[incoming-share] could not resolve shared file metadata", error);+ return [];+ }+}++async function incomingShareIdForPayloads(payloads: ReadonlyArray<SharePayload>): Promise<string> {+ const fingerprint = JSON.stringify(+ payloads.map((payload) => ({+ shareType: payload.shareType,+ mimeType: payload.mimeType ?? null,+ value: payload.value,+ })),+ );+ const digest = await Crypto.digestStringAsync(Crypto.CryptoDigestAlgorithm.SHA256, fingerprint);+ return `share-${digest}`;+}++async function readBase64(uri: string): Promise<string> {+ const { File } = await import("expo-file-system");+ return new File(uri).base64();+}++async function removeOwnedFile(uri: string): Promise<void> {+ if (!uri.startsWith("file:")) {+ return;+ }+ try {+ const { File } = await import("expo-file-system");+ const file = new File(uri);+ if (file.exists) {+ file.delete();+ }+ } catch (error) {+ console.warn("[incoming-share] could not remove temporary shared file", error);+ }+}++async function removeReplayedImagePayloadFiles(+ payloads: ReadonlyArray<SharePayload>,+): Promise<void> {+ const uris = new Set<string>();+ for (const payload of payloads) {+ if (payload.shareType === "image") {+ uris.add(payload.value);+ }+ }+ if (uris.size === 0) {+ return;+ }+ const resolvedPayloads = await resolvedPayloadsForImages();+ for (const payload of resolvedPayloads) {+ if (payload.shareType === "image" && payload.contentUri) {+ uris.add(payload.contentUri);+ }+ }+ await Promise.all([...uris].map(removeOwnedFile));+}++// Keep one operation queue across provider remounts (including development+// Strict Mode remounts) so two app lifecycle notifications cannot ingest the+// same native handoff independently.+const incomingShareInbox = new IncomingShareInbox({+ loadDrafts: loadIncomingShareDrafts,+ writeDraft: writeIncomingShareDraft,+ removeDraft: removeIncomingShareDraft,+ getPayloads: getSharedPayloads,+ clearPayloads: clearSharedPayloads,+ buildDraft: async ({ payloads, id, createdAt }) => {+ const cleanupUris = new Set<string>();+ const resolvedPayloads = payloads.some((payload) => payload.shareType === "image")+ ? await resolvedPayloadsForImages()+ : [];+ const draft = await buildIncomingShareDraft({+ payloads,+ resolvedPayloads,+ fileReader: {+ readBase64,+ removeOwnedFile: (uri) => {+ cleanupUris.add(uri);+ },+ },+ id,+ createdAt,+ });+ return {+ draft,+ cleanup: async () => {+ await Promise.all([...cleanupUris].map(removeOwnedFile));+ },+ };+ },+ cleanupReplayedPayloads: removeReplayedImagePayloadFiles,+ idForPayloads: incomingShareIdForPayloads,+ now: () => new Date().toISOString(),+ onClearError: (error) => {+ console.warn("[incoming-share] could not acknowledge native payload", error);+ },+ onCleanupError: (error) => {+ console.warn("[incoming-share] could not remove temporary shared file", error);+ },+});++export function IncomingShareProvider(props: React.PropsWithChildren) {+ const enabled = receiveSharingEnabled();+ const [drafts, setDrafts] = useState<ReadonlyArray<IncomingShareDraft>>([]);+ const [isLoading, setIsLoading] = useState(true);+ const [error, setError] = useState<Error | null>(null);+ const refreshPromiseRef = useRef<Promise<void> | null>(null);+ const mountedRef = useRef(false);++ useEffect(() => {+ mountedRef.current = true;+ return () => {+ mountedRef.current = false;+ };+ }, []);++ const refresh = useCallback(async () => {+ if (refreshPromiseRef.current) {+ return refreshPromiseRef.current;+ }++ const operation = (async () => {+ try {+ const snapshot = await incomingShareInbox.refresh({ ingestNative: enabled });+ if (mountedRef.current) {+ setDrafts(snapshot);+ setError(null);+ }+ } catch (cause) {+ const persisted = await incomingShareInbox+ .refresh({ ingestNative: false })+ .catch(() => null);+ if (mountedRef.current) {+ if (persisted) {+ setDrafts(persisted);+ }+ setError(cause instanceof Error ? cause : new Error("Could not import shared content."));+ }+ }+ })().finally(() => {+ refreshPromiseRef.current = null;+ });++ refreshPromiseRef.current = operation;+ return operation;+ }, [enabled]);++ useEffect(() => {+ void refresh().finally(() => {+ if (mountedRef.current) {+ setIsLoading(false);+ }+ });+ }, [refresh]);++ const refreshOnAppActive = useEffectEvent(() => {+ void refresh();+ });++ useEffect(() => {+ if (!enabled) {+ return;+ }+ const subscription = AppState.addEventListener("change", (state) => {+ if (state === "active") {+ refreshOnAppActive();+ }+ });+ return () => subscription.remove();+ }, [enabled]);++ useEffect(() => {+ if (!error) {+ return;+ }+ Alert.alert("Could not import shared content", error.message, [+ { text: "Dismiss", style: "cancel", onPress: () => setError(null) },+ {+ text: "Retry",+ onPress: () => {+ setError(null);+ void refresh();+ },+ },+ ]);+ }, [error, refresh]);++ const consumeShare = useCallback(async (shareId: string) => {+ const snapshot = await incomingShareInbox.consume(shareId);+ if (mountedRef.current) {+ setDrafts(snapshot);+ }+ }, []);+ const reserveShare = useCallback(+ async (shareId: string, destination: IncomingShareDestination) => {+ const snapshot = await incomingShareInbox.reserve(shareId, destination);+ if (mountedRef.current) {+ setDrafts(snapshot);+ }+ },+ [],+ );+ const releaseShareReservation = useCallback(+ async (shareId: string, expectedDestination: IncomingShareDestination) => {+ const snapshot = await incomingShareInbox.releaseReservation(shareId, expectedDestination);+ if (mountedRef.current) {+ setDrafts(snapshot);+ }+ },+ [],+ );+ const getShare = useCallback(+ (shareId: string) => drafts.find((draft) => draft.id === shareId) ?? null,+ [drafts],+ );++ const value = useMemo<IncomingShareContextValue>(+ () => ({+ pendingShare: drafts[0] ?? null,+ isLoading,+ error,+ getShare,+ releaseShareReservation,+ reserveShare,+ consumeShare,+ refresh,+ }),+ [+ consumeShare,+ drafts,+ error,+ getShare,+ isLoading,+ refresh,+ releaseShareReservation,+ reserveShare,+ ],+ );++ return (+ <IncomingShareContext.Provider value={value}>{props.children}</IncomingShareContext.Provider>+ );+}++export function useIncomingShare(): IncomingShareContextValue {+ const value = React.use(IncomingShareContext);+ if (value === null) {+ throw new Error("useIncomingShare must be used within IncomingShareProvider.");+ }+ return value;+}diff --git a/apps/mobile/src/features/sharing/incoming-share-inbox.test.ts b/apps/mobile/src/features/sharing/incoming-share-inbox.test.tsnew file mode 100644index 000000000..ff50c6a91--- /dev/null+++ b/apps/mobile/src/features/sharing/incoming-share-inbox.test.ts@@ -0,0 +1,236 @@+import { describe, expect, it, vi } from "@effect/vitest";+import type { SharePayload } from "expo-sharing";++import type { IncomingShareDraft } from "./incoming-share-model";+import { IncomingShareInbox, type IncomingShareInboxDependencies } from "./incoming-share-inbox";++const PAYLOAD: SharePayload = {+ shareType: "text",+ mimeType: "text/plain",+ value: "Fix this",+};++function draft(id: string, createdAt = "2026-07-16T08:00:00.000Z"): IncomingShareDraft {+ return {+ schemaVersion: 1,+ id,+ createdAt,+ text: PAYLOAD.value,+ attachments: [],+ warnings: [],+ };+}++function deferred() {+ let resolve!: () => void;+ const promise = new Promise<void>((next) => {+ resolve = next;+ });+ return { promise, resolve };+}++function createHarness(overrides: Partial<IncomingShareInboxDependencies> = {}) {+ const persisted = new Map<string, IncomingShareDraft>();+ let payloads: ReadonlyArray<SharePayload> = [PAYLOAD];+ const dependencies: IncomingShareInboxDependencies = {+ loadDrafts: async () => [...persisted.values()],+ writeDraft: async (value) => {+ persisted.set(value.id, value);+ },+ removeDraft: async (shareId) => {+ persisted.delete(shareId);+ },+ getPayloads: () => payloads,+ clearPayloads: () => {+ payloads = [];+ },+ buildDraft: async ({ id, createdAt }) => ({+ draft: draft(id, createdAt),+ cleanup: async () => undefined,+ }),+ idForPayloads: async () => "share-stable",+ now: () => "2026-07-16T08:00:00.000Z",+ ...overrides,+ };+ return { inbox: new IncomingShareInbox(dependencies), persisted };+}++describe("IncomingShareInbox", () => {+ it("coalesces a replay of an already-persisted native handoff", async () => {+ const buildDraft = vi.fn(async ({ id, createdAt }) => ({+ draft: draft(id, createdAt),+ cleanup: async () => undefined,+ }));+ const cleanupReplayedPayloads = vi.fn(async () => undefined);+ const { inbox, persisted } = createHarness({ buildDraft, cleanupReplayedPayloads });+ persisted.set("share-stable", draft("share-stable"));++ await expect(inbox.refresh({ ingestNative: true })).resolves.toEqual([draft("share-stable")]);+ expect(buildDraft).not.toHaveBeenCalled();+ expect(cleanupReplayedPayloads).toHaveBeenCalledWith([PAYLOAD]);+ });++ it("serializes concurrent refreshes so one native payload creates one inbox item", async () => {+ const building = deferred();+ const buildDraft = vi.fn(async ({ id, createdAt }) => {+ await building.promise;+ return { draft: draft(id, createdAt), cleanup: async () => undefined };+ });+ const { inbox } = createHarness({ buildDraft });++ const first = inbox.refresh({ ingestNative: true });+ const second = inbox.refresh({ ingestNative: true });+ building.resolve();++ await expect(Promise.all([first, second])).resolves.toEqual([+ [draft("share-stable")],+ [draft("share-stable")],+ ]);+ expect(buildDraft).toHaveBeenCalledTimes(1);+ });++ it("orders consumption after an in-flight refresh without restoring stale state", async () => {+ const building = deferred();+ const { inbox, persisted } = createHarness({+ buildDraft: async ({ id, createdAt }) => {+ await building.promise;+ return { draft: draft(id, createdAt), cleanup: async () => undefined };+ },+ });++ const refresh = inbox.refresh({ ingestNative: true });+ const consume = inbox.consume("share-stable");+ building.resolve();++ await expect(refresh).resolves.toEqual([draft("share-stable")]);+ await expect(consume).resolves.toEqual([]);+ expect([...persisted.values()]).toEqual([]);+ });++ it("consumes only the addressed share when another share has identical content", async () => {+ const { inbox, persisted } = createHarness();+ persisted.set("share-first", draft("share-first", "2026-07-16T07:59:00.000Z"));+ persisted.set("share-second", draft("share-second"));++ await expect(inbox.refresh({ ingestNative: false })).resolves.toEqual([+ draft("share-second"),+ draft("share-first", "2026-07-16T07:59:00.000Z"),+ ]);+ await expect(inbox.consume("share-second")).resolves.toEqual([+ draft("share-first", "2026-07-16T07:59:00.000Z"),+ ]);+ expect([...persisted.values()]).toEqual([draft("share-first", "2026-07-16T07:59:00.000Z")]);+ });++ it("keeps content-identical shares addressable by their own ids", async () => {+ const { inbox, persisted } = createHarness();+ persisted.set("share-open-flow", draft("share-open-flow", "2026-07-16T07:59:00.000Z"));+ persisted.set("share-newer", draft("share-newer"));++ await expect(inbox.refresh({ ingestNative: false })).resolves.toEqual([+ draft("share-newer"),+ draft("share-open-flow", "2026-07-16T07:59:00.000Z"),+ ]);+ });++ it("does not acknowledge a supported payload when its durable write fails", async () => {+ const clearPayloads = vi.fn();+ const cleanup = vi.fn(async () => undefined);+ const { inbox } = createHarness({+ clearPayloads,+ buildDraft: async ({ id, createdAt }) => ({+ draft: draft(id, createdAt),+ cleanup,+ }),+ writeDraft: async () => {+ throw new Error("disk full");+ },+ });++ await expect(inbox.refresh({ ingestNative: true })).rejects.toThrow("disk full");+ expect(clearPayloads).not.toHaveBeenCalled();+ expect(cleanup).not.toHaveBeenCalled();+ });++ it("durably reserves a share for one project before draft import", async () => {+ const { inbox, persisted } = createHarness();+ persisted.set("share-stable", draft("share-stable"));+ const destination = { environmentId: "environment-1", projectId: "project-1" };++ await expect(inbox.reserve("share-stable", destination)).resolves.toEqual([+ { ...draft("share-stable"), destination },+ ]);+ expect(persisted.get("share-stable")?.destination).toEqual(destination);+ await expect(inbox.reserve("share-stable", destination)).resolves.toEqual([+ { ...draft("share-stable"), destination },+ ]);+ });++ it("rejects moving a reserved share to another project", async () => {+ const { inbox, persisted } = createHarness();+ persisted.set("share-stable", {+ ...draft("share-stable"),+ destination: { environmentId: "environment-1", projectId: "project-1" },+ });++ await expect(+ inbox.reserve("share-stable", {+ environmentId: "environment-1",+ projectId: "project-2",+ }),+ ).rejects.toThrow("already reserved");+ expect(persisted.get("share-stable")?.destination?.projectId).toBe("project-1");+ });++ it("conditionally releases a reservation when its project is unavailable", async () => {+ const { inbox, persisted } = createHarness();+ const destination = { environmentId: "environment-1", projectId: "project-1" };+ persisted.set("share-stable", { ...draft("share-stable"), destination });++ await expect(inbox.releaseReservation("share-stable", destination)).resolves.toEqual([+ draft("share-stable"),+ ]);+ expect(persisted.get("share-stable")?.destination).toBeUndefined();++ await expect(+ inbox.reserve("share-stable", {+ environmentId: "environment-2",+ projectId: "project-2",+ }),+ ).resolves.toEqual([+ {+ ...draft("share-stable"),+ destination: { environmentId: "environment-2", projectId: "project-2" },+ },+ ]);+ });++ it("does not release a reservation that changed concurrently", async () => {+ const { inbox, persisted } = createHarness();+ persisted.set("share-stable", {+ ...draft("share-stable"),+ destination: { environmentId: "environment-2", projectId: "project-2" },+ });++ await expect(+ inbox.releaseReservation("share-stable", {+ environmentId: "environment-1",+ projectId: "project-1",+ }),+ ).rejects.toThrow("reservation changed");+ expect(persisted.get("share-stable")?.destination?.projectId).toBe("project-2");+ });++ it("treats an already-removed share as an already-released reservation", async () => {+ const { inbox, persisted } = createHarness();+ persisted.set("share-other", draft("share-other"));++ await expect(+ inbox.releaseReservation("share-stable", {+ environmentId: "environment-1",+ projectId: "project-1",+ }),+ ).resolves.toEqual([draft("share-other")]);+ expect([...persisted.values()]).toEqual([draft("share-other")]);+ });+});diff --git a/apps/mobile/src/features/sharing/incoming-share-inbox.ts b/apps/mobile/src/features/sharing/incoming-share-inbox.tsnew file mode 100644index 000000000..1f61ea710--- /dev/null+++ b/apps/mobile/src/features/sharing/incoming-share-inbox.ts@@ -0,0 +1,193 @@+import type { SharePayload } from "expo-sharing";++import { SerializedAsyncQueue } from "../../lib/serialized-async-queue";+import {+ hasIncomingShareContent,+ type IncomingShareDestination,+ type IncomingShareDraft,+} from "./incoming-share-model";++export interface IncomingShareInboxDependencies {+ readonly loadDrafts: () => Promise<ReadonlyArray<IncomingShareDraft>>;+ readonly writeDraft: (draft: IncomingShareDraft) => Promise<void>;+ readonly removeDraft: (shareId: string) => Promise<void>;+ readonly getPayloads: () => ReadonlyArray<SharePayload>;+ readonly clearPayloads: () => void;+ readonly buildDraft: (input: {+ readonly payloads: ReadonlyArray<SharePayload>;+ readonly id: string;+ readonly createdAt: string;+ }) => Promise<{+ readonly draft: IncomingShareDraft;+ readonly cleanup: () => Promise<void>;+ }>;+ readonly cleanupReplayedPayloads?: (payloads: ReadonlyArray<SharePayload>) => Promise<void>;+ readonly idForPayloads: (payloads: ReadonlyArray<SharePayload>) => Promise<string>;+ readonly now: () => string;+ readonly onClearError?: (error: unknown) => void;+ readonly onCleanupError?: (error: unknown) => void;+}++export function sortAndDedupeIncomingShares(+ drafts: ReadonlyArray<IncomingShareDraft>,+): ReadonlyArray<IncomingShareDraft> {+ const ids = new Set<string>();+ return [...drafts]+ .sort((left, right) => right.createdAt.localeCompare(left.createdAt))+ .filter((draft) => {+ if (ids.has(draft.id)) {+ return false;+ }+ ids.add(draft.id);+ return true;+ });+}++/**+ * Serializes every durable inbox mutation. This prevents a stale storage load+ * or a foreground refresh from restoring an item after it has been consumed.+ */+export class IncomingShareInbox {+ private readonly operations = new SerializedAsyncQueue();++ constructor(private readonly dependencies: IncomingShareInboxDependencies) {}++ private runExclusive<T>(operation: () => Promise<T>): Promise<T> {+ return this.operations.run(operation);+ }++ private clearNativePayloads(): void {+ try {+ this.dependencies.clearPayloads();+ } catch (error) {+ this.dependencies.onClearError?.(error);+ }+ }++ private async cleanup(operation: () => Promise<void>): Promise<void> {+ try {+ await operation();+ } catch (error) {+ this.dependencies.onCleanupError?.(error);+ }+ }++ refresh(options: { readonly ingestNative: boolean }): Promise<ReadonlyArray<IncomingShareDraft>> {+ return this.runExclusive(async () => {+ const loaded = await this.dependencies.loadDrafts();+ const persisted = sortAndDedupeIncomingShares(loaded);+ if (!options.ingestNative) {+ return persisted;+ }++ const payloads = this.dependencies.getPayloads();+ if (payloads.length === 0) {+ return persisted;+ }++ // A share extension payload remains available until the containing app+ // acknowledges it. Use a content-derived id so a crash after the durable+ // write but before acknowledgement reuses the same inbox item.+ const shareId = await this.dependencies.idForPayloads(payloads);+ if (loaded.some((draft) => draft.id === shareId)) {+ if (this.dependencies.cleanupReplayedPayloads) {+ await this.cleanup(() => this.dependencies.cleanupReplayedPayloads!(payloads));+ }+ this.clearNativePayloads();+ return persisted;+ }++ const built = await this.dependencies.buildDraft({+ payloads,+ id: shareId,+ createdAt: this.dependencies.now(),+ });+ const { draft } = built;+ if (!hasIncomingShareContent(draft)) {+ // Unsupported native payloads cannot become actionable on retry and+ // would otherwise reopen the project picker on every foreground.+ await this.cleanup(built.cleanup);+ this.clearNativePayloads();+ throw new Error(+ draft.warnings[0] ?? "The shared content is not supported by the composer.",+ );+ }++ // The durable inbox write is the transaction boundary. Never clear the+ // native handoff first: a process termination must leave one recoverable+ // copy on one side of the boundary.+ await this.dependencies.writeDraft(draft);+ await this.cleanup(built.cleanup);+ this.clearNativePayloads();+ return sortAndDedupeIncomingShares([draft, ...persisted]);+ });+ }++ consume(shareId: string): Promise<ReadonlyArray<IncomingShareDraft>> {+ return this.runExclusive(async () => {+ // The stable payload-derived id already coalesces retries of the same+ // native handoff. Payload equality cannot identify duplicate handoffs:+ // users may intentionally share identical content more than once.+ await this.dependencies.removeDraft(shareId);+ return sortAndDedupeIncomingShares(await this.dependencies.loadDrafts());+ });+ }++ reserve(+ shareId: string,+ destination: IncomingShareDestination,+ ): Promise<ReadonlyArray<IncomingShareDraft>> {+ return this.runExclusive(async () => {+ const persisted = await this.dependencies.loadDrafts();+ const target = persisted.find((draft) => draft.id === shareId);+ if (!target) {+ throw new Error("The shared content is no longer available.");+ }+ if (target.destination) {+ if (+ target.destination.environmentId !== destination.environmentId ||+ target.destination.projectId !== destination.projectId+ ) {+ throw new Error("The shared content is already reserved for another project draft.");+ }+ return sortAndDedupeIncomingShares(persisted);+ }++ const reserved = { ...target, destination };+ await this.dependencies.writeDraft(reserved);+ return sortAndDedupeIncomingShares(+ persisted.map((draft) => (draft.id === shareId ? reserved : draft)),+ );+ });+ }++ releaseReservation(+ shareId: string,+ expectedDestination: IncomingShareDestination,+ ): Promise<ReadonlyArray<IncomingShareDraft>> {+ return this.runExclusive(async () => {+ const persisted = await this.dependencies.loadDrafts();+ const target = persisted.find((draft) => draft.id === shareId);+ if (!target) {+ // Conditional release is idempotent: if another operation already+ // consumed the share, no reservation remains to clean up.+ return sortAndDedupeIncomingShares(persisted);+ }+ if (!target.destination) {+ return sortAndDedupeIncomingShares(persisted);+ }+ if (+ target.destination.environmentId !== expectedDestination.environmentId ||+ target.destination.projectId !== expectedDestination.projectId+ ) {+ throw new Error("The shared content reservation changed before it could be released.");+ }++ const { destination: _destination, ...unreserved } = target;+ await this.dependencies.writeDraft(unreserved);+ return sortAndDedupeIncomingShares(+ persisted.map((draft) => (draft.id === shareId ? unreserved : draft)),+ );+ });+ }+}diff --git a/apps/mobile/src/features/sharing/incoming-share-model.test.ts b/apps/mobile/src/features/sharing/incoming-share-model.test.tsnew file mode 100644index 000000000..07ede18b8--- /dev/null+++ b/apps/mobile/src/features/sharing/incoming-share-model.test.ts@@ -0,0 +1,196 @@+import { describe, expect, it, vi } from "@effect/vitest";+import {+ PROVIDER_SEND_TURN_MAX_ATTACHMENTS,+ PROVIDER_SEND_TURN_MAX_IMAGE_BYTES,+} from "@t3tools/contracts";+import type { ResolvedSharePayload, SharePayload } from "expo-sharing";++import { buildIncomingShareDraft, hasIncomingShareContent } from "./incoming-share-model";++describe("incoming native shares", () => {+ it("converts shared text, URLs, and images into a durable composer draft", async () => {+ const image: SharePayload = {+ shareType: "image",+ value: "file:///shared/Screenshot.png",+ mimeType: "image/png",+ };+ const payloads: SharePayload[] = [+ { shareType: "text", value: "Please explain this error" },+ { shareType: "url", value: "https://example.com/issue/1" },+ { shareType: "text", value: "Please explain this error" },+ image,+ ];+ const resolvedImage: ResolvedSharePayload = {+ ...image,+ contentUri: image.value,+ contentType: "image",+ contentMimeType: "image/png",+ contentSize: 3,+ originalName: "Screenshot.png",+ };+ const removeOwnedFile = vi.fn(() => Promise.resolve());++ const result = await buildIncomingShareDraft({+ id: "share-1",+ createdAt: "2026-07-15T10:00:00.000Z",+ payloads,+ resolvedPayloads: [resolvedImage],+ fileReader: {+ readBase64: async () => "YWJj",+ removeOwnedFile,+ },+ });++ expect(result).toEqual({+ schemaVersion: 1,+ id: "share-1",+ createdAt: "2026-07-15T10:00:00.000Z",+ text: "Please explain this error\n\nhttps://example.com/issue/1",+ attachments: [+ {+ id: "share-1:image:3",+ type: "image",+ name: "Screenshot.png",+ mimeType: "image/png",+ sizeBytes: 3,+ dataUrl: "data:image/png;base64,YWJj",+ previewUri: "data:image/png;base64,YWJj",+ },+ ],+ warnings: [],+ });+ expect(removeOwnedFile).toHaveBeenCalledWith(image.value);+ expect(hasIncomingShareContent(result)).toBe(true);+ });++ it("skips oversized images and releases the temporary native file", async () => {+ const image: SharePayload = {+ shareType: "image",+ value: "file:///shared/huge.png",+ mimeType: "image/png",+ };+ const readBase64 = vi.fn(async () => "unused");+ const removeOwnedFile = vi.fn(() => Promise.resolve());++ const result = await buildIncomingShareDraft({+ id: "share-2",+ createdAt: "2026-07-15T10:00:00.000Z",+ payloads: [image],+ resolvedPayloads: [+ {+ ...image,+ contentUri: image.value,+ contentType: "image",+ contentMimeType: "image/png",+ contentSize: PROVIDER_SEND_TURN_MAX_IMAGE_BYTES + 1,+ originalName: "huge.png",+ },+ ],+ fileReader: { readBase64, removeOwnedFile },+ });++ expect(result.attachments).toEqual([]);+ expect(result.warnings).toEqual(["'huge.png' exceeds the 10 MB attachment limit."]);+ expect(readBase64).not.toHaveBeenCalled();+ expect(removeOwnedFile).toHaveBeenCalledWith(image.value);+ expect(hasIncomingShareContent(result)).toBe(false);+ });++ it("releases every temporary file when a share exceeds the attachment limit", async () => {+ const payloads = Array.from({ length: PROVIDER_SEND_TURN_MAX_ATTACHMENTS + 1 }, (_, index) => ({+ shareType: "image" as const,+ value: `file:///shared/${index}.png`,+ mimeType: "image/png",+ }));+ const removeOwnedFile = vi.fn(() => Promise.resolve());+ const readBase64 = vi.fn(async () => "YWJj");++ const result = await buildIncomingShareDraft({+ id: "share-3",+ createdAt: "2026-07-15T10:00:00.000Z",+ payloads,+ resolvedPayloads: [],+ fileReader: { readBase64, removeOwnedFile },+ });++ expect(result.attachments).toHaveLength(PROVIDER_SEND_TURN_MAX_ATTACHMENTS);+ expect(result.warnings).toEqual([+ `Only the first ${PROVIDER_SEND_TURN_MAX_ATTACHMENTS} shared images were attached.`,+ ]);+ expect(readBase64).toHaveBeenCalledTimes(PROVIDER_SEND_TURN_MAX_ATTACHMENTS);+ expect(removeOwnedFile).toHaveBeenCalledTimes(payloads.length);+ });++ it("maps duplicate image payloads to distinct resolved files", async () => {+ const duplicate: SharePayload = {+ shareType: "image",+ value: "content://shared/screenshot",+ mimeType: "image/png",+ };+ const resolvedPayloads: ResolvedSharePayload[] = [+ {+ ...duplicate,+ contentUri: "file:///cache/first.png",+ contentType: "image",+ contentMimeType: "image/png",+ contentSize: 3,+ originalName: "first.png",+ },+ {+ ...duplicate,+ contentUri: "file:///cache/second.png",+ contentType: "image",+ contentMimeType: "image/png",+ contentSize: 3,+ originalName: "second.png",+ },+ ];+ const readBase64 = vi.fn(async (uri: string) =>+ uri.includes("first") ? "Zmlyc3Q=" : "c2Vjb25k",+ );+ const removeOwnedFile = vi.fn(async () => undefined);++ const result = await buildIncomingShareDraft({+ id: "share-duplicates",+ createdAt: "2026-07-16T08:00:00.000Z",+ payloads: [duplicate, duplicate],+ resolvedPayloads,+ fileReader: { readBase64, removeOwnedFile },+ });++ expect(readBase64.mock.calls.map(([uri]) => uri)).toEqual([+ "file:///cache/first.png",+ "file:///cache/second.png",+ ]);+ expect(result.attachments.map((attachment) => attachment.name)).toEqual([+ "first.png",+ "second.png",+ ]);+ expect(removeOwnedFile).toHaveBeenCalledWith("file:///cache/first.png");+ expect(removeOwnedFile).toHaveBeenCalledWith("file:///cache/second.png");+ });++ it("keeps imported content when temporary-file cleanup fails", async () => {+ const image: SharePayload = {+ shareType: "image",+ value: "file:///shared/screenshot.png",+ mimeType: "image/png",+ };++ const result = await buildIncomingShareDraft({+ id: "share-cleanup-failure",+ createdAt: "2026-07-16T08:00:00.000Z",+ payloads: [image],+ resolvedPayloads: [],+ fileReader: {+ readBase64: async () => "YWJj",+ removeOwnedFile: async () => {+ throw new Error("file is busy");+ },+ },+ });++ expect(result.attachments).toHaveLength(1);+ expect(result.warnings).toEqual([]);+ });+});diff --git a/apps/mobile/src/features/sharing/incoming-share-model.ts b/apps/mobile/src/features/sharing/incoming-share-model.tsnew file mode 100644index 000000000..873574209--- /dev/null+++ b/apps/mobile/src/features/sharing/incoming-share-model.ts@@ -0,0 +1,217 @@+import {+ PROVIDER_SEND_TURN_MAX_ATTACHMENTS,+ PROVIDER_SEND_TURN_MAX_IMAGE_BYTES,+} from "@t3tools/contracts";+import * as Schema from "effect/Schema";+import type { ResolvedSharePayload, SharePayload } from "expo-sharing";++import { DraftComposerImageAttachmentSchema } from "../../lib/composer-image-schema";+import type { DraftComposerImageAttachment } from "../../lib/composerImages";+import { estimateBase64ByteSize } from "../../lib/base64";++export interface IncomingShareDraft {+ readonly schemaVersion: 1;+ readonly id: string;+ readonly createdAt: string;+ readonly destination?: IncomingShareDestination;+ readonly text: string;+ readonly attachments: ReadonlyArray<DraftComposerImageAttachment>;+ readonly warnings: ReadonlyArray<string>;+}++export interface IncomingShareDestination {+ readonly environmentId: string;+ readonly projectId: string;+}++const IncomingShareDestinationSchema = Schema.Struct({+ environmentId: Schema.String,+ projectId: Schema.String,+});++export const IncomingShareDraftSchema = Schema.Struct({+ schemaVersion: Schema.Literal(1),+ id: Schema.String,+ createdAt: Schema.String,+ destination: Schema.optional(IncomingShareDestinationSchema),+ text: Schema.String,+ attachments: Schema.Array(DraftComposerImageAttachmentSchema),+ warnings: Schema.Array(Schema.String),+});++const decodeIncomingShareDraftSync = Schema.decodeUnknownSync(IncomingShareDraftSchema);++export function decodeIncomingShareDraft(value: unknown): IncomingShareDraft {+ return decodeIncomingShareDraftSync(value);+}++export interface IncomingShareFileReader {+ readonly readBase64: (uri: string) => Promise<string>;+ readonly removeOwnedFile: (uri: string) => Promise<void> | void;+}++function sharedText(payloads: ReadonlyArray<SharePayload>): string {+ const seen = new Set<string>();+ const values: string[] = [];+ for (const payload of payloads) {+ if (payload.shareType !== "text" && payload.shareType !== "url") {+ continue;+ }+ const value = payload.value.trim();+ if (!value || seen.has(value)) {+ continue;+ }+ seen.add(value);+ values.push(value);+ }+ return values.join("\n\n");+}++function resolvedImageFor(+ payload: SharePayload,+ index: number,+ resolvedPayloads: ReadonlyArray<ResolvedSharePayload>,+ consumedIndexes: Set<number>,+): ResolvedSharePayload | undefined {+ const sameIndex = resolvedPayloads[index];+ if (+ !consumedIndexes.has(index) &&+ sameIndex?.shareType === payload.shareType &&+ sameIndex.value === payload.value+ ) {+ consumedIndexes.add(index);+ return sameIndex;+ }+ const matchingIndex = resolvedPayloads.findIndex(+ (candidate, candidateIndex) =>+ !consumedIndexes.has(candidateIndex) &&+ candidate.shareType === payload.shareType &&+ candidate.value === payload.value,+ );+ if (matchingIndex < 0) {+ return undefined;+ }+ consumedIndexes.add(matchingIndex);+ return resolvedPayloads[matchingIndex];+}++async function releaseOwnedFiles(+ fileReader: IncomingShareFileReader,+ uris: ReadonlyArray<string | undefined>,+): Promise<void> {+ for (const uri of new Set(uris.filter((candidate): candidate is string => Boolean(candidate)))) {+ try {+ await fileReader.removeOwnedFile(uri);+ } catch {+ // Temporary-file cleanup is best-effort and must never discard content+ // that was successfully converted into a durable composer attachment.+ }+ }+}++function fallbackName(uri: string, index: number, mimeType: string): string {+ try {+ const pathName = new URL(uri).pathname.split("/").findLast((segment) => segment.length > 0);+ if (pathName) {+ return decodeURIComponent(pathName);+ }+ } catch {+ // Fall through to a deterministic attachment name.+ }+ const extension = mimeType.split("/")[1]?.replace(/[^a-z0-9.+-]/gi, "") || "png";+ return `shared-image-${index + 1}.${extension}`;+}++export async function buildIncomingShareDraft(input: {+ readonly payloads: ReadonlyArray<SharePayload>;+ readonly resolvedPayloads: ReadonlyArray<ResolvedSharePayload>;+ readonly fileReader: IncomingShareFileReader;+ readonly id: string;+ readonly createdAt: string;+}): Promise<IncomingShareDraft> {+ const attachments: DraftComposerImageAttachment[] = [];+ const warnings: string[] = [];+ const consumedResolvedPayloadIndexes = new Set<number>();+ let warnedAttachmentLimit = false;++ for (const [index, payload] of input.payloads.entries()) {+ if (payload.shareType !== "image") {+ continue;+ }+ const resolved = resolvedImageFor(+ payload,+ index,+ input.resolvedPayloads,+ consumedResolvedPayloadIndexes,+ );+ const uri = resolved?.contentUri ?? payload.value;+ if (attachments.length >= PROVIDER_SEND_TURN_MAX_ATTACHMENTS) {+ if (!warnedAttachmentLimit) {+ warnings.push(+ `Only the first ${PROVIDER_SEND_TURN_MAX_ATTACHMENTS} shared images were attached.`,+ );+ warnedAttachmentLimit = true;+ }+ await releaseOwnedFiles(input.fileReader, [uri, payload.value]);+ continue;+ }++ const mimeType = (resolved?.contentMimeType ?? payload.mimeType ?? "image/png").toLowerCase();+ if (!uri || !mimeType.startsWith("image/")) {+ warnings.push("One shared item was not a supported image.");+ await releaseOwnedFiles(input.fileReader, [uri, payload.value]);+ continue;+ }+ if (+ resolved?.contentSize !== null &&+ resolved?.contentSize !== undefined &&+ resolved.contentSize > PROVIDER_SEND_TURN_MAX_IMAGE_BYTES+ ) {+ warnings.push(+ `'${resolved.originalName ?? fallbackName(uri, index, mimeType)}' exceeds the 10 MB attachment limit.`,+ );+ await releaseOwnedFiles(input.fileReader, [uri, payload.value]);+ continue;+ }++ try {+ const base64 = await input.fileReader.readBase64(uri);+ const sizeBytes = resolved?.contentSize ?? estimateBase64ByteSize(base64);+ if (sizeBytes <= 0 || sizeBytes > PROVIDER_SEND_TURN_MAX_IMAGE_BYTES) {+ warnings.push(+ `'${resolved?.originalName ?? fallbackName(uri, index, mimeType)}' exceeds the 10 MB attachment limit.`,+ );+ continue;+ }+ const dataUrl = `data:${mimeType};base64,${base64}`;+ attachments.push({+ id: `${input.id}:image:${index}`,+ type: "image",+ name: resolved?.originalName ?? fallbackName(uri, index, mimeType),+ mimeType,+ sizeBytes,+ dataUrl,+ // The share provider's file is temporary. A data-backed preview keeps+ // the composer valid after its source file and App Group entry are gone.+ previewUri: dataUrl,+ });+ } catch {+ warnings.push(`Could not read '${fallbackName(uri, index, mimeType)}'.`);+ } finally {+ await releaseOwnedFiles(input.fileReader, [uri, payload.value]);+ }+ }++ return {+ schemaVersion: 1,+ id: input.id,+ createdAt: input.createdAt,+ text: sharedText(input.payloads),+ attachments,+ warnings,+ };+}++export function hasIncomingShareContent(draft: IncomingShareDraft): boolean {+ return draft.text.trim().length > 0 || draft.attachments.length > 0;+}diff --git a/apps/mobile/src/features/sharing/incoming-share-presentation.test.ts b/apps/mobile/src/features/sharing/incoming-share-presentation.test.tsnew file mode 100644index 000000000..c46ee6eb3--- /dev/null+++ b/apps/mobile/src/features/sharing/incoming-share-presentation.test.ts@@ -0,0 +1,92 @@+import { describe, expect, it } from "@effect/vitest";++import {+ EMPTY_INCOMING_SHARE_PRESENTATION_STATE,+ transitionIncomingSharePresentation,+} from "./incoming-share-presentation";++describe("incoming share presentation", () => {+ it("does not reopen a dismissed share when refresh returns a new object for the same id", () => {+ const presented = transitionIncomingSharePresentation(EMPTY_INCOMING_SHARE_PRESENTATION_STATE, {+ isShareSheetPresented: false,+ pendingShareId: "share-1",+ });+ expect(presented.shareIdToPresent).toBe("share-1");++ const whilePresented = transitionIncomingSharePresentation(presented.state, {+ isShareSheetPresented: true,+ pendingShareId: "share-1",+ });+ expect(whilePresented).toEqual({ state: presented.state, shareIdToPresent: null });++ const dismissed = transitionIncomingSharePresentation(whilePresented.state, {+ isShareSheetPresented: false,+ pendingShareId: "share-1",+ });+ expect(dismissed.state.dismissedShareId).toBe("share-1");++ expect(+ transitionIncomingSharePresentation(dismissed.state, {+ isShareSheetPresented: false,+ pendingShareId: "share-1",+ }),+ ).toEqual({ state: dismissed.state, shareIdToPresent: null });+ });++ it("presents the next queued share immediately after the previous sheet closes", () => {+ const first = transitionIncomingSharePresentation(EMPTY_INCOMING_SHARE_PRESENTATION_STATE, {+ isShareSheetPresented: false,+ pendingShareId: "share-1",+ });++ const next = transitionIncomingSharePresentation(first.state, {+ isShareSheetPresented: false,+ pendingShareId: "share-2",+ });+ expect(next.shareIdToPresent).toBe("share-2");+ expect(next.state).toEqual({ presentedShareId: "share-2", dismissedShareId: null });+ });++ it("forgets dismissal after consumption so a later handoff may reuse the id", () => {+ const dismissed = {+ presentedShareId: null,+ dismissedShareId: "share-1",+ };+ const consumed = transitionIncomingSharePresentation(dismissed, {+ isShareSheetPresented: false,+ pendingShareId: null,+ });+ expect(consumed.state).toEqual(EMPTY_INCOMING_SHARE_PRESENTATION_STATE);++ expect(+ transitionIncomingSharePresentation(consumed.state, {+ isShareSheetPresented: false,+ pendingShareId: "share-1",+ }).shareIdToPresent,+ ).toBe("share-1");+ });++ it("forgets a consumed presentation while its sheet is still mounted", () => {+ const presented = {+ presentedShareId: "share-1",+ dismissedShareId: null,+ };+ const consumed = transitionIncomingSharePresentation(presented, {+ isShareSheetPresented: true,+ pendingShareId: null,+ });+ expect(consumed.state).toEqual(EMPTY_INCOMING_SHARE_PRESENTATION_STATE);++ const replacementWhileOpen = transitionIncomingSharePresentation(consumed.state, {+ isShareSheetPresented: true,+ pendingShareId: "share-1",+ });+ expect(replacementWhileOpen.shareIdToPresent).toBeNull();+ expect(+ transitionIncomingSharePresentation(replacementWhileOpen.state, {+ isShareSheetPresented: false,+ pendingShareId: "share-1",+ }).shareIdToPresent,+ ).toBe("share-1");+ });+});diff --git a/apps/mobile/src/features/sharing/incoming-share-presentation.ts b/apps/mobile/src/features/sharing/incoming-share-presentation.tsnew file mode 100644index 000000000..663d9dc17--- /dev/null+++ b/apps/mobile/src/features/sharing/incoming-share-presentation.ts@@ -0,0 +1,71 @@+export interface IncomingSharePresentationState {+ readonly presentedShareId: string | null;+ readonly dismissedShareId: string | null;+}++export interface IncomingSharePresentationTransition {+ readonly state: IncomingSharePresentationState;+ readonly shareIdToPresent: string | null;+}++export const EMPTY_INCOMING_SHARE_PRESENTATION_STATE: IncomingSharePresentationState = {+ presentedShareId: null,+ dismissedShareId: null,+};++/**+ * Tracks presentation by durable share id rather than object identity. A user+ * dismissal suppresses only that inbox item until it is consumed or replaced.+ */+export function transitionIncomingSharePresentation(+ state: IncomingSharePresentationState,+ input: {+ readonly isShareSheetPresented: boolean;+ readonly pendingShareId: string | null;+ },+): IncomingSharePresentationTransition {+ if (input.isShareSheetPresented) {+ if (state.presentedShareId !== null && input.pendingShareId !== state.presentedShareId) {+ // Consumption may happen while the sheet remains mounted. Forget the+ // old presentation immediately so a later handoff may reuse its id.+ return {+ state: EMPTY_INCOMING_SHARE_PRESENTATION_STATE,+ shareIdToPresent: null,+ };+ }+ return { state, shareIdToPresent: null };+ }++ let nextState = state;+ if (state.presentedShareId !== null) {+ if (input.pendingShareId === state.presentedShareId) {+ return {+ state: {+ presentedShareId: null,+ dismissedShareId: state.presentedShareId,+ },+ shareIdToPresent: null,+ };+ }+ nextState = { ...state, presentedShareId: null };+ }++ if (input.pendingShareId === null) {+ return {+ state: EMPTY_INCOMING_SHARE_PRESENTATION_STATE,+ shareIdToPresent: null,+ };+ }++ if (nextState.dismissedShareId === input.pendingShareId) {+ return { state: nextState, shareIdToPresent: null };+ }++ return {+ state: {+ presentedShareId: input.pendingShareId,+ dismissedShareId: null,+ },+ shareIdToPresent: input.pendingShareId,+ };+}diff --git a/apps/mobile/src/features/sharing/incoming-share-storage.ts b/apps/mobile/src/features/sharing/incoming-share-storage.tsnew file mode 100644index 000000000..8364b4c98--- /dev/null+++ b/apps/mobile/src/features/sharing/incoming-share-storage.ts@@ -0,0 +1,80 @@+import * as Schema from "effect/Schema";++import { decodeIncomingShareDraft, type IncomingShareDraft } from "./incoming-share-model";++const INCOMING_SHARE_DIRECTORY = "incoming-shares";++export class IncomingShareStorageError extends Schema.TaggedErrorClass<IncomingShareStorageError>()(+ "IncomingShareStorageError",+ {+ operation: Schema.Literals(["load", "write", "remove"]),+ shareId: Schema.NullOr(Schema.String),+ cause: Schema.Defect(),+ },+) {+ override get message(): string {+ return `Incoming share storage operation ${this.operation} failed for ${this.shareId ?? "unknown"}.`;+ }+}++function fileName(shareId: string): string {+ return `${encodeURIComponent(shareId)}.json`;+}++async function getDirectory() {+ const { Directory, Paths } = await import("expo-file-system");+ const directory = new Directory(Paths.document, INCOMING_SHARE_DIRECTORY);+ directory.create({ idempotent: true, intermediates: true });+ return directory;+}++async function getFile(shareId: string) {+ const { File } = await import("expo-file-system");+ return new File(await getDirectory(), fileName(shareId));+}++export async function loadIncomingShareDrafts(): Promise<ReadonlyArray<IncomingShareDraft>> {+ try {+ const { File } = await import("expo-file-system");+ const drafts: IncomingShareDraft[] = [];+ for (const entry of (await getDirectory()).list()) {+ if (!(entry instanceof File) || !entry.name.endsWith(".json")) {+ continue;+ }+ try {+ drafts.push(decodeIncomingShareDraft(JSON.parse(await entry.text()) as unknown));+ } catch (cause) {+ console.warn(+ "[incoming-share] ignored invalid persisted share",+ new IncomingShareStorageError({ operation: "load", shareId: null, cause }),+ );+ }+ }+ return drafts.sort((left, right) => right.createdAt.localeCompare(left.createdAt));+ } catch (cause) {+ throw new IncomingShareStorageError({ operation: "load", shareId: null, cause });+ }+}++export async function writeIncomingShareDraft(draft: IncomingShareDraft): Promise<void> {+ try {+ const file = await getFile(draft.id);+ if (!file.exists) {+ file.create({ intermediates: true, overwrite: true });+ }+ file.write(JSON.stringify(draft));+ } catch (cause) {+ throw new IncomingShareStorageError({ operation: "write", shareId: draft.id, cause });+ }+}++export async function removeIncomingShareDraft(shareId: string): Promise<void> {+ try {+ const file = await getFile(shareId);+ if (file.exists) {+ file.delete();+ }+ } catch (cause) {+ throw new IncomingShareStorageError({ operation: "remove", shareId, cause });+ }+}diff --git a/apps/mobile/src/features/threads/NewTaskDraftRouteScreen.tsx b/apps/mobile/src/features/threads/NewTaskDraftRouteScreen.tsxindex a9c508f81..8e6819378 100644--- a/apps/mobile/src/features/threads/NewTaskDraftRouteScreen.tsx+++ b/apps/mobile/src/features/threads/NewTaskDraftRouteScreen.tsx@@ -9,6 +9,7 @@ type NewTaskDraftRouteParams = {readonly projectId?: string | string[];readonly title?: string | string[];readonly pendingTaskId?: string | string[];+ readonly incomingShareId?: string | string[];};export function NewTaskDraftRouteScreen({ route }: StaticScreenProps<NewTaskDraftRouteParams>) {@@ -36,6 +37,9 @@ export function NewTaskDraftRouteScreen({ route }: StaticScreenProps<NewTaskDraf/><NewTaskDraftScreeninitialProjectRef={initialProjectRef}+ incomingShareId={+ Array.isArray(params.incomingShareId) ? params.incomingShareId[0] : params.incomingShareId+ }pendingTaskId={Array.isArray(params.pendingTaskId) ? params.pendingTaskId[0] : params.pendingTaskId}diff --git a/apps/mobile/src/features/threads/NewTaskDraftScreen.tsx b/apps/mobile/src/features/threads/NewTaskDraftScreen.tsxindex dd8216dce..ce81db8c4 100644--- a/apps/mobile/src/features/threads/NewTaskDraftScreen.tsx+++ b/apps/mobile/src/features/threads/NewTaskDraftScreen.tsx@@ -1,5 +1,5 @@import { NativeStackScreenOptions } from "../../native/StackHeader";-import { StackActions, useNavigation } from "@react-navigation/native";+import { StackActions, useNavigation, usePreventRemove } from "@react-navigation/native";import { useCallback, useEffect, useMemo, useRef, useState } from "react";import { Alert, InteractionManager, Platform, View, useColorScheme } from "react-native";import { KeyboardAvoidingView, useKeyboardState } from "react-native-keyboard-controller";@@ -35,7 +35,13 @@ import {resolveProviderOptionDescriptors,} from "../../lib/providerOptions";import { useScaledTextRole } from "../settings/appearance/useScaledTextRole";-import { getComposerDraftSnapshot } from "../../state/use-composer-drafts";+import {+ clearComposerDraftContent,+ getComposerDraftSnapshot,+ mergeComposerDraftContent,+ restoreComposerDraftSnapshot,+ type ComposerDraft,+} from "../../state/use-composer-drafts";import { useProjects } from "../../state/entities";import { deriveThreadTitleFromPrompt } from "../../lib/projectThreadStartTurn";import { armAgentAwarenessLiveActivityForLocalWork } from "../agent-awareness/remoteRegistration";@@ -43,6 +49,7 @@ import { enqueueThreadOutboxMessage, removeThreadOutboxMessage } from "../../staimport { useRemoteConnectionStatus } from "../../state/use-remote-environment-registry";import { branchBadgeLabel, useNewTaskFlow } from "./new-task-flow-provider";import { useCreateProjectThread } from "./use-project-actions";+import { useIncomingShare } from "../sharing/IncomingShareProvider";function formatWorkspaceLabel(input: {readonly workspaceMode: string;@@ -63,11 +70,20 @@ export function NewTaskDraftScreen(props: {};/** Queued outbox message id when editing an existing pending task. */readonly pendingTaskId?: string;+ /** Durable native share inbox item to merge into this project draft. */+ readonly incomingShareId?: string;}) {const projects = useProjects();const createProjectThread = useCreateProjectThread();const flow = useNewTaskFlow();const navigation = useNavigation();+ const {+ consumeShare,+ getShare,+ isLoading: isIncomingShareInboxLoading,+ releaseShareReservation,+ reserveShare,+ } = useIncomingShare();const insets = useSafeAreaInsets();const colorScheme = useColorScheme();const isKeyboardVisible = useKeyboardState((state) => state.isVisible);@@ -82,10 +98,94 @@ export function NewTaskDraftScreen(props: {const promptInputRef = useRef<ComposerEditorHandle>(null);const loadedBranchesProjectKeyRef = useRef<string | null>(null);const [isComposerFocused, setIsComposerFocused] = useState(false);+ const [importingShareKey, setImportingShareKey] = useState<string | null>(null);+ const [isCancellingShareImport, setIsCancellingShareImport] = useState(false);+ const [cancelledIncomingShareId, setCancelledIncomingShareId] = useState<string | null>(null);+ const [isReturningToProjectPicker, setIsReturningToProjectPicker] = useState(false);+ const [shareImportAttempt, setShareImportAttempt] = useState(0);+ const startedShareImportKeyRef = useRef<string | null>(null);+ const cancellingShareImportKeyRef = useRef<string | null>(null);+ const shareImportDraftBackupRef = useRef(new Map<string, ComposerDraft>());+ const activeShareImportTokenRef = useRef<symbol | null>(null);+ const shareImportMountedRef = useRef(true);+ const latestDraftKeyRef = useRef(flow.draftKey);+ const latestIncomingShareIdRef = useRef(props.incomingShareId);+ latestDraftKeyRef.current = flow.draftKey;+ latestIncomingShareIdRef.current = props.incomingShareId;+ const isImportingShare = importingShareKey !== null;+ const alertedUnavailableIncomingShareIdRef = useRef<string | null>(null);+ const incomingShare = props.incomingShareId ? getShare(props.incomingShareId) : null;+ const requestedInitialProjectAvailable = Boolean(+ props.initialProjectRef?.environmentId &&+ props.initialProjectRef.projectId &&+ projects.some(+ (project) =>+ project.environmentId === props.initialProjectRef?.environmentId &&+ project.id === props.initialProjectRef?.projectId,+ ),+ );+ const isProjectPickerReturnActive =+ isReturningToProjectPicker && !requestedInitialProjectAvailable;+ const isIncomingShareTransferPending = Boolean(+ incomingShare && cancelledIncomingShareId !== props.incomingShareId,+ );+ usePreventRemove(+ (isIncomingShareTransferPending && !isProjectPickerReturnActive) || isCancellingShareImport,+ () => undefined,+ );+ const hasImportedIncomingShare = Boolean(+ props.incomingShareId &&+ flow.draftKey &&+ getComposerDraftSnapshot(flow.draftKey).importedShareIds?.includes(props.incomingShareId),+ );+ const isIncomingShareUnavailable = Boolean(+ props.incomingShareId &&+ !isIncomingShareInboxLoading &&+ !incomingShare &&+ !hasImportedIncomingShare,+ );+ const isIncomingShareReady =+ !props.incomingShareId ||+ (hasImportedIncomingShare && !incomingShare) ||+ isIncomingShareUnavailable;const appliedInitialProjectKeyRef = useRef<string | null>(null);useEffect(() => {+ if (cancelledIncomingShareId === props.incomingShareId) {+ navigation.goBack();+ }+ }, [cancelledIncomingShareId, navigation, props.incomingShareId]);+ useEffect(() => {+ if (!isReturningToProjectPicker) {+ return;+ }+ if (requestedInitialProjectAvailable) {+ setIsReturningToProjectPicker(false);+ return;+ }+ // Let usePreventRemove commit its disabled state before replacing this+ // route, otherwise the transfer guard can swallow the fallback action.+ const frame = requestAnimationFrame(() => {+ navigation.dispatch(+ StackActions.replace("NewTask", { incomingShareId: props.incomingShareId }),+ );+ });+ return () => cancelAnimationFrame(frame);+ }, [+ isReturningToProjectPicker,+ navigation,+ props.incomingShareId,+ requestedInitialProjectAvailable,+ ]);+ useEffect(() => {+ if (!shareImportMountedRef.current) {+ startedShareImportKeyRef.current = null;+ }+ shareImportMountedRef.current = true;return () => {appliedInitialProjectKeyRef.current = null;+ shareImportMountedRef.current = false;+ activeShareImportTokenRef.current = null;+ cancellingShareImportKeyRef.current = null;};}, []);@@ -163,6 +263,14 @@ export function NewTaskDraftScreen(props: {setProject(directProject);return;}++ if (projects.length > 0) {+ // Never fall through to the flow provider's temporary first-project+ // default. Return to the picker with the share id intact so the user+ // can choose an available destination.+ setIsReturningToProjectPicker(true);+ }+ return;}if (selectedProject) {@@ -179,6 +287,7 @@ export function NewTaskDraftScreen(props: {logicalProjects,projects,props.initialProjectRef,+ props.incomingShareId,props.pendingTaskId,navigation,selectedProject,@@ -198,6 +307,205 @@ export function NewTaskDraftScreen(props: {void flow.loadBranches();}, [flow.loadBranches, selectedProject]);+ useEffect(() => {+ const shareId = props.incomingShareId;+ const draftKey = flow.draftKey;+ const destinationProject = selectedProject;+ const initialEnvironmentId = props.initialProjectRef?.environmentId;+ const initialProjectId = props.initialProjectRef?.projectId;+ const selectedProjectMatchesRoute =+ !initialEnvironmentId ||+ !initialProjectId ||+ (destinationProject?.environmentId === initialEnvironmentId &&+ destinationProject.id === initialProjectId);+ if (+ !shareId ||+ !draftKey ||+ !destinationProject ||+ !selectedProjectMatchesRoute ||+ cancelledIncomingShareId === shareId+ ) {+ return;+ }+ const importKey = `${shareId}:${draftKey}`;+ if (+ startedShareImportKeyRef.current === importKey ||+ cancellingShareImportKeyRef.current === importKey+ ) {+ return;+ }++ if (!incomingShare) {+ if (isIncomingShareUnavailable && alertedUnavailableIncomingShareIdRef.current !== shareId) {+ alertedUnavailableIncomingShareIdRef.current = shareId;+ Alert.alert(+ "Shared content unavailable",+ "The shared content is no longer in the inbox. You can continue editing this task draft.",+ );+ }+ return;+ }++ if (alertedUnavailableIncomingShareIdRef.current === shareId) {+ alertedUnavailableIncomingShareIdRef.current = null;+ }+ startedShareImportKeyRef.current = importKey;+ const draftBackup =+ shareImportDraftBackupRef.current.get(importKey) ?? getComposerDraftSnapshot(draftKey);+ shareImportDraftBackupRef.current.set(importKey, draftBackup);+ const importToken = Symbol(importKey);+ let didReserveShare = false;+ let needsDraftRestore = false;+ activeShareImportTokenRef.current = importToken;+ setImportingShareKey(importKey);+ void (async () => {+ await reserveShare(shareId, {+ environmentId: String(destinationProject.environmentId),+ projectId: String(destinationProject.id),+ });+ didReserveShare = true;+ if (+ !shareImportMountedRef.current ||+ activeShareImportTokenRef.current !== importToken ||+ latestDraftKeyRef.current !== draftKey ||+ latestIncomingShareIdRef.current !== shareId+ ) {+ return;+ }+ needsDraftRestore = true;+ const { skippedAttachmentCount } = await mergeComposerDraftContent(draftKey, {+ text: incomingShare.text,+ attachments: incomingShare.attachments,+ sourceShareId: shareId,+ });+ if (+ !shareImportMountedRef.current ||+ activeShareImportTokenRef.current !== importToken ||+ latestDraftKeyRef.current !== draftKey ||+ latestIncomingShareIdRef.current !== shareId+ ) {+ // The durable reservation makes an interrupted transfer resume only+ // in this project instead of copying into a second project draft.+ return;+ }+ await consumeShare(shareId);+ if (!shareImportMountedRef.current || activeShareImportTokenRef.current !== importToken) {+ return;+ }+ const warnings = [...incomingShare.warnings];+ if (skippedAttachmentCount > 0) {+ warnings.push(+ `${skippedAttachmentCount} shared image${skippedAttachmentCount === 1 ? " was" : "s were"} skipped because this draft reached the attachment limit.`,+ );+ }+ if (warnings.length > 0) {+ Alert.alert("Some shared content was skipped", warnings.join("\n"));+ }+ shareImportDraftBackupRef.current.delete(importKey);+ })()+ .catch((error) => {+ if (!shareImportMountedRef.current || activeShareImportTokenRef.current !== importToken) {+ return;+ }+ Alert.alert(+ "Could not import shared content",+ error instanceof Error ? error.message : "The shared content could not be saved.",+ [+ {+ text: "Cancel import",+ style: "cancel",+ onPress: () => {+ const cancelImport = async (): Promise<void> => {+ if (!shareImportMountedRef.current) {+ return;+ }+ // Latch synchronously before restoring the draft. The+ // restore publishes atom state and can re-run the import+ // effect before React commits the cancelling state update.+ cancellingShareImportKeyRef.current = importKey;+ setIsCancellingShareImport(true);+ try {+ if (needsDraftRestore) {+ await restoreComposerDraftSnapshot(draftKey, draftBackup);+ needsDraftRestore = false;+ }+ if (didReserveShare) {+ await releaseShareReservation(shareId, {+ environmentId: String(destinationProject.environmentId),+ projectId: String(destinationProject.id),+ });+ }+ shareImportDraftBackupRef.current.delete(importKey);+ if (shareImportMountedRef.current) {+ setIsCancellingShareImport(false);+ setCancelledIncomingShareId(shareId);+ }+ } catch (cancelError) {+ if (!shareImportMountedRef.current) {+ return;+ }+ Alert.alert(+ "Could not cancel import",+ cancelError instanceof Error+ ? cancelError.message+ : "The shared content could not be restored safely.",+ [+ {+ text: "Retry import",+ onPress: () => {+ cancellingShareImportKeyRef.current = null;+ setIsCancellingShareImport(false);+ setShareImportAttempt((attempt) => attempt + 1);+ },+ },+ {+ text: "Retry cancel",+ onPress: () => void cancelImport(),+ },+ ],+ { cancelable: false },+ );+ }+ };+ void cancelImport();+ },+ },+ {+ text: "Retry",+ onPress: () => setShareImportAttempt((attempt) => attempt + 1),+ },+ ],+ { cancelable: false },+ );+ })+ .finally(() => {+ if (startedShareImportKeyRef.current === importKey) {+ // Every terminal path, including an invalidated operation, must+ // release the synchronous start latch so this transfer can retry.+ startedShareImportKeyRef.current = null;+ }+ if (shareImportMountedRef.current && activeShareImportTokenRef.current === importToken) {+ activeShareImportTokenRef.current = null;+ setImportingShareKey(null);+ }+ });+ }, [+ consumeShare,+ cancelledIncomingShareId,+ flow.draftKey,+ hasImportedIncomingShare,+ incomingShare,+ isIncomingShareInboxLoading,+ isIncomingShareUnavailable,+ props.incomingShareId,+ props.initialProjectRef?.environmentId,+ props.initialProjectRef?.projectId,+ releaseShareReservation,+ reserveShare,+ selectedProject,+ shareImportAttempt,+ ]);+useEffect(() => {// Android starts with the collapsed composer pill (like an open thread)// and only expands/focuses when tapped.@@ -223,10 +531,11 @@ export function NewTaskDraftScreen(props: {flow.environments.map((environment) => ({id: `environment:${environment.environmentId}`,title: environment.environmentLabel,+ attributes: isIncomingShareTransferPending ? { disabled: true } : undefined,state:flow.selectedEnvironmentId === environment.environmentId ? ("on" as const) : undefined,})),- [flow.environments, flow.selectedEnvironmentId],+ [flow.environments, flow.selectedEnvironmentId, isIncomingShareTransferPending],);const modelMenuActions = useMemo(@@ -391,20 +700,23 @@ export function NewTaskDraftScreen(props: {[currentBranchName, flow.selectedBranchName, flow.workspaceMode],);function handleModelMenuAction(event: string) {- if (!event.startsWith("model:")) {+ if (isIncomingShareTransferPending || !event.startsWith("model:")) {return;}flow.setSelectedModelKey(event.slice("model:".length));}function handleEnvironmentMenuAction(event: string) {- if (!event.startsWith("environment:")) {+ if (isIncomingShareTransferPending || !event.startsWith("environment:")) {return;}flow.selectEnvironment(EnvironmentId.make(event.slice("environment:".length)));}function handleOptionsMenuAction(event: string) {+ if (isIncomingShareTransferPending) {+ return;+ }const providerOptions = applyProviderOptionMenuEvent(providerOptionDescriptors, event);if (providerOptions) {flow.setSelectedModelOptions(providerOptions);@@ -424,6 +736,9 @@ export function NewTaskDraftScreen(props: {}function handleWorkspaceMenuAction(event: string) {+ if (isIncomingShareTransferPending) {+ return;+ }if (event.startsWith("workspace:mode:")) {flow.setWorkspaceMode(event.slice("workspace:mode:".length) as Parameters<typeof flow.setWorkspaceMode>[0],@@ -444,6 +759,9 @@ export function NewTaskDraftScreen(props: {}async function handlePickImages(): Promise<void> {+ if (isIncomingShareTransferPending) {+ return;+ }const result = await pickComposerImages({ existingCount: flow.attachments.length });if (result.images.length > 0) {flow.appendAttachments(result.images);@@ -526,8 +844,7 @@ export function NewTaskDraftScreen(props: {if (editingPendingTask) {flow.finishEditingPendingTask();} else {- flow.setPrompt("");- flow.clearAttachments();+ clearComposerDraftContent(draftKey);}navigation.getParent()?.goBack();return;@@ -585,8 +902,7 @@ export function NewTaskDraftScreen(props: {}flow.finishEditingPendingTask();} else {- flow.setPrompt("");- flow.clearAttachments();+ clearComposerDraftContent(draftKey);}navigation.dispatch(StackActions.replace("Thread", {@@ -620,12 +936,15 @@ export function NewTaskDraftScreen(props: {Boolean(flow.selectedProject) &&Boolean(flow.selectedModel) &&flow.prompt.trim().length > 0 &&+ isIncomingShareReady &&+ !isImportingShare &&!flow.submitting &&!(flow.workspaceMode === "worktree" && !flow.selectedBranchName);const promptEditor = (<ComposerEditorref={promptInputRef}autoFocus={!isAndroid}+ editable={!isIncomingShareTransferPending}multilinescrollEnabled={isExpanded}value={flow.prompt}@@ -660,6 +979,7 @@ export function NewTaskDraftScreen(props: {icon="plus"onPress={() => void handlePickImages()}showChevron={false}+ disabled={isIncomingShareTransferPending}/><ControlPillMenuactions={modelMenuActions}@@ -667,6 +987,7 @@ export function NewTaskDraftScreen(props: {><ComposerToolbarTriggeraccessibilityLabel="Model"+ disabled={isIncomingShareTransferPending}iconNode={<ProviderIcon provider={flow.selectedModelOption?.providerDriver} size={16} />}label={flow.selectedModelOption?.label ?? "Model"}/>@@ -677,6 +998,7 @@ export function NewTaskDraftScreen(props: {><ComposerToolbarTriggeraccessibilityLabel="Configuration"+ disabled={isIncomingShareTransferPending}icon="slider.horizontal.3"label={configurationLabel}/>@@ -687,6 +1009,7 @@ export function NewTaskDraftScreen(props: {><ComposerToolbarTriggeraccessibilityLabel="Environment"+ disabled={isIncomingShareTransferPending}icon="desktopcomputer"label={selectedEnvironmentLabel}/>@@ -697,6 +1020,7 @@ export function NewTaskDraftScreen(props: {><ComposerToolbarTriggeraccessibilityLabel="Workspace"+ disabled={isIncomingShareTransferPending}icon="point.topleft.down.curvedto.point.bottomright.up"label={workspaceLabel}/>@@ -763,7 +1087,9 @@ export function NewTaskDraftScreen(props: {<View className="pb-2.5"><ComposerAttachmentStripattachments={flow.attachments}- onRemove={flow.removeAttachment}+ onRemove={+ isIncomingShareTransferPending ? () => undefined : flow.removeAttachment+ }/></View>) : null}@@ -807,7 +1133,7 @@ export function NewTaskDraftScreen(props: {<View className="px-4 pt-3"><ComposerAttachmentStripattachments={flow.attachments}- onRemove={flow.removeAttachment}+ onRemove={isIncomingShareTransferPending ? () => undefined : flow.removeAttachment}imageSize={88}imageBorderRadius={20}/>diff --git a/apps/mobile/src/features/threads/NewTaskRouteScreen.tsx b/apps/mobile/src/features/threads/NewTaskRouteScreen.tsxindex ca857f678..99985385e 100644--- a/apps/mobile/src/features/threads/NewTaskRouteScreen.tsx+++ b/apps/mobile/src/features/threads/NewTaskRouteScreen.tsx@@ -1,9 +1,9 @@import { NativeHeaderToolbar, NativeStackScreenOptions } from "../../native/StackHeader";-import { useNavigation } from "@react-navigation/native";+import { useIsFocused, useNavigation, type StaticScreenProps } from "@react-navigation/native";import { SymbolView } from "../../components/AppSymbol";import type { EnvironmentId, ProjectId } from "@t3tools/contracts";-import { useMemo } from "react";-import { ActivityIndicator, Platform, Pressable, ScrollView, View } from "react-native";+import { useEffect, useMemo, useRef } from "react";+import { ActivityIndicator, Alert, Platform, Pressable, ScrollView, View } from "react-native";import { useSafeAreaInsets } from "react-native-safe-area-context";import { useThemeColor } from "../../lib/useThemeColor";import { cn } from "../../lib/cn";@@ -16,6 +16,11 @@ import type { WorkspaceState } from "../../state/workspaceModel";import { useWorkspaceState } from "../../state/workspace";import { groupProjectsByRepository } from "../../lib/repositoryGroups";import { useAdaptiveWorkspaceLayout } from "../layout/AdaptiveWorkspaceLayout";+import { useIncomingShare } from "../sharing/IncomingShareProvider";++type NewTaskRouteParams = {+ readonly incomingShareId?: string | string[];+};function deriveProjectEmptyState(catalogState: WorkspaceState): {readonly title: string;@@ -72,15 +77,29 @@ function deriveProjectEmptyState(catalogState: WorkspaceState): {};}-export function NewTaskRouteScreen() {+export function NewTaskRouteScreen({ route }: StaticScreenProps<NewTaskRouteParams | undefined>) {const projects = useProjects();const threads = useThreadShells();const { state: catalogState } = useWorkspaceState();const navigation = useNavigation();+ const isFocused = useIsFocused();const { layout } = useAdaptiveWorkspaceLayout();const insets = useSafeAreaInsets();const chevronColor = useThemeColor("--color-chevron");const accentColor = useThemeColor("--color-icon-muted");+ const { getShare, releaseShareReservation } = useIncomingShare();+ const routeShareId = Array.isArray(route.params?.incomingShareId)+ ? route.params.incomingShareId[0]+ : route.params?.incomingShareId;+ const incomingShare = routeShareId ? getShare(routeShareId) : null;+ const incomingShareSubtitle = incomingShare+ ? incomingShare.attachments.length === 0+ ? "Choose a project for what you shared"+ : incomingShare.attachments.length === 1+ ? "Choose a project for the image you shared"+ : `Choose a project for the ${incomingShare.attachments.length} images you shared`+ : null;+ const screenTitle = incomingShare ? "Start a task" : "Choose project";const repositoryGroups = useMemo(() => groupProjectsByRepository({ projects, threads }),[projects, threads],@@ -109,6 +128,70 @@ export function NewTaskRouteScreen() {return nextItems;}, [repositoryGroups]);const projectEmptyState = deriveProjectEmptyState(catalogState);+ const resumedDestinationKeyRef = useRef<string | null>(null);+ const reservedDestinationProject = incomingShare?.destination+ ? (projects.find(+ (project) =>+ project.environmentId === incomingShare.destination?.environmentId &&+ project.id === incomingShare.destination?.projectId,+ ) ?? null)+ : null;++ async function selectProject(item: (typeof items)[number]): Promise<void> {+ if (incomingShare?.destination && !reservedDestinationProject) {+ try {+ await releaseShareReservation(incomingShare.id, incomingShare.destination);+ } catch (error) {+ Alert.alert(+ "Could not change project",+ error instanceof Error+ ? error.message+ : "The shared content reservation could not be updated.",+ );+ return;+ }+ }+ navigation.navigate("NewTaskSheet", {+ screen: "NewTaskDraft",+ params: {+ environmentId: item.environmentId,+ projectId: item.id,+ title: item.title,+ incomingShareId: incomingShare?.id,+ },+ });+ }++ useEffect(() => {+ const destination = incomingShare?.destination;+ if (!destination) {+ resumedDestinationKeyRef.current = null;+ return;+ }+ if (!isFocused) {+ // Returning from the reserved draft is a fresh resume attempt. Keeping+ // this latch set would leave every project row disabled with no route.+ resumedDestinationKeyRef.current = null;+ return;+ }+ const destinationKey = `${incomingShare.id}:${destination.environmentId}:${destination.projectId}`;+ if (resumedDestinationKeyRef.current === destinationKey) {+ return;+ }+ if (!reservedDestinationProject) {+ return;+ }+ resumedDestinationKeyRef.current = destinationKey;+ navigation.navigate("NewTaskSheet", {+ screen: "NewTaskDraft",+ params: {+ environmentId: reservedDestinationProject.environmentId,+ projectId: reservedDestinationProject.id,+ title: reservedDestinationProject.title,+ incomingShareId: incomingShare.id,+ },+ });+ }, [incomingShare, isFocused, navigation, reservedDestinationProject]);return (<View collapsable={false} className="flex-1 bg-sheet">@@ -117,7 +200,8 @@ export function NewTaskRouteScreen() {{/* Android renders its own in-screen header instead of the native bar. */}<NativeStackScreenOptions options={{ headerShown: false }} /><AndroidScreenHeader- title="Choose project"+ title={screenTitle}+ subtitle={incomingShareSubtitle}onBack={layout.usesSplitView ? () => navigation.goBack() : undefined}actions={[{@@ -129,21 +213,29 @@ export function NewTaskRouteScreen() {/></>) : (- <NativeHeaderToolbar placement="right">- {layout.usesSplitView ? (+ <>+ <NativeStackScreenOptions+ options={{+ title: screenTitle,+ unstable_headerSubtitle: incomingShareSubtitle ?? undefined,+ }}+ />+ <NativeHeaderToolbar placement="right">+ {layout.usesSplitView ? (+ <NativeHeaderToolbar.Button+ accessibilityLabel="Close new task"+ icon="xmark"+ onPress={() => navigation.goBack()}+ separateBackground+ />+ ) : null}<NativeHeaderToolbar.Button- accessibilityLabel="Close new task"- icon="xmark"- onPress={() => navigation.goBack()}+ icon="plus"+ onPress={() => navigation.navigate("NewTaskSheet", { screen: "AddProject" })}separateBackground/>- ) : null}- <NativeHeaderToolbar.Button- icon="plus"- onPress={() => navigation.navigate("NewTaskSheet", { screen: "AddProject" })}- separateBackground- />- </NativeHeaderToolbar>+ </NativeHeaderToolbar>+ </>)}<ScrollView@@ -152,6 +244,7 @@ export function NewTaskRouteScreen() {className="flex-1"contentInset={{ bottom: Math.max(insets.bottom, 18) + 18 }}contentContainerStyle={{+ gap: 12,paddingHorizontal: 20,paddingTop: 8,}}@@ -194,16 +287,8 @@ export function NewTaskRouteScreen() {return (<Pressablekey={item.key}- onPress={() =>- navigation.navigate("NewTaskSheet", {- screen: "NewTaskDraft",- params: {- environmentId: item.environmentId,- projectId: item.id,- title: item.title,- },- })- }+ disabled={reservedDestinationProject !== null}+ onPress={() => void selectProject(item)}className={cn("bg-card px-4 py-3.5",!isFirst && "border-t border-border-subtle",diff --git a/apps/mobile/src/lib/base64.ts b/apps/mobile/src/lib/base64.tsnew file mode 100644index 000000000..640e2260b--- /dev/null+++ b/apps/mobile/src/lib/base64.ts@@ -0,0 +1,4 @@+export function estimateBase64ByteSize(base64: string): number {+ const padding = base64.endsWith("==") ? 2 : base64.endsWith("=") ? 1 : 0;+ return Math.floor((base64.length * 3) / 4) - padding;+}diff --git a/apps/mobile/src/lib/composerImages.ts b/apps/mobile/src/lib/composerImages.tsindex 8aa6d2a3f..5c79b5b5e 100644--- a/apps/mobile/src/lib/composerImages.ts+++ b/apps/mobile/src/lib/composerImages.ts@@ -3,6 +3,7 @@ import {PROVIDER_SEND_TURN_MAX_IMAGE_BYTES,type UploadChatImageAttachment,} from "@t3tools/contracts";+import { estimateBase64ByteSize } from "./base64";import { uuidv4 } from "./uuid";export interface DraftComposerImageAttachment extends UploadChatImageAttachment {@@ -25,11 +26,6 @@ export function toUploadChatImageAttachments(const OWNED_PASTED_IMAGE_DIRECTORY = "t3-composer-paste";-function estimateBase64ByteSize(base64: string): number {- const padding = base64.endsWith("==") ? 2 : base64.endsWith("=") ? 1 : 0;- return Math.floor((base64.length * 3) / 4) - padding;-}-async function loadImagePicker() {try {return await import("expo-image-picker");diff --git a/apps/mobile/src/lib/serialized-async-queue.test.ts b/apps/mobile/src/lib/serialized-async-queue.test.tsnew file mode 100644index 000000000..71dc9aa76--- /dev/null+++ b/apps/mobile/src/lib/serialized-async-queue.test.ts@@ -0,0 +1,45 @@+import { describe, expect, it } from "@effect/vitest";++import { SerializedAsyncQueue } from "./serialized-async-queue";++function deferred() {+ let resolve!: () => void;+ const promise = new Promise<void>((next) => {+ resolve = next;+ });+ return { promise, resolve };+}++describe("SerializedAsyncQueue", () => {+ it("does not let a newer operation overtake an in-flight operation", async () => {+ const queue = new SerializedAsyncQueue();+ const firstGate = deferred();+ const events: string[] = [];++ const first = queue.run(async () => {+ events.push("first:start");+ await firstGate.promise;+ events.push("first:end");+ });+ const second = queue.run(async () => {+ events.push("second");+ });++ await Promise.resolve();+ expect(events).toEqual(["first:start"]);+ firstGate.resolve();+ await Promise.all([first, second]);+ expect(events).toEqual(["first:start", "first:end", "second"]);+ });++ it("continues after a rejected operation", async () => {+ const queue = new SerializedAsyncQueue();+ const first = queue.run(async () => {+ throw new Error("failed");+ });+ const second = queue.run(async () => "recovered");++ await expect(first).rejects.toThrow("failed");+ await expect(second).resolves.toBe("recovered");+ });+});diff --git a/apps/mobile/src/lib/serialized-async-queue.ts b/apps/mobile/src/lib/serialized-async-queue.tsnew file mode 100644index 000000000..e989eb7da--- /dev/null+++ b/apps/mobile/src/lib/serialized-async-queue.ts@@ -0,0 +1,16 @@+/**+ * Runs asynchronous operations in call order while keeping the queue usable+ * after an individual operation rejects.+ */+export class SerializedAsyncQueue {+ private tail: Promise<void> = Promise.resolve();++ run<T>(operation: () => Promise<T>): Promise<T> {+ const result = this.tail.then(operation, operation);+ this.tail = result.then(+ () => undefined,+ () => undefined,+ );+ return result;+ }+}diff --git a/apps/mobile/src/native/StackHeader.tsx b/apps/mobile/src/native/StackHeader.tsxindex e27087579..bbcbb8e42 100644--- a/apps/mobile/src/native/StackHeader.tsx+++ b/apps/mobile/src/native/StackHeader.tsx@@ -195,7 +195,7 @@ function convertToolbarChild(child: ReactNode): NativeStackHeaderItem | null {if (typeName === "NativeHeaderToolbarButton") {return {type: "button",- label: "",+ label: typeof child.props.label === "string" ? child.props.label : "",accessibilityLabel:typeof child.props.accessibilityLabel === "string"? child.props.accessibilityLabel@@ -293,6 +293,7 @@ function NativeHeaderToolbarButton(_props: {readonly accessibilityLabel?: string;readonly disabled?: boolean;readonly icon?: string;+ readonly label?: string;readonly onPress?: () => void;readonly separateBackground?: boolean;readonly tintColor?: ColorValue;diff --git a/apps/mobile/src/state/use-composer-drafts.test.ts b/apps/mobile/src/state/use-composer-drafts.test.tsindex d02abb6a2..fdabe67bc 100644--- a/apps/mobile/src/state/use-composer-drafts.test.ts+++ b/apps/mobile/src/state/use-composer-drafts.test.ts@@ -8,7 +8,9 @@ import {decodePersistedComposerDrafts,type ComposerDraft,getComposerDraftSnapshot,+ mergeComposerDraftContentState,removeComposerDraftsForEnvironment,+ restoreComposerDraftSnapshotState,} from "./use-composer-drafts";const DRAFT: ComposerDraft = {@@ -94,6 +96,7 @@ describe("mobile composer drafts", () => {const draft: ComposerDraft = {text: "send this",attachments: [],+ importedShareIds: ["share-1"],modelSelection: {instanceId: ProviderInstanceId.make("codex"),model: "gpt-5.4",@@ -108,7 +111,8 @@ describe("mobile composer drafts", () => {expect(clearComposerDraftContentState({ [draftKey]: draft }, draftKey)).toEqual({[draftKey]: {- ...draft,+ modelSelection: draft.modelSelection,+ workspaceSelection: draft.workspaceSelection,text: "",attachments: [],},@@ -131,6 +135,90 @@ describe("mobile composer drafts", () => {expect(getComposerDraftSnapshot(draftKey)).toEqual(selectedDraft);});+ it("merges shared content into a project draft without duplicating retries", () => {+ const draftKey = "new-task:environment-1:project-1";+ const sharedAttachment = {+ id: "share-1:image:0",+ type: "image" as const,+ name: "Screenshot.png",+ mimeType: "image/png",+ sizeBytes: 3,+ dataUrl: "data:image/png;base64,YWJj",+ previewUri: "data:image/png;base64,YWJj",+ };+ const existing: Record<string, ComposerDraft> = {+ [draftKey]: { text: "Existing context", attachments: [] },+ };+ const content = {+ text: "Shared note",+ attachments: [sharedAttachment],+ sourceShareId: "share-1",+ };++ const merged = mergeComposerDraftContentState(existing, draftKey, content);+ expect(merged[draftKey]).toMatchObject({+ text: "Existing context\n\nShared note",+ attachments: [sharedAttachment],+ importedShareIds: ["share-1"],+ });+ expect(mergeComposerDraftContentState(merged, draftKey, content)).toBe(merged);++ const edited = {+ ...merged,+ [draftKey]: { ...merged[draftKey]!, text: "User edited the imported context" },+ };+ expect(mergeComposerDraftContentState(edited, draftKey, content)).toBe(edited);+ });++ it("preserves existing images when shared content exceeds the draft attachment limit", () => {+ const draftKey = "new-task:environment-1:project-1";+ const image = (id: string) => ({+ id,+ type: "image" as const,+ name: `${id}.png`,+ mimeType: "image/png",+ sizeBytes: 3,+ dataUrl: "data:image/png;base64,YWJj",+ previewUri: "data:image/png;base64,YWJj",+ });+ const existingImage = image("existing");+ const sharedImages = Array.from({ length: 8 }, (_, index) => image(`shared-${index}`));++ const merged = mergeComposerDraftContentState(+ { [draftKey]: { text: "", attachments: [existingImage] } },+ draftKey,+ { text: "", attachments: sharedImages },+ );++ expect(merged[draftKey]?.attachments).toHaveLength(8);+ expect(merged[draftKey]?.attachments[0]).toEqual(existingImage);+ expect(merged[draftKey]?.attachments.at(-1)?.id).toBe("shared-6");+ });++ it("restores the exact draft captured before an interrupted share import", () => {+ const draftKey = "new-task:environment-1:project-1";+ const beforeImport: ComposerDraft = {+ text: "Existing context",+ attachments: [],+ runtimeMode: "approval-required",+ };+ const imported: ComposerDraft = {+ ...beforeImport,+ text: "Existing context\n\nShared note",+ importedShareIds: ["share-1"],+ };++ expect(+ restoreComposerDraftSnapshotState({ [draftKey]: imported }, draftKey, beforeImport),+ ).toEqual({ [draftKey]: beforeImport });+ expect(+ restoreComposerDraftSnapshotState({ [draftKey]: imported }, draftKey, {+ text: "",+ attachments: [],+ }),+ ).toEqual({});+ });+it("removes only drafts owned by the selected environment", () => {const environmentId = EnvironmentId.make("environment-cloud");const retainedEnvironmentId = EnvironmentId.make("environment-local");diff --git a/apps/mobile/src/state/use-composer-drafts.ts b/apps/mobile/src/state/use-composer-drafts.tsindex aa2e2dd5c..cdef999e0 100644--- a/apps/mobile/src/state/use-composer-drafts.ts+++ b/apps/mobile/src/state/use-composer-drafts.ts@@ -1,6 +1,7 @@import { useAtomValue } from "@effect/atom-react";import {ModelSelection as ModelSelectionSchema,+ PROVIDER_SEND_TURN_MAX_ATTACHMENTS,ProviderInteractionMode as ProviderInteractionModeSchema,RuntimeMode as RuntimeModeSchema,type EnvironmentId,@@ -14,6 +15,7 @@ import { Atom } from "effect/unstable/reactivity";import { DraftComposerImageAttachmentSchema } from "../lib/composer-image-schema";import type { DraftComposerImageAttachment } from "../lib/composerImages";+import { SerializedAsyncQueue } from "../lib/serialized-async-queue";import { appAtomRegistry } from "./atom-registry";const COMPOSER_DRAFTS_SCHEMA_VERSION = 1;@@ -38,12 +40,19 @@ export class ComposerDraftPersistenceError extends Schema.TaggedErrorClass<Compoexport interface ComposerDraft {readonly text: string;readonly attachments: ReadonlyArray<DraftComposerImageAttachment>;+ readonly importedShareIds?: ReadonlyArray<string>;readonly modelSelection?: ModelSelection;readonly runtimeMode?: RuntimeMode;readonly interactionMode?: ProviderInteractionMode;readonly workspaceSelection?: ComposerDraftWorkspaceSelection;}+export interface ComposerDraftContent {+ readonly text: string;+ readonly attachments: ReadonlyArray<DraftComposerImageAttachment>;+ readonly sourceShareId?: string;+}+export interface ComposerDraftWorkspaceSelection {readonly mode: "local" | "worktree";readonly branch: string | null;@@ -66,6 +75,7 @@ const ComposerDraftWorkspaceSelectionSchema = Schema.Struct({const ComposerDraftSchema = Schema.Struct({text: Schema.String,attachments: Schema.Array(DraftComposerImageAttachmentSchema),+ importedShareIds: Schema.optional(Schema.Array(Schema.String)),modelSelection: Schema.optional(ModelSelectionSchema),runtimeMode: Schema.optional(RuntimeModeSchema),interactionMode: Schema.optional(ProviderInteractionModeSchema),@@ -93,6 +103,7 @@ export const composerDraftsAtom = Atom.make<Record<string, ComposerDraft>>({}).plet loadPromise: Promise<void> | null = null;let persistTimer: ReturnType<typeof setTimeout> | null = null;+const persistenceQueue = new SerializedAsyncQueue();function normalizeDraft(draft: ComposerDraft | undefined): ComposerDraft {if (!draft) {@@ -193,7 +204,7 @@ async function writePersistedComposerDrafts(drafts: Record<string, ComposerDraftasync function savePersistedComposerDrafts(drafts: Record<string, ComposerDraft>): Promise<void> {try {- await writePersistedComposerDrafts(drafts);+ await persistenceQueue.run(() => writePersistedComposerDrafts(drafts));} catch (error) {console.warn("[composer-drafts] failed to persist drafts", error);// Draft persistence is best-effort; in-memory drafts still keep working.@@ -366,8 +377,9 @@ export function clearComposerDraftContentState(if (!existing) {return current;}+ const { importedShareIds: _importedShareIds, ...retained } = existing;const draft = {- ...existing,+ ...retained,text: "",attachments: [],};@@ -382,6 +394,138 @@ export function clearComposerDraftContentState(};}+export function restoreComposerDraftSnapshotState(+ current: Record<string, ComposerDraft>,+ draftKey: string,+ snapshot: ComposerDraft,+): Record<string, ComposerDraft> {+ const next = { ...current };+ if (isEmptyDraft(snapshot)) {+ delete next[draftKey];+ } else {+ next[draftKey] = snapshot;+ }+ return next;+}++function mergeComposerDraftText(existing: string, incoming: string): string {+ if (incoming.length === 0) {+ return existing;+ }+ if (existing.length === 0) {+ return incoming;+ }+ // Import retries are possible after an interrupted native handoff. Keep the+ // operation idempotent when the same shared text is already present.+ if (existing === incoming || existing.endsWith(`\n\n${incoming}`)) {+ return existing;+ }+ return `${existing}\n\n${incoming}`;+}++export function mergeComposerDraftContentState(+ current: Record<string, ComposerDraft>,+ draftKey: string,+ content: ComposerDraftContent,+): Record<string, ComposerDraft> {+ const existing = normalizeDraft(current[draftKey]);+ if (content.sourceShareId && existing.importedShareIds?.includes(content.sourceShareId)) {+ return current;+ }+ const attachmentIds = new Set(existing.attachments.map((attachment) => attachment.id));+ const incomingAttachments = content.attachments.filter((attachment) => {+ if (attachmentIds.has(attachment.id)) {+ return false;+ }+ attachmentIds.add(attachment.id);+ return true;+ });+ const attachments = [...existing.attachments, ...incomingAttachments].slice(+ 0,+ PROVIDER_SEND_TURN_MAX_ATTACHMENTS,+ );+ const text = mergeComposerDraftText(existing.text, content.text);+ const importedShareIds = content.sourceShareId+ ? [...(existing.importedShareIds ?? []), content.sourceShareId]+ : existing.importedShareIds;+ if (+ text === existing.text &&+ attachments.length === existing.attachments.length &&+ importedShareIds === existing.importedShareIds+ ) {+ return current;+ }+ return {+ ...current,+ [draftKey]: {+ ...existing,+ text,+ attachments,+ ...(importedShareIds ? { importedShareIds } : {}),+ },+ };+}++/**+ * Atomically moves an incoming share into a project-scoped composer draft.+ * The durable write happens before the share inbox item can be acknowledged.+ */+export async function mergeComposerDraftContent(+ draftKey: string,+ content: ComposerDraftContent,+): Promise<{ readonly skippedAttachmentCount: number }> {+ ensureComposerDraftsLoaded();+ if (loadPromise !== null) {+ await loadPromise;+ }+ if (persistTimer !== null) {+ clearTimeout(persistTimer);+ persistTimer = null;+ }+ const current = appAtomRegistry.get(composerDraftsAtom);+ const next = mergeComposerDraftContentState(current, draftKey, content);+ const currentAttachmentIds = new Set(+ normalizeDraft(current[draftKey]).attachments.map((attachment) => attachment.id),+ );+ const nextAttachmentIds = new Set(+ normalizeDraft(next[draftKey]).attachments.map((attachment) => attachment.id),+ );+ const skippedAttachmentCount = content.attachments.filter(+ (attachment) =>+ !currentAttachmentIds.has(attachment.id) && !nextAttachmentIds.has(attachment.id),+ ).length;+ // Publish the content and its import receipt together before the filesystem+ // await. Typing during persistence then builds on the receipt-bearing state,+ // and its debounced write is serialized after this transaction.+ if (next !== current) {+ appAtomRegistry.set(composerDraftsAtom, next);+ }+ await persistenceQueue.run(() => writePersistedComposerDrafts(next));+ return { skippedAttachmentCount };+}++/** Restores the exact content/settings captured before an interrupted import. */+export async function restoreComposerDraftSnapshot(+ draftKey: string,+ snapshot: ComposerDraft,+): Promise<void> {+ ensureComposerDraftsLoaded();+ if (loadPromise !== null) {+ await loadPromise;+ }+ if (persistTimer !== null) {+ clearTimeout(persistTimer);+ persistTimer = null;+ }+ const next = restoreComposerDraftSnapshotState(+ appAtomRegistry.get(composerDraftsAtom),+ draftKey,+ snapshot,+ );+ appAtomRegistry.set(composerDraftsAtom, next);+ await persistenceQueue.run(() => writePersistedComposerDrafts(next));+}+export function clearComposerDraftContent(draftKey: string): void {updateComposerDrafts((current) => clearComposerDraftContentState(current, draftKey));}diff --git a/pnpm-lock.yaml b/pnpm-lock.yamlindex ee737f9e7..5c50f4a98 100644--- a/pnpm-lock.yaml+++ b/pnpm-lock.yaml@@ -61,6 +61,8 @@ overrides:'@types/node': 24.12.4effect: 4.0.0-beta.78expo-modules-jsi: 56.0.10+ expo-sharing>@expo/config-plugins: 56.0.9+ expo-sharing>@expo/config-types: 56.0.6vite: npm:@voidzero-dev/[email protected]yaml: ^2.9.0@@ -336,6 +338,9 @@ importers:expo-secure-store:specifier: ~56.0.4version: 56.0.4([email protected])+ expo-sharing:+ specifier: ~56.0.18+ version: 56.0.18([email protected])([email protected](@babel/[email protected])(@react-native/[email protected](@babel/[email protected])([email protected])([email protected]))(@types/[email protected])([email protected])([email protected])([email protected]))([email protected])([email protected])expo-splash-screen:specifier: ~56.0.10version: 56.0.10([email protected])([email protected])@@ -2422,15 +2427,9 @@ packages:'@expo/[email protected]':resolution: {integrity: sha512-iNe0puxwBNEcuua9gmTGzq+SuMDa0iATai1FlFTMHJ/vUmKvN/V//drXoLJkVb5i5H3iE/n/qIJxyoBnXouD0w==}- '@expo/[email protected]':- resolution: {integrity: sha512-phTuyBhgVLfqUHMjQkAfRtbyoY6yTxoKja1awtpVnEkoJDxPJuXx1KX5uvq1eZtt4bJQ08OBJ6P95INqRSHpRg==}-'@expo/[email protected]':resolution: {integrity: sha512-/6a/S9USwx8OC9tGjHxbviLFiBHyueN3aoNWMLvWDEJoZ1CIVW800ZBzwXq/FYNK2qzcN1LxFmQtzD1zeFQKNA==}- '@expo/[email protected]':- resolution: {integrity: sha512-GsAHO/MwW9ZRdgnmyfRXqVGLCP/zejD6rWnp5OROp8mBGRObKm4HfrjlUyT1skjMwCj1OrURx9ZfIc6yeBAkIA==}-'@expo/[email protected]':resolution: {integrity: sha512-4Y6Aum5J4Re5NnxGVofRNe1aDwUBOmWhQYkynZsqzRtX/zEA1ADUeyHXuEckv9YD9djiyT7bKtLt5gKL3mA6VQ==}@@ -6725,6 +6724,13 @@ packages:resolution: {integrity: sha512-SmM2p2g3Jrktpiazcst+OxhjSzOHXKAY4BPURHYHXvApzzoybMmrNF4IEZ8DKZ145BhSe4ydAmlEFCRTsdtgUQ==}engines: {node: '>=20.16.0'}+ resolution: {integrity: sha512-45w4BWNFmdTczp+fJX6YfwJrn9sX+VeRWz2VWLhauygcCrym44HtVDXX5yVYPB9TW9ZesLcEI+CCrCBNWL7smQ==}+ peerDependencies:+ expo: '*'+ react: '*'+ react-native: '*'+resolution: {integrity: sha512-vDIlo8hzt9HlCZQ0kSY66v83D1WEXOJbVMeyPDfXDu9tbDdPMNUyDpi4WGJXikAjxnAKfbt5Mv5NnEbxINy+VA==}peerDependencies:@@ -12217,25 +12223,6 @@ snapshots:dependencies:node-forge: 1.4.0- '@expo/[email protected]([email protected])':- dependencies:- '@expo/config-types': 56.0.5- '@expo/json-file': 10.2.0- '@expo/plist': 0.7.0- '@expo/require-utils': 56.1.3([email protected])- '@expo/sdk-runtime-versions': 1.0.0- chalk: 4.1.2- debug: 4.4.3- getenv: 2.0.0- glob: 13.0.6- semver: 7.8.5- slugify: 1.6.9- xcode: 3.0.1- xml2js: 0.6.0- transitivePeerDependencies:- - supports-color- - typescript-'@expo/[email protected]([email protected])':dependencies:'@expo/config-types': 56.0.6@@ -12255,14 +12242,12 @@ snapshots:- supports-color- typescript- '@expo/[email protected]': {}-'@expo/[email protected]': {}'@expo/[email protected]([email protected])':dependencies:'@expo/config-plugins': 56.0.9([email protected])- '@expo/config-types': 56.0.5+ '@expo/config-types': 56.0.6'@expo/json-file': 10.2.0'@expo/require-utils': 56.1.3([email protected])deepmerge: 4.3.1@@ -17035,9 +17020,21 @@ snapshots:+ [email protected]([email protected])([email protected](@babel/[email protected])(@react-native/[email protected](@babel/[email protected])([email protected])([email protected]))(@types/[email protected])([email protected])([email protected])([email protected]))([email protected])([email protected]):+ dependencies:+ '@expo/config-plugins': 56.0.9([email protected])+ '@expo/config-types': 56.0.6+ '@expo/plist': 0.7.0+ expo: 56.0.12(8895228379997a2a064f9644cda56ed0)+ react: 19.2.3+ react-native: 0.85.3(@babel/[email protected])(@react-native/[email protected](@babel/[email protected])([email protected])([email protected]))(@types/[email protected])([email protected])([email protected])([email protected])+ transitivePeerDependencies:+ - supports-color+ - typescript+dependencies:- '@expo/config-plugins': 56.0.8([email protected])+ '@expo/config-plugins': 56.0.9([email protected])'@expo/image-utils': 0.10.1([email protected])expo: 56.0.12(8895228379997a2a064f9644cda56ed0)xml2js: 0.6.0diff --git a/pnpm-workspace.yaml b/pnpm-workspace.yamlindex 7d85b1059..096e21fcf 100644--- a/pnpm-workspace.yaml+++ b/pnpm-workspace.yaml@@ -86,6 +86,8 @@ overrides:"@types/node": "catalog:"effect: "catalog:"expo-modules-jsi: 56.0.10+ "expo-sharing>@expo/config-plugins": 56.0.9+ "expo-sharing>@expo/config-types": 56.0.6vite: "catalog:"yaml: "catalog:"