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