Skip to content

Send files directly between devices over the internet - no cloud storage, no size limits.

Keep transfers running in the background for IOS (#81)

Denis Lupookov1235f2314565
diff --git a/apps/mobile/app.json b/apps/mobile/app.json
index 5c4796a..d6b3fce 100644
--- a/apps/mobile/app.json
+++ b/apps/mobile/app.json
@@ -22,7 +22,9 @@
"UIFileSharingEnabled": true,
"LSSupportsOpeningDocumentsInPlace": true,
"ITSAppUsesNonExemptEncryption": false,
- "CFBundleAllowMixedLocalizations": true
+ "CFBundleAllowMixedLocalizations": true,
+ "UIBackgroundModes": ["processing"],
+ "BGTaskSchedulerPermittedIdentifiers": ["com.altersend.mobile.transfer"]
},
"privacyManifests": {
"NSPrivacyTracking": false,
diff --git a/apps/mobile/app/(tabs)/receive/index.tsx b/apps/mobile/app/(tabs)/receive/index.tsx
index 50eb1d0..a75c513 100644
--- a/apps/mobile/app/(tabs)/receive/index.tsx
+++ b/apps/mobile/app/(tabs)/receive/index.tsx
@@ -12,12 +12,12 @@ import {
} from '@altersend/domain'
import { clearSession, joinSession } from '@altersend/domain'
import {
- ErrorPanel,
ReceiveConnectingView,
ReceiveInterruptedView,
ReceiveJoinView,
openCompletedFile
} from '@/src/transfer/receive'
+import { useErrorToast } from '@/src/transfer/receive/utils/useErrorToast'
import { Layout } from '@/src/components'
export default function ReceiveScreen() {
@@ -106,10 +106,7 @@ export default function ReceiveScreen() {
)
const displayError = getDisplayError(t, errorCode)
- const errorPanel =
- displayError && step !== 'interrupted' ? (
- <ErrorPanel title={t('receive:errors.transferIssue')} message={displayError} />
- ) : null
+ useErrorToast(step === 'interrupted' ? null : displayError, t('receive:errors.transferIssue'))
if (step === 'join') {
return (
@@ -127,11 +124,7 @@ export default function ReceiveScreen() {
}
if (step === 'connecting') {
- return (
- <ReceiveConnectingView title={title} description={copy.description} footer={footer}>
- {errorPanel}
- </ReceiveConnectingView>
- )
+ return <ReceiveConnectingView title={title} description={copy.description} footer={footer} />
}
if (step === 'interrupted') {
@@ -147,9 +140,5 @@ export default function ReceiveScreen() {
)
}
- return (
- <ReceiveConnectingView title={title} description={copy.description} footer={footer}>
- {errorPanel}
- </ReceiveConnectingView>
- )
+ return <ReceiveConnectingView title={title} description={copy.description} footer={footer} />
}
diff --git a/apps/mobile/app/_layout.tsx b/apps/mobile/app/_layout.tsx
index f5822bf..c369ef1 100644
--- a/apps/mobile/app/_layout.tsx
+++ b/apps/mobile/app/_layout.tsx
@@ -9,6 +9,7 @@ import type { Theme } from '@altersend/components'
import {
bindTransferApi,
startBackgroundReconnectEffect,
+ startDownloadRetryEffect,
startPeerWatchdog,
useSimulatedLoading
} from '@altersend/domain'
@@ -53,6 +54,7 @@ mobileApi.worker
startAppStateBridge()
startPeerWatchdog()
startBackgroundReconnectEffect()
+startDownloadRetryEffect()
startBackgroundTransferService()
startDownloadRoutingEffect()
startDeepLinkHandler()
diff --git a/apps/mobile/app/receive/incoming.tsx b/apps/mobile/app/receive/incoming.tsx
index bd75fef..e72a617 100644
--- a/apps/mobile/app/receive/incoming.tsx
+++ b/apps/mobile/app/receive/incoming.tsx
@@ -7,7 +7,8 @@ import { useTranslation } from '@altersend/locales'
import { useNavigation, useRouter } from 'expo-router'
import { uriToPath } from '@/src/api/mobileApi'
import { Layout, IllustrationLayout } from '@/src/components'
-import { ErrorPanel, ReceiveIncomingView, ReceiveReconnectingView } from '@/src/transfer/receive'
+import { ReceiveIncomingView, ReceiveReconnectingView } from '@/src/transfer/receive'
+import { useErrorToast } from '@/src/transfer/receive/utils/useErrorToast'
import { exitToReceiveTab } from '@/src/transfer/receive/utils/exitToReceiveTab'
import ConnectionLostSvg from '../../../../assets/connection-lost.svg'
import {
@@ -37,6 +38,8 @@ export default function ReceiveIncomingScreen() {
const errorCode = useTransferStore((s) => s.errorCode)
const displayError = getDisplayError(t, errorCode)
+ useErrorToast(displayError, t('receive:errors.transferIssue'))
+
const { totals, fileOffers, allDownloaded } = downloads
const hasIncomingFiles = incomingFileOffers.length > 0
const downloadableFileCount = fileOffers.length
@@ -200,9 +203,6 @@ export default function ReceiveIncomingScreen() {
</View>
}
>
- {displayError ? (
- <ErrorPanel title={t('receive:errors.transferIssue')} message={displayError} />
- ) : null}
<ReceiveIncomingView />
</Layout>
)
diff --git a/apps/mobile/modules/transfer-service/expo-module.config.json b/apps/mobile/modules/transfer-service/expo-module.config.json
index 148026e..d06f7fd 100644
--- a/apps/mobile/modules/transfer-service/expo-module.config.json
+++ b/apps/mobile/modules/transfer-service/expo-module.config.json
@@ -1,5 +1,9 @@
{
- "platforms": ["android"],
+ "platforms": ["android", "apple"],
+ "apple": {
+ "modules": ["TransferServiceModule"],
+ "appDelegateSubscribers": ["TransferTaskRegistrar"]
+ },
"android": {
"modules": ["expo.modules.transferservice.TransferServiceModule"]
}
diff --git a/apps/mobile/modules/transfer-service/ios/BackgroundAssertion.swift b/apps/mobile/modules/transfer-service/ios/BackgroundAssertion.swift
new file mode 100644
index 0000000..22f573b
--- /dev/null
+++ b/apps/mobile/modules/transfer-service/ios/BackgroundAssertion.swift
@@ -0,0 +1,37 @@
+import UIKit
+
+final class BackgroundAssertion {
+ private var taskId: UIBackgroundTaskIdentifier = .invalid
+ private let onExpire: () -> Void
+
+ init(onExpire: @escaping () -> Void) {
+ self.onExpire = onExpire
+ }
+
+ var isHeld: Bool {
+ taskId != .invalid
+ }
+
+ func begin() {
+ guard taskId == .invalid else { return }
+
+ taskId = UIApplication.shared.beginBackgroundTask(withName: "AlterSend.transfer") { [weak self] in
+ self?.expire()
+ }
+ }
+
+ func end() {
+ guard taskId != .invalid else { return }
+
+ let finished = taskId
+ taskId = .invalid
+ UIApplication.shared.endBackgroundTask(finished)
+ }
+
+ private func expire() {
+ guard taskId != .invalid else { return }
+
+ end()
+ onExpire()
+ }
+}
diff --git a/apps/mobile/modules/transfer-service/ios/ContinuedTransferTask.swift b/apps/mobile/modules/transfer-service/ios/ContinuedTransferTask.swift
new file mode 100644
index 0000000..8771041
--- /dev/null
+++ b/apps/mobile/modules/transfer-service/ios/ContinuedTransferTask.swift
@@ -0,0 +1,90 @@
+import BackgroundTasks
+import Foundation
+
+@available(iOS 26.0, *)
+final class ContinuedTransferTask {
+ static let shared = ContinuedTransferTask()
+ static let identifier = "com.altersend.mobile.transfer"
+
+ private var task: BGContinuedProcessingTask?
+ private var submitted = false
+ var onExpire: (() -> Void)?
+ var onAttach: (() -> Void)?
+
+ var isRunning: Bool {
+ task != nil
+ }
+
+ private init() {}
+
+ func register() {
+ BGTaskScheduler.shared.register(forTaskWithIdentifier: Self.identifier, using: .main) { [weak self] task in
+ guard let continued = task as? BGContinuedProcessingTask else {
+ task.setTaskCompleted(success: false)
+ return
+ }
+ self?.attach(continued)
+ }
+ }
+
+ func submit(title: String, subtitle: String) {
+ guard !submitted else { return }
+ submitted = true
+
+ let request = BGContinuedProcessingTaskRequest(
+ identifier: Self.identifier,
+ title: title,
+ subtitle: subtitle
+ )
+ request.strategy = .queue
+
+ do {
+ try BGTaskScheduler.shared.submit(request)
+ } catch {
+ submitted = false
+ NSLog("TransferService: continued task submit failed: \(error.localizedDescription)")
+ }
+ }
+
+ func update(title: String, subtitle: String, percent: Int) {
+ guard let task else { return }
+
+ task.updateTitle(title, subtitle: subtitle)
+
+ if percent < 0 {
+ task.progress.totalUnitCount = 0
+ task.progress.completedUnitCount = 0
+ return
+ }
+
+ task.progress.totalUnitCount = 100
+ task.progress.completedUnitCount = Int64(min(100, percent))
+ }
+
+ func finish() {
+ if let task {
+ let progress = task.progress
+ let complete = progress.totalUnitCount > 0
+ && progress.completedUnitCount >= progress.totalUnitCount
+ task.setTaskCompleted(success: complete)
+ } else if submitted {
+ BGTaskScheduler.shared.cancel(taskRequestWithIdentifier: Self.identifier)
+ }
+
+ task = nil
+ submitted = false
+ }
+
+ private func attach(_ continued: BGContinuedProcessingTask) {
+ task = continued
+ continued.progress.totalUnitCount = 100
+ onAttach?()
+
+ continued.expirationHandler = { [weak self] in
+ continued.setTaskCompleted(success: false)
+ self?.task = nil
+ self?.submitted = false
+ self?.onExpire?()
+ }
+ }
+}
diff --git a/apps/mobile/modules/transfer-service/ios/TransferNotificationContent.swift b/apps/mobile/modules/transfer-service/ios/TransferNotificationContent.swift
new file mode 100644
index 0000000..92549b1
--- /dev/null
+++ b/apps/mobile/modules/transfer-service/ios/TransferNotificationContent.swift
@@ -0,0 +1,8 @@
+import ExpoModulesCore
+
+struct TransferNotificationContent: Record {
+ @Field var title: String = ""
+ @Field var text: String = ""
+ @Field var subText: String = ""
+ @Field var progress: Int = -1
+}
diff --git a/apps/mobile/modules/transfer-service/ios/TransferService.podspec b/apps/mobile/modules/transfer-service/ios/TransferService.podspec
new file mode 100644
index 0000000..8298523
--- /dev/null
+++ b/apps/mobile/modules/transfer-service/ios/TransferService.podspec
@@ -0,0 +1,28 @@
+require 'json'
+
+package = JSON.parse(File.read(File.join(__dir__, '..', 'package.json')))
+
+Pod::Spec.new do |s|
+ s.name = 'TransferService'
+ s.version = package['version']
+ s.summary = 'Keeps AlterSend transfers running while the app is backgrounded'
+ s.description = s.summary
+ s.license = 'Apache-2.0'
+ s.author = 'AlterSend'
+ s.homepage = 'https://altersend.com'
+ s.platforms = {
+ :ios => '15.1'
+ }
+ s.swift_version = '5.9'
+ s.source = { git: 'https://github.com/denislupookov/altersend.git' }
+ s.static_framework = true
+
+ s.dependency 'ExpoModulesCore'
+
+ s.pod_target_xcconfig = {
+ 'DEFINES_MODULE' => 'YES',
+ 'SWIFT_COMPILATION_MODE' => 'wholemodule'
+ }
+
+ s.source_files = "**/*.{h,m,swift}"
+end
diff --git a/apps/mobile/modules/transfer-service/ios/TransferServiceModule.swift b/apps/mobile/modules/transfer-service/ios/TransferServiceModule.swift
new file mode 100644
index 0000000..9617161
--- /dev/null
+++ b/apps/mobile/modules/transfer-service/ios/TransferServiceModule.swift
@@ -0,0 +1,90 @@
+import ExpoModulesCore
+
+public class TransferServiceModule: Module {
+ private var assertion: BackgroundAssertion?
+
+ public func definition() -> ModuleDefinition {
+ Name("TransferService")
+
+ Events("onStopped")
+
+ OnDestroy {
+ self.releaseAssertion()
+ }
+
+ AsyncFunction("start") { (content: TransferNotificationContent, _: String) in
+ self.holdAssertion()
+ self.continueInBackground(content)
+ }
+ .runOnQueue(.main)
+
+ AsyncFunction("update") { (content: TransferNotificationContent) in
+ self.holdAssertion()
+ self.continueInBackground(content)
+
+ if #available(iOS 26.0, *) {
+ ContinuedTransferTask.shared.update(
+ title: content.title,
+ subtitle: content.text,
+ percent: content.progress
+ )
+ }
+ }
+ .runOnQueue(.main)
+
+ AsyncFunction("notifyCompleted") { (_: String, _: String, _: String) in
+ }
+
+ AsyncFunction("setTransferring") { (_: Bool) in
+ }
+
+ AsyncFunction("stop") {
+ if #available(iOS 26.0, *) {
+ ContinuedTransferTask.shared.finish()
+ }
+ self.releaseAssertion()
+ }
+ .runOnQueue(.main)
+ }
+
+ private func continueInBackground(_ content: TransferNotificationContent) {
+ guard content.progress >= 0 else { return }
+
+ if #available(iOS 26.0, *) {
+ ContinuedTransferTask.shared.onExpire = { [weak self] in
+ self?.sendEvent("onStopped", [:])
+ }
+ ContinuedTransferTask.shared.onAttach = { [weak self] in
+ self?.releaseAssertion()
+ }
+ ContinuedTransferTask.shared.submit(title: content.title, subtitle: content.text)
+ }
+ }
+
+ private func continuedTaskIsRunning() -> Bool {
+ if #available(iOS 26.0, *) {
+ return ContinuedTransferTask.shared.isRunning
+ }
+ return false
+ }
+
+ private func holdAssertion() {
+ guard !continuedTaskIsRunning() else { return }
+
+ if assertion == nil {
+ assertion = BackgroundAssertion { [weak self] in
+ guard let self else { return }
+ self.assertion = nil
+ if !self.continuedTaskIsRunning() {
+ self.sendEvent("onStopped", [:])
+ }
+ }
+ }
+ assertion?.begin()
+ }
+
+ private func releaseAssertion() {
+ assertion?.end()
+ assertion = nil
+ }
+}
diff --git a/apps/mobile/modules/transfer-service/ios/TransferTaskRegistrar.swift b/apps/mobile/modules/transfer-service/ios/TransferTaskRegistrar.swift
new file mode 100644
index 0000000..a97e13a
--- /dev/null
+++ b/apps/mobile/modules/transfer-service/ios/TransferTaskRegistrar.swift
@@ -0,0 +1,13 @@
+import ExpoModulesCore
+
+public class TransferTaskRegistrar: ExpoAppDelegateSubscriber {
+ public func application(
+ _ application: UIApplication,
+ didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]? = nil
+ ) -> Bool {
+ if #available(iOS 26.0, *) {
+ ContinuedTransferTask.shared.register()
+ }
+ return true
+ }
+}
diff --git a/apps/mobile/src/api/mobileApi.ts b/apps/mobile/src/api/mobileApi.ts
index bbad6d6..0e5ce46 100644
--- a/apps/mobile/src/api/mobileApi.ts
+++ b/apps/mobile/src/api/mobileApi.ts
@@ -173,6 +173,7 @@ class MobileApi {
if (state !== 'background' || worklet.suspended) return
if (isBackgroundTransferActive()) return
+ if (Platform.OS !== 'android') return
worklet.suspend()
}
diff --git a/apps/mobile/src/components/Toast/Toast.tsx b/apps/mobile/src/components/Toast/Toast.tsx
index 8b316a8..b115ed4 100644
--- a/apps/mobile/src/components/Toast/Toast.tsx
+++ b/apps/mobile/src/components/Toast/Toast.tsx
@@ -3,9 +3,12 @@ import { Animated, Easing, Platform } from 'react-native'
import { ToastIos } from './ToastIos'
import { ToastAndroid } from './ToastAndroid'
+export type ToastTone = 'success' | 'error'
+
export interface ToastPayload {
id: number
title: string
+ tone?: ToastTone
hint?: string
actionLabel?: string
onPress?: () => void
@@ -71,6 +74,7 @@ export function Toast({ toast, onDismiss }: ToastProps) {
<ToastIos
title={toast.title}
hint={toast.hint}
+ tone={toast.tone}
translate={translate}
opacity={opacity}
onPress={handlePress}
@@ -82,6 +86,7 @@ export function Toast({ toast, onDismiss }: ToastProps) {
<ToastAndroid
title={toast.title}
hint={toast.hint}
+ tone={toast.tone}
actionLabel={toast.actionLabel}
translate={translate}
opacity={opacity}
diff --git a/apps/mobile/src/components/Toast/ToastAndroid.tsx b/apps/mobile/src/components/Toast/ToastAndroid.tsx
index 0366444..7a97227 100644
--- a/apps/mobile/src/components/Toast/ToastAndroid.tsx
+++ b/apps/mobile/src/components/Toast/ToastAndroid.tsx
@@ -3,9 +3,11 @@ import { Animated, Pressable, StyleSheet, View } from 'react-native'
import { useSafeAreaInsets } from 'react-native-safe-area-context'
import { useTheme } from '@altersend/components'
import { Text } from '@/src/components/ThemedText'
+import type { ToastTone } from './Toast'
interface ToastAndroidProps {
title: string
+ tone?: ToastTone
hint?: string
actionLabel?: string
translate: Animated.Value
@@ -16,6 +18,7 @@ interface ToastAndroidProps {
export function ToastAndroid({
title,
hint,
+ tone,
actionLabel,
translate,
opacity,
@@ -43,7 +46,15 @@ export function ToastAndroid({
]}
>
<View style={styles.textBlock}>
- <Text numberOfLines={1} style={[styles.title, { color: theme.colors.colorTextPrimary }]}>
+ <Text
+ numberOfLines={1}
+ style={[
+ styles.title,
+ {
+ color: tone === 'error' ? theme.colors.colorDanger : theme.colors.colorTextPrimary
+ }
+ ]}
+ >
{title}
</Text>
{hint ? (
diff --git a/apps/mobile/src/components/Toast/ToastIos.tsx b/apps/mobile/src/components/Toast/ToastIos.tsx
index 252a939..076da34 100644
--- a/apps/mobile/src/components/Toast/ToastIos.tsx
+++ b/apps/mobile/src/components/Toast/ToastIos.tsx
@@ -2,18 +2,20 @@ import React from 'react'
import { Animated, Pressable, StyleSheet, View } from 'react-native'
import { useSafeAreaInsets } from 'react-native-safe-area-context'
import { useTheme } from '@altersend/components'
-import { CheckIcon } from '@altersend/components/icons'
+import { AlertCircleIcon, CheckIcon } from '@altersend/components/icons'
import { Text } from '@/src/components/ThemedText'
+import type { ToastTone } from './Toast'
interface ToastIosProps {
title: string
hint?: string
+ tone?: ToastTone
translate: Animated.Value
opacity: Animated.Value
onPress: () => void
}
-export function ToastIos({ title, hint, translate, opacity, onPress }: ToastIosProps) {
+export function ToastIos({ title, hint, tone, translate, opacity, onPress }: ToastIosProps) {
const { theme } = useTheme()
const insets = useSafeAreaInsets()
@@ -36,8 +38,20 @@ export function ToastIos({ title, hint, translate, opacity, onPress }: ToastIosP
}
]}
>
- <View style={[styles.icon, { backgroundColor: theme.colors.colorSuccess }]}>
- <CheckIcon size={14} color={theme.colors.colorTextPrimary} />
+ <View
+ style={[
+ styles.icon,
+ {
+ backgroundColor:
+ tone === 'error' ? theme.colors.colorDanger : theme.colors.colorSuccess
+ }
+ ]}
+ >
+ {tone === 'error' ? (
+ <AlertCircleIcon size={14} color={theme.colors.colorTextPrimary} />
+ ) : (
+ <CheckIcon size={14} color={theme.colors.colorTextPrimary} />
+ )}
</View>
<View style={styles.textBlock}>
<Text numberOfLines={1} style={[styles.title, { color: theme.colors.colorTextPrimary }]}>
diff --git a/apps/mobile/src/lifecycle/backgroundTransferService.ts b/apps/mobile/src/lifecycle/backgroundTransferService.ts
index 8ef4996..57bb903 100644
--- a/apps/mobile/src/lifecycle/backgroundTransferService.ts
+++ b/apps/mobile/src/lifecycle/backgroundTransferService.ts
@@ -53,7 +53,7 @@ let session: TransferSession | null = null
const report = (context: string) => captureIn(`backgroundTransferService.${context}`)
async function requestNotificationPermission(): Promise<void> {
- if (permissionRequested) return
+ if (permissionRequested || Platform.OS !== 'android') return
const version = Platform.Version
if (typeof version === 'number' && version < NOTIFICATION_PERMISSION_SDK) return
diff --git a/apps/mobile/src/transfer/receive/index.ts b/apps/mobile/src/transfer/receive/index.ts
index 341744f..43b2980 100644
--- a/apps/mobile/src/transfer/receive/index.ts
+++ b/apps/mobile/src/transfer/receive/index.ts
@@ -1,4 +1,3 @@
-export { ErrorPanel } from './views/ErrorPanel'
export { ReceiveCompleteView } from './views/ReceiveCompleteView'
export { ReceiveConnectingView } from './views/ReceiveConnectingView'
export { ReceiveIncomingView } from './views/ReceiveIncomingView'
diff --git a/apps/mobile/src/transfer/receive/utils/useErrorToast.ts b/apps/mobile/src/transfer/receive/utils/useErrorToast.ts
new file mode 100644
index 0000000..f0e4169
--- /dev/null
+++ b/apps/mobile/src/transfer/receive/utils/useErrorToast.ts
@@ -0,0 +1,19 @@
+import { useEffect } from 'react'
+import { pushToast } from '@/src/components/Toast'
+
+const ERROR_TOAST_DURATION_MS = 5000
+
+let shown: string | null = null
+
+export function useErrorToast(message: string | null, title: string): void {
+ useEffect(() => {
+ if (!message) {
+ shown = null
+ return
+ }
+ if (shown === message) return
+
+ shown = message
+ pushToast({ title, hint: message, tone: 'error', durationMs: ERROR_TOAST_DURATION_MS })
+ }, [message, title])
+}
diff --git a/apps/mobile/src/transfer/receive/views/ErrorPanel.tsx b/apps/mobile/src/transfer/receive/views/ErrorPanel.tsx
deleted file mode 100644
index d3966c1..0000000
--- a/apps/mobile/src/transfer/receive/views/ErrorPanel.tsx
+++ /dev/null
@@ -1,65 +0,0 @@
-import { StyleSheet, View } from 'react-native'
-import { useTheme, withAlpha } from '@altersend/components'
-import { AlertCircleIcon } from '@altersend/components/icons'
-import { Text } from '@/src/components/ThemedText'
-
-interface ErrorPanelProps {
- title: string
- message: string
-}
-
-export function ErrorPanel({ title, message }: ErrorPanelProps) {
- const { theme } = useTheme()
- const c = theme.colors
- return (
- <View
- style={[
- styles.container,
- {
- backgroundColor: withAlpha(c.colorDanger, 0.12),
- borderColor: withAlpha(c.colorDanger, 0.24)
- }
- ]}
- >
- <View style={[styles.iconBox, { backgroundColor: withAlpha(c.colorDanger, 0.18) }]}>
- <AlertCircleIcon size={20} color={c.colorDanger} />
- </View>
- <View style={styles.content}>
- <Text style={[styles.title, { color: c.colorDanger }]}>{title}</Text>
- <Text style={[styles.text, { color: c.colorDanger }]}>{message}</Text>
- </View>
- </View>
- )
-}
-
-const styles = StyleSheet.create({
- container: {
- flexDirection: 'row',
- alignItems: 'center',
- gap: 14,
- borderRadius: 12,
- borderWidth: 1,
- padding: 16
- },
- iconBox: {
- width: 40,
- height: 40,
- borderRadius: 12,
- alignItems: 'center',
- justifyContent: 'center'
- },
- content: {
- flex: 1,
- gap: 2
- },
- title: {
- fontSize: 15,
- fontWeight: '700',
- lineHeight: 20,
- letterSpacing: -0.2
- },
- text: {
- fontSize: 13,
- lineHeight: 18
- }
-})
diff --git a/packages/core/src/worklet/transfer/orchestrator.ts b/packages/core/src/worklet/transfer/orchestrator.ts
index 48d9b31..6065002 100644
--- a/packages/core/src/worklet/transfer/orchestrator.ts
+++ b/packages/core/src/worklet/transfer/orchestrator.ts
@@ -617,7 +617,7 @@ export class TransferOrchestrator implements TransferRPC {
throw new BadRequestError('Missing files to download')
}
if (this.suspended) {
- throw new BadRequestError('Cannot download files while suspended')
+ await this.resume()
}
const controller = new AbortController()
diff --git a/packages/domain/src/receive/autoResume.test.ts b/packages/domain/src/receive/autoResume.test.ts
new file mode 100644
index 0000000..7d21ec1
--- /dev/null
+++ b/packages/domain/src/receive/autoResume.test.ts
@@ -0,0 +1,48 @@
+import { describe, expect, it } from 'vitest'
+import { applyDownloadMessage, isAutoResumable, type DownloadItemState } from './downloadModel'
+
+const failed = (overrides: Partial<DownloadItemState> = {}): DownloadItemState => ({
+ status: 'failed',
+ bytesTransferred: 400,
+ totalBytes: 1000,
+ resumable: true,
+ savedTo: '/tmp/a.bin',
+ ...overrides
+})
+
+describe('isAutoResumable', () => {
+ it('retries a resumable network failure', () => {
+ expect(isAutoResumable(failed())).toBe(true)
+ })
+
+ it('never retries a download the user paused', () => {
+ expect(isAutoResumable(failed({ pausedByUser: true }))).toBe(false)
+ })
+
+ it('stops once retries are exhausted', () => {
+ expect(isAutoResumable(failed({ retriesExhausted: true }))).toBe(false)
+ })
+
+ it('ignores failures that cannot be resumed', () => {
+ expect(isAutoResumable(failed({ resumable: false }))).toBe(false)
+ expect(isAutoResumable(failed({ savedTo: undefined }))).toBe(false)
+ })
+
+ it('keeps a known partial resumable when a retry fails instantly', () => {
+ const previous = failed()
+ const next = applyDownloadMessage({ a: previous }, 'a', {
+ type: 'status',
+ state: 'download-failed',
+ fileId: 'a',
+ message: 'peer unavailable'
+ } as never)
+
+ expect(next.a.resumable).toBe(true)
+ expect(isAutoResumable(next.a)).toBe(true)
+ })
+
+ it('ignores downloads that are not failed', () => {
+ expect(isAutoResumable(failed({ status: 'downloading' }))).toBe(false)
+ expect(isAutoResumable(undefined)).toBe(false)
+ })
+})
diff --git a/packages/domain/src/receive/downloadModel.ts b/packages/domain/src/receive/downloadModel.ts
index ccf5f76..4a4aacf 100644
--- a/packages/domain/src/receive/downloadModel.ts
+++ b/packages/domain/src/receive/downloadModel.ts
@@ -23,6 +23,13 @@ export interface DownloadItemState {
starting?: boolean
queued?: boolean
pausable?: boolean
+ pausedByUser?: boolean
+ retriesExhausted?: boolean
+}
+
+export function isAutoResumable(state: DownloadItemState | undefined): boolean {
+ if (!isResumable(state)) return false
+ return state?.pausedByUser !== true && state?.retriesExhausted !== true
}
export type DownloadRowStatusTone = 'muted' | 'active' | 'success'
@@ -353,7 +360,9 @@ export function applyDownloadMessage(
queued: undefined,
message: message.message,
savedTo: message.savedTo ?? previous.savedTo,
- resumable: message.resumable === true
+ resumable: message.resumable === true || previous.resumable === true,
+ pausedByUser: message.cancelled === true || undefined,
+ retriesExhausted: undefined
}
}
}
diff --git a/packages/domain/src/transfer/activity.ts b/packages/domain/src/transfer/activity.ts
index 3da7469..e9c0486 100644
--- a/packages/domain/src/transfer/activity.ts
+++ b/packages/domain/src/transfer/activity.ts
@@ -1,4 +1,4 @@
-import { getDownloadTotals } from '../receive/downloadModel'
+import { getDownloadTotals, isAutoResumable } from '../receive/downloadModel'
import { summarizeEvents, type PeerDownloadEvent } from '../send/shareModel'
import type { SenderUploadItem } from '../send/draftTypes'
import { toProgressPercent } from './rate'
@@ -123,15 +123,17 @@ function getReceiverActivity(state: TransferSessionState): TransferActivity {
let queued = false
let failed = false
let routing = false
+ let retrying = false
for (const item of Object.values(state.receiveDownloadStates)) {
if (item.queued === true) queued = true
if (item.status === 'failed') failed = true
if (item.status === 'completed' && item.destination === undefined) routing = true
+ if (state.peerCount > 0 && isAutoResumable(item)) retrying = true
}
return {
- active: totals.activeCount > 0 || queued || routing,
+ active: totals.activeCount > 0 || queued || routing || retrying,
settled: !failed,
role: 'receiver',
phase: 'transferring',
diff --git a/packages/domain/src/transfer/effects/downloadRetryEffect.ts b/packages/domain/src/transfer/effects/downloadRetryEffect.ts
new file mode 100644
index 0000000..aa4834b
--- /dev/null
+++ b/packages/domain/src/transfer/effects/downloadRetryEffect.ts
@@ -0,0 +1,98 @@
+import {
+ createSingleDownloadRequest,
+ getOfferKey,
+ isAutoResumable
+} from '../../receive/downloadModel'
+import { downloadFiles } from '../commands'
+import { reportError } from '../binding'
+import { dispatchToTransferStore, transferStore } from '../store'
+import type { TransferSessionState } from '../types'
+
+const MAX_ATTEMPTS = 3
+
+let started = false
+let unsubscribe: (() => void) | null = null
+let inFlight = false
+const attempts = new Map<string, number>()
+const seenBytes = new Map<string, number>()
+
+function collectRetryable(state: TransferSessionState): string[] {
+ const retryable: string[] = []
+
+ for (const [key, item] of Object.entries(state.receiveDownloadStates)) {
+ if (item.bytesTransferred > (seenBytes.get(key) ?? 0)) {
+ seenBytes.set(key, item.bytesTransferred)
+ attempts.delete(key)
+ }
+
+ if (item.status === 'downloading') continue
+ if (item.status === 'completed') {
+ attempts.delete(key)
+ continue
+ }
+ if (isAutoResumable(item)) retryable.push(key)
+ }
+
+ return retryable
+}
+
+function retry(state: TransferSessionState, keys: string[]): void {
+ const exhausted = keys.filter((key) => (attempts.get(key) ?? 0) >= MAX_ATTEMPTS)
+ if (exhausted.length > 0) {
+ dispatchToTransferStore({ type: 'downloads_retries_exhausted', offerKeys: exhausted })
+ }
+
+ const retryable = keys.filter((key) => (attempts.get(key) ?? 0) < MAX_ATTEMPTS)
+ if (retryable.length === 0) return
+
+ const requests = retryable
+ .map((key) => {
+ const offer = state.incomingFileOffers.find((item) => getOfferKey(item) === key)
+ const savedTo = state.receiveDownloadStates[key]?.savedTo
+ if (offer?.kind !== 'file' || !savedTo) return null
+ return createSingleDownloadRequest(offer, savedTo)
+ })
+ .filter((request) => request !== null)
+
+ if (requests.length === 0) return
+
+ for (const key of retryable) attempts.set(key, (attempts.get(key) ?? 0) + 1)
+
+ inFlight = true
+ downloadFiles(requests)
+ .catch((error: unknown) => reportError('downloadRetryEffect', error))
+ .finally(() => {
+ inFlight = false
+ evaluate(transferStore.getState())
+ })
+}
+
+function evaluate(state: TransferSessionState): void {
+ if (state.role !== 'receiver') {
+ attempts.clear()
+ seenBytes.clear()
+ return
+ }
+ if (inFlight || state.peerCount === 0) return
+
+ const keys = collectRetryable(state)
+ if (keys.length > 0) retry(state, keys)
+}
+
+export function startDownloadRetryEffect(): () => void {
+ if (started) return teardown
+ started = true
+
+ unsubscribe = transferStore.subscribe(evaluate)
+
+ return teardown
+}
+
+function teardown(): void {
+ started = false
+ inFlight = false
+ attempts.clear()
+ seenBytes.clear()
+ unsubscribe?.()
+ unsubscribe = null
+}
diff --git a/packages/domain/src/transfer/index.ts b/packages/domain/src/transfer/index.ts
index 83c557e..107acf7 100644
--- a/packages/domain/src/transfer/index.ts
+++ b/packages/domain/src/transfer/index.ts
@@ -17,3 +17,4 @@ export * from './effects/appActive'
export * from './effects/backgroundTransfer'
export * from './effects/peerWatchdog'
export * from './effects/backgroundReconnectEffect'
+export * from './effects/downloadRetryEffect'
diff --git a/packages/domain/src/transfer/reducer.ts b/packages/domain/src/transfer/reducer.ts
index 53bfd8f..e40f501 100644
--- a/packages/domain/src/transfer/reducer.ts
+++ b/packages/domain/src/transfer/reducer.ts
@@ -374,6 +374,17 @@ export function transferSessionReducer(
)
}
}
+ case 'downloads_retries_exhausted': {
+ if (state.role !== 'receiver') return state
+
+ const next = { ...state.receiveDownloadStates }
+ for (const key of action.offerKeys) {
+ const previous = next[key]
+ if (!previous) continue
+ next[key] = { ...previous, retriesExhausted: true }
+ }
+ return { ...state, receiveDownloadStates: next }
+ }
case 'download_routed':
if (state.role !== 'receiver') return state
return {
diff --git a/packages/domain/src/transfer/types.ts b/packages/domain/src/transfer/types.ts
index cb444b9..b7f0603 100644
--- a/packages/domain/src/transfer/types.ts
+++ b/packages/domain/src/transfer/types.ts
@@ -111,6 +111,7 @@ export type TransferAction =
| { type: 'clear_send_draft' }
| { type: 'receive_download_event'; event: ReceiveDownloadStatusEvent }
| { type: 'downloads_queued'; offerKeys: string[]; queued: boolean }
+ | { type: 'downloads_retries_exhausted'; offerKeys: string[] }
| {
type: 'download_routed'
offerKey: string
diff --git a/packages/locales/src/source-copy.test.ts b/packages/locales/src/source-copy.test.ts
index 4a9f57f..c3ac4e2 100644
--- a/packages/locales/src/source-copy.test.ts
+++ b/packages/locales/src/source-copy.test.ts
@@ -21,7 +21,7 @@ const hardcodedCopyChecks = [
snippets: ['Devices', '1 connected', '${activeCount} connected']
},
{
- file: 'apps/mobile/src/transfer/receive/views/ErrorPanel.tsx',
+ file: 'apps/mobile/src/transfer/receive/utils/useErrorToast.ts',
snippets: ['Transfer issue']
},
{