Skip to content

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

Add folder support in desktop (#42)

Denis Lupookov2b07aa0c554b
diff --git a/apps/desktop/src/electron/ipc.ts b/apps/desktop/src/electron/ipc.ts
index 24bee31..7102dad 100644
--- a/apps/desktop/src/electron/ipc.ts
+++ b/apps/desktop/src/electron/ipc.ts
@@ -8,7 +8,7 @@ import {
type OpenDialogOptions
} from 'electron'
import { isMac } from 'which-runtime'
-import { stat } from 'fs/promises'
+import { readdir, stat } from 'fs/promises'
import path from 'path'
import { isPathSafe, type TransferMethod } from '@altersend/core'
import type { DesktopRuntime } from './runtime.js'
@@ -31,6 +31,62 @@ function isAllowedPath(senderId: number, filePath: string): boolean {
return false
}
+interface PickedFile {
+ path: string
+ name: string
+ size: number
+ relativePath?: string
+}
+
+const FOLDER_SCAN_CONCURRENCY = 16
+
+function createLimit(max: number) {
+ let active = 0
+ const queue: (() => void)[] = []
+ const next = () => {
+ if (active >= max) return
+ const run = queue.shift()
+ if (!run) return
+ active++
+ run()
+ }
+
+ return <T>(task: () => Promise<T>): Promise<T> =>
+ new Promise<T>((resolve, reject) => {
+ queue.push(() => {
+ task()
+ .then(resolve, reject)
+ .finally(() => {
+ active--
+ next()
+ })
+ })
+ next()
+ })
+}
+
+async function collectFolderFiles(rootDir: string): Promise<PickedFile[]> {
+ const files: PickedFile[] = []
+ const limit = createLimit(FOLDER_SCAN_CONCURRENCY)
+ const walk = async (absDir: string, relDir: string): Promise<void> => {
+ const entries = await limit(() => readdir(absDir, { withFileTypes: true }))
+ await Promise.all(
+ entries.map(async (entry) => {
+ const abs = path.join(absDir, entry.name)
+ const rel = `${relDir}/${entry.name}`
+ if (entry.isDirectory()) {
+ await walk(abs, rel)
+ } else if (entry.isFile()) {
+ const fileStats = await limit(() => stat(abs))
+ files.push({ path: abs, name: entry.name, size: fileStats.size, relativePath: rel })
+ }
+ })
+ )
+ }
+ await walk(rootDir, path.basename(rootDir))
+ return files
+}
+
export function registerIpcHandlers(runtime: DesktopRuntime) {
ipcMain.on('pkg', (evt) => {
evt.returnValue = runtime.metadata.pkg
@@ -56,8 +112,8 @@ export function registerIpcHandlers(runtime: DesktopRuntime) {
ipcMain.handle('app:pickFiles', async (evt) => {
const parentWindow = BrowserWindow.fromWebContents(evt.sender) ?? undefined
const dialogOptions: OpenDialogOptions = {
- title: 'Select files to share',
- properties: ['openFile', 'multiSelections']
+ title: 'Select files or folders to share',
+ properties: ['openFile', 'openDirectory', 'multiSelections']
}
const result = parentWindow
? await dialog.showOpenDialog(parentWindow, dialogOptions)
@@ -68,19 +124,18 @@ export function registerIpcHandlers(runtime: DesktopRuntime) {
}
const id = evt.sender.id
- return Promise.all(
- result.filePaths.map(async (filePath) => {
- recordPickedPath(id, filePath)
- const fileName = path.basename(filePath)
- const fileStats = await stat(filePath)
-
- return {
- path: filePath,
- name: fileName,
- size: fileStats.size
- }
- })
- )
+ const picked: PickedFile[] = []
+ for (const filePath of result.filePaths) {
+ recordPickedPath(id, filePath)
+ const fileStats = await stat(filePath)
+ if (fileStats.isDirectory()) {
+ picked.push(...(await collectFolderFiles(filePath)))
+ } else {
+ picked.push({ path: filePath, name: path.basename(filePath), size: fileStats.size })
+ }
+ }
+
+ return picked
})
ipcMain.handle('app:pickSaveFile', async (evt, defaultName) => {
diff --git a/apps/desktop/src/electron/runtime.ts b/apps/desktop/src/electron/runtime.ts
index 584ee11..28d9221 100644
--- a/apps/desktop/src/electron/runtime.ts
+++ b/apps/desktop/src/electron/runtime.ts
@@ -110,7 +110,7 @@ function migrateIdentityIfNeeded(oldRoot: string, newRoot: string): void {
async function initDeviceKeychain(client: WorkerClient, identityRoot: string): Promise<void> {
const keyPath = path.join(identityRoot, 'device.key')
- const available = safeStorage.isEncryptionAvailable()
+ const available = app.isPackaged && safeStorage.isEncryptionAvailable()
let sealed: string | null = null
if (available) {
@@ -126,7 +126,7 @@ async function initDeviceKeychain(client: WorkerClient, identityRoot: string): P
const reply = await client.initDeviceSecret(
available ? { mode: 'managed', secret: sealed } : { mode: 'legacy' }
)
- if (available && reply.secretKey) {
+ if (available && reply.secretKey && reply.secretKey !== sealed) {
fs.mkdirSync(identityRoot, { recursive: true })
const tmp = keyPath + '.tmp'
fs.writeFileSync(tmp, safeStorage.encryptString(reply.secretKey))
diff --git a/apps/desktop/src/renderer/pages/ReceivePage/ReceiveConnectedView.tsx b/apps/desktop/src/renderer/pages/ReceivePage/ReceiveConnectedView.tsx
index 3ae90c6..13ca3aa 100644
--- a/apps/desktop/src/renderer/pages/ReceivePage/ReceiveConnectedView.tsx
+++ b/apps/desktop/src/renderer/pages/ReceivePage/ReceiveConnectedView.tsx
@@ -1,6 +1,6 @@
-import { useMemo } from 'react'
-import { Button, LinkRow } from '@altersend/components'
-import { DownloadIcon } from '@altersend/components/icons'
+import { Fragment, useMemo, useState } from 'react'
+import { Button, LinkRow, useTheme } from '@altersend/components'
+import { ChevronRightIcon, DownloadIcon, FolderIcon } from '@altersend/components/icons'
import { useTranslation } from '@altersend/locales'
import { bridgeApi } from '../../api/bridgeApi'
import {
@@ -10,10 +10,15 @@ import {
downloadFiles,
getDownloadRowDisplay,
getDownloadTotals,
+ getFolderRowDisplay,
getOfferKey,
+ groupReceiveRows,
+ type ReceiveFolderRow,
useTransferStore
} from '@altersend/domain'
+import type { IncomingFileOffer } from '@altersend/core'
+type FileOffer = Extract<IncomingFileOffer, { kind: 'file' }>
type DownloadRow = ReturnType<typeof getDownloadRowDisplay>
function getDownloadStatusLabel(t: ReturnType<typeof useTranslation>['t'], row: DownloadRow) {
@@ -31,16 +36,81 @@ function getDownloadStatusLabel(t: ReturnType<typeof useTranslation>['t'], row:
export function ReceiveConnectedView() {
const { t } = useTranslation(['receive', 'common', 'errors'])
+ const { theme } = useTheme()
const incomingFileOffers = useTransferStore((s) => s.incomingFileOffers)
const downloadStates = useTransferStore((s) => s.receiveDownloadStates)
const peerCount = useTransferStore((s) => s.peerCount)
+ const [expandedFolders, setExpandedFolders] = useState<Set<string>>(new Set())
const hasIncomingFiles = incomingFileOffers.length > 0
+ const rows = useMemo(() => groupReceiveRows(incomingFileOffers), [incomingFileOffers])
const totals = useMemo(
() => getDownloadTotals(incomingFileOffers, downloadStates),
[downloadStates, incomingFileOffers]
)
+ const toggleFolder = (name: string) =>
+ setExpandedFolders((prev) => {
+ const next = new Set(prev)
+ if (next.has(name)) next.delete(name)
+ else next.add(name)
+ return next
+ })
+
+ const statusFor = (row: DownloadRow) =>
+ row.status.kind === 'ready'
+ ? undefined
+ : { label: getDownloadStatusLabel(t, row), tone: row.status.tone }
+
+ const renderFileRow = (offer: FileOffer, isFirst = false) => {
+ const row = getDownloadRowDisplay(offer, downloadStates[getOfferKey(offer)])
+ return (
+ <LinkRow
+ key={getOfferKey(offer)}
+ file
+ bare
+ compact
+ isFirst={isFirst}
+ label={offer.name}
+ size={offer.size}
+ description={row.description}
+ status={statusFor(row)}
+ progressPercent={row.progressPercent}
+ />
+ )
+ }
+
+ const renderFolderRow = (folderRow: ReceiveFolderRow, isFirst = false) => {
+ const folder = getFolderRowDisplay(folderRow.offers, downloadStates)
+ const isExpanded = expandedFolders.has(folderRow.name)
+ return (
+ <Fragment key={`folder:${folderRow.name}`}>
+ <LinkRow
+ icon={<FolderIcon size={16} />}
+ bare
+ compact
+ isFirst={isFirst}
+ label={folderRow.name}
+ size={folderRow.totalSize}
+ description={folder.description}
+ status={statusFor(folder)}
+ progressPercent={folder.progressPercent}
+ onPress={() => toggleFolder(folderRow.name)}
+ trailing={
+ <span
+ className={`inline-flex transition-transform duration-200 ${isExpanded ? 'rotate-90' : ''}`}
+ >
+ <ChevronRightIcon size={14} color={theme.colors.colorTextMuted} />
+ </span>
+ }
+ />
+ {isExpanded ? (
+ <div className='pl-10'>{folderRow.offers.map((offer) => renderFileRow(offer))}</div>
+ ) : null}
+ </Fragment>
+ )
+ }
+
const isDownloading = totals.activeCount > 0
const allCompleted = hasIncomingFiles && totals.completedCount === incomingFileOffers.length
@@ -61,7 +131,9 @@ export function ReceiveConnectedView() {
const fileOffers = incomingFileOffers.filter((f) => f.kind === 'file')
if (fileOffers.length === 0 || isDownloading) return
- if (fileOffers.length === 1) {
+ const isSingleLooseFile = rows.length === 1 && rows[0].kind === 'file'
+
+ if (isSingleLooseFile) {
const selected = await bridgeApi.pickSaveFile(fileOffers[0].name)
if (!selected?.path) return
@@ -77,9 +149,7 @@ export function ReceiveConnectedView() {
if (!selectedDirectory?.path) return
try {
- await downloadFiles(
- createDirectoryDownloadRequests(incomingFileOffers, selectedDirectory.path)
- )
+ await downloadFiles(createDirectoryDownloadRequests(fileOffers, selectedDirectory.path))
} catch (error) {
console.error('ReceiveConnectedView: directory download failed', error)
}
@@ -96,23 +166,11 @@ export function ReceiveConnectedView() {
) : (
<div className='min-h-0 flex-1 overflow-y-auto pr-1'>
<div className='overflow-hidden rounded-[10px] border border-border-primary bg-background-subtle'>
- {incomingFileOffers.map((file) => {
- if (file.kind !== 'file') return null
- const row = getDownloadRowDisplay(file, downloadStates[getOfferKey(file)])
- return (
- <LinkRow
- key={getOfferKey(file)}
- file
- bare
- compact
- label={file.name}
- size={file.size}
- description={row.description}
- status={{ label: getDownloadStatusLabel(t, row), tone: row.status.tone }}
- progressPercent={row.progressPercent}
- />
- )
- })}
+ {rows.map((row, index) =>
+ row.kind === 'file'
+ ? renderFileRow(row.offer, index === 0)
+ : renderFolderRow(row, index === 0)
+ )}
</div>
</div>
)}
diff --git a/apps/desktop/src/renderer/pages/SendPage/SelectFilesView.tsx b/apps/desktop/src/renderer/pages/SendPage/SelectFilesView.tsx
index e5aaa7a..9b94a6d 100644
--- a/apps/desktop/src/renderer/pages/SendPage/SelectFilesView.tsx
+++ b/apps/desktop/src/renderer/pages/SendPage/SelectFilesView.tsx
@@ -1,8 +1,11 @@
import { useState } from 'react'
import { DropZoneLink, ErrorBanner, FileDropZone, LinkRow } from '@altersend/components'
+import { FolderIcon } from '@altersend/components/icons'
import { useTranslation } from '@altersend/locales'
import {
addSelectedFiles,
+ type BrowserFileLike,
+ groupSelectedFiles,
normalizeSelectedFiles,
removeSelectedFile,
useTransferStore,
@@ -11,18 +14,45 @@ import {
import { bridgeApi } from '../../api/bridgeApi'
import { Input, Button } from '@altersend/components'
-interface DataTransferEntryLike {
- isDirectory: boolean
+function readAllEntries(reader: FileSystemDirectoryReader): Promise<FileSystemEntry[]> {
+ return new Promise((resolve, reject) => {
+ const all: FileSystemEntry[] = []
+ const readBatch = () =>
+ reader.readEntries((batch) => {
+ if (batch.length === 0) resolve(all)
+ else {
+ all.push(...batch)
+ readBatch()
+ }
+ }, reject)
+ readBatch()
+ })
}
-function getEntry(item: DataTransferItem) {
- return (
- (
- item as DataTransferItem & {
- webkitGetAsEntry?: () => DataTransferEntryLike | null
- }
- ).webkitGetAsEntry?.() ?? null
- )
+function entryToFile(entry: FileSystemFileEntry): Promise<File> {
+ return new Promise((resolve, reject) => entry.file(resolve, reject))
+}
+
+async function collectDroppedEntries(
+ entry: FileSystemEntry,
+ getPathForFile: (file: File) => string,
+ out: BrowserFileLike[]
+): Promise<void> {
+ if (entry.isFile) {
+ const file = await entryToFile(entry as FileSystemFileEntry)
+ const path = getPathForFile(file)
+ if (path) {
+ out.push({
+ name: file.name,
+ path,
+ size: file.size,
+ relativePath: entry.fullPath.replace(/^\/+/, '')
+ })
+ }
+ } else if (entry.isDirectory) {
+ const entries = await readAllEntries((entry as FileSystemDirectoryEntry).createReader())
+ for (const child of entries) await collectDroppedEntries(child, getPathForFile, out)
+ }
}
export function SelectFilesView() {
@@ -50,24 +80,23 @@ export function SelectFilesView() {
setIsDropZoneDragging(false)
const items = Array.from(event.dataTransfer.items ?? [])
- let hasFolderSelection = false
- const droppedFiles =
- items.length > 0
- ? items.flatMap((item) => {
- const entry = getEntry(item)
- if (entry?.isDirectory) {
- hasFolderSelection = true
- return []
- }
-
- const file = item.kind === 'file' ? item.getAsFile() : null
- return file ? [file] : []
- })
- : Array.from(event.dataTransfer.files ?? [])
-
- setSelectionError(hasFolderSelection ? t('send:errors.folderUnsupported') : null)
-
- const normalizedFiles = normalizeSelectedFiles(droppedFiles, bridgeApi.getPathForFile)
+ const entries = items
+ .map((item) => (item.kind === 'file' ? item.webkitGetAsEntry() : null))
+ .filter((entry): entry is FileSystemEntry => entry !== null)
+ const fallbackFiles = entries.length === 0 ? Array.from(event.dataTransfer.files ?? []) : []
+
+ void ingestDrop(entries, fallbackFiles)
+ }
+
+ const ingestDrop = async (entries: FileSystemEntry[], fallbackFiles: File[]) => {
+ const dropped: Array<File | BrowserFileLike> = [...fallbackFiles]
+ for (const entry of entries) {
+ await collectDroppedEntries(entry, bridgeApi.getPathForFile, dropped)
+ }
+
+ setSelectionError(null)
+
+ const normalizedFiles = normalizeSelectedFiles(dropped, bridgeApi.getPathForFile)
if (normalizedFiles.length > 0) {
addSelectedFiles(normalizedFiles)
}
@@ -125,18 +154,31 @@ export function SelectFilesView() {
{hasSelectedFiles ? (
<div className='flex flex-col gap-1.5'>
- {selectedFiles.map((file) => (
- <LinkRow
- key={file.path}
- file
- standalone
- compact
- label={file.name}
- onRemove={() => removeSelectedFile(file.path)}
- removeLabel={t('send:files.removeLabel', { name: file.name })}
- size={file.size}
- />
- ))}
+ {groupSelectedFiles(selectedFiles).map((row) =>
+ row.kind === 'file' ? (
+ <LinkRow
+ key={row.file.path}
+ file
+ standalone
+ compact
+ label={row.file.name}
+ onRemove={() => removeSelectedFile(row.file.path)}
+ removeLabel={t('send:files.removeLabel', { name: row.file.name })}
+ size={row.file.size}
+ />
+ ) : (
+ <LinkRow
+ key={`folder:${row.name}`}
+ icon={<FolderIcon size={16} />}
+ standalone
+ compact
+ label={row.name}
+ onRemove={() => row.files.forEach((file) => removeSelectedFile(file.path))}
+ removeLabel={t('send:files.removeLabel', { name: row.name })}
+ size={row.totalSize}
+ />
+ )
+ )}
</div>
) : null}
diff --git a/apps/desktop/src/renderer/pages/SendPage/ShareView.tsx b/apps/desktop/src/renderer/pages/SendPage/ShareView.tsx
index e76b790..113a753 100644
--- a/apps/desktop/src/renderer/pages/SendPage/ShareView.tsx
+++ b/apps/desktop/src/renderer/pages/SendPage/ShareView.tsx
@@ -1,5 +1,10 @@
import { useState } from 'react'
-import { buildJoinUrl, formatFileSize, useShareViewModel } from '@altersend/domain'
+import {
+ buildJoinUrl,
+ formatFileSize,
+ groupSelectedFiles,
+ useShareViewModel
+} from '@altersend/domain'
import { Button, LinkCard, LinkRow, WaitingRadar, useTheme } from '@altersend/components'
import {
ChevronsUpDownIcon,
@@ -37,6 +42,8 @@ export function ShareView() {
})
const [isQrOpen, setIsQrOpen] = useState(false)
const hasConnectedDevices = vm.connectedCount > 0
+ const fileRows = groupSelectedFiles(vm.files)
+ const singleFolder = fileRows.length === 1 && fileRows[0].kind === 'folder' ? fileRows[0] : null
const copyTopic = async () => {
if (!vm.topic) return
@@ -53,7 +60,9 @@ export function ShareView() {
<LinkRow
compact
icon={<FolderIcon size={16} color={c.colorTextSecondary} />}
- label={t('common:files.count', { count: vm.files.length })}
+ label={
+ singleFolder ? singleFolder.name : t('common:files.count', { count: vm.files.length })
+ }
subtitle={formatFileSize(vm.totalSize)}
trailing={<ChevronsUpDownIcon size={16} color={c.colorTextMuted} />}
isLast
@@ -64,16 +73,28 @@ export function ShareView() {
{() => (
<div style={{ maxHeight: 280, overflowY: 'auto' }}>
<LinkCard>
- {vm.files.map((file, index) => (
- <LinkRow
- key={file.path}
- compact
- file
- label={file.name}
- size={file.size}
- isLast={index === vm.files.length - 1}
- />
- ))}
+ {fileRows.map((row, index) =>
+ row.kind === 'folder' ? (
+ <LinkRow
+ key={`folder:${row.name}`}
+ compact
+ icon={<FolderIcon size={16} color={c.colorTextSecondary} />}
+ label={row.name}
+ size={row.totalSize}
+ subtitle={t('common:files.count', { count: row.files.length })}
+ isLast={index === fileRows.length - 1}
+ />
+ ) : (
+ <LinkRow
+ key={row.file.path}
+ compact
+ file
+ label={row.file.name}
+ size={row.file.size}
+ isLast={index === fileRows.length - 1}
+ />
+ )
+ )}
</LinkCard>
</div>
)}
@@ -91,7 +112,7 @@ export function ShareView() {
onCopy={() => void copyTopic()}
placeholder={t('send:connection.placeholder')}
/>
- <div className='flex aspect-square shrink-0'>
+ <div className='flex h-12 w-12 shrink-0'>
<Button
variant='secondary'
iconOnly
diff --git a/apps/desktop/src/types.d.ts b/apps/desktop/src/types.d.ts
index c7bfaee..dd515b8 100644
--- a/apps/desktop/src/types.d.ts
+++ b/apps/desktop/src/types.d.ts
@@ -29,6 +29,7 @@ interface PickedFile {
path: string
name: string
size?: number
+ relativePath?: string
}
declare global {
diff --git a/packages/core/src/worklet/rpc/protocol.ts b/packages/core/src/worklet/rpc/protocol.ts
index ff06fee..a12321d 100644
--- a/packages/core/src/worklet/rpc/protocol.ts
+++ b/packages/core/src/worklet/rpc/protocol.ts
@@ -44,6 +44,7 @@ export interface JoinReply {
export interface ShareFileRequest {
path: string
+ relativePath?: string
isTemporary?: boolean
kind?: 'file' | 'text'
content?: string
diff --git a/packages/core/src/worklet/transfer/orchestrator.ts b/packages/core/src/worklet/transfer/orchestrator.ts
index b3ea955..6941727 100644
--- a/packages/core/src/worklet/transfer/orchestrator.ts
+++ b/packages/core/src/worklet/transfer/orchestrator.ts
@@ -405,7 +405,7 @@ export class TransferOrchestrator implements TransferRPC {
for (const error of errors) this.sendError(error)
if (files.length === 0 && textRequests.length === 0) {
- this.sendError('No valid items were selected to share. Folders are not supported yet.')
+ this.sendError('No valid items were selected to share.')
return { acceptedFiles: 0 }
}
diff --git a/packages/core/src/worklet/transfer/receiver.ts b/packages/core/src/worklet/transfer/receiver.ts
index e29766d..a14ab61 100644
--- a/packages/core/src/worklet/transfer/receiver.ts
+++ b/packages/core/src/worklet/transfer/receiver.ts
@@ -7,9 +7,10 @@ import {
getDirname,
getFileName,
isPathSafe,
- isSafeFileName,
+ isSafeRelativePath,
isValidHexKey,
- joinFilePath
+ joinFilePath,
+ toRelativePath
} from './utils'
import type { DownloadFileRequest, DownloadFileResult } from '../rpc/protocol'
import type { DownloaderCallbacks } from './download-events'
@@ -80,12 +81,12 @@ export class TransferReceiver {
continue
}
- if (!isSafeFileName(resolvedName)) {
- const fileName = typeof resolvedName === 'string' ? resolvedName : ''
+ const relativeTarget = toRelativePath(file.path)
+ if (!isSafeRelativePath(relativeTarget)) {
fail(
- fileName,
+ resolvedName,
file.targetPath ?? file.targetDir ?? '',
- 'Rejected unsafe file name from sender'
+ 'Rejected unsafe file path from sender'
)
continue
}
@@ -96,7 +97,7 @@ export class TransferReceiver {
continue
}
- const targetPath = file.targetPath ?? joinFilePath(file.targetDir!, resolvedName)
+ const targetPath = file.targetPath ?? joinFilePath(file.targetDir!, relativeTarget)
try {
const outcome = await this.downloadFile(file, targetPath, callbacks, signal)
diff --git a/packages/core/src/worklet/transfer/sender.ts b/packages/core/src/worklet/transfer/sender.ts
index 7a629c4..1dd2050 100644
--- a/packages/core/src/worklet/transfer/sender.ts
+++ b/packages/core/src/worklet/transfer/sender.ts
@@ -4,7 +4,7 @@ import b4a from 'b4a'
import Localdrive from 'localdrive'
import MirrorDrive from 'mirror-drive'
import type Hyperdrive from 'hyperdrive'
-import { AbortError, getDirname, getFileName } from './utils'
+import { AbortError, getDirname, getFileName, toRelativePath } from './utils'
import type { FileOffer } from './control-channel'
export interface ScannedFile {
@@ -27,6 +27,25 @@ function createFileId(): string {
return crypto.randomBytes(12).toString('hex')
}
+function resolveSource(
+ path: string,
+ requestedRelativePath: string | undefined,
+ fileName: string
+): { root: string; relativePath: string } {
+ const normalizedPath = path.replace(/\\/g, '/')
+ const relativePath = toRelativePath(requestedRelativePath ?? fileName)
+ const suffix = `/${relativePath}`
+
+ if (relativePath && normalizedPath.endsWith(suffix)) {
+ return {
+ root: normalizedPath.slice(0, normalizedPath.length - suffix.length) || '/',
+ relativePath
+ }
+ }
+
+ return { root: getDirname(path), relativePath: fileName }
+}
+
/**
* TransferSender handles the **sender** side of a file transfer.
*
@@ -50,7 +69,9 @@ export class TransferSender {
return b4a.toString(this.drive.key, 'hex')
}
- async scanFiles(requests: { path: string; isTemporary?: boolean }[]): Promise<ScanResult> {
+ async scanFiles(
+ requests: { path: string; relativePath?: string; isTemporary?: boolean }[]
+ ): Promise<ScanResult> {
const files: ScannedFile[] = []
const errors: string[] = []
let totalBytes = 0
@@ -60,12 +81,12 @@ export class TransferSender {
for (const req of requests) {
const path = req.path
const fileName = getFileName(path)
- const sourcePath = `/${fileName}`
- const dir = getDirname(path)
- let sourceDrive = driveByDir.get(dir)
+ const { root, relativePath } = resolveSource(path, req.relativePath, fileName)
+ const sourcePath = `/${relativePath}`
+ let sourceDrive = driveByDir.get(root)
if (!sourceDrive) {
- sourceDrive = new Localdrive(dir)
- driveByDir.set(dir, sourceDrive)
+ sourceDrive = new Localdrive(root)
+ driveByDir.set(root, sourceDrive)
this.scanDrives.add(sourceDrive)
await sourceDrive.ready()
}
diff --git a/packages/core/src/worklet/transfer/utils.test.ts b/packages/core/src/worklet/transfer/utils.test.ts
index 702e379..bee2987 100644
--- a/packages/core/src/worklet/transfer/utils.test.ts
+++ b/packages/core/src/worklet/transfer/utils.test.ts
@@ -5,8 +5,10 @@ import {
joinFilePath,
isPathSafe,
isSafeFileName,
+ isSafeRelativePath,
isValidHexKey,
- shortKey
+ shortKey,
+ toRelativePath
} from './utils'
describe('getDirname', () => {
@@ -185,6 +187,71 @@ describe('isPathSafe', () => {
})
})
+describe('isSafeRelativePath', () => {
+ it('accepts a plain file name', () => {
+ expect(isSafeRelativePath('report.pdf')).toBe(true)
+ })
+
+ it('accepts a nested relative path', () => {
+ expect(isSafeRelativePath('Photos/2024/img.png')).toBe(true)
+ })
+
+ it('rejects a rooted POSIX path (leading slash)', () => {
+ expect(isSafeRelativePath('/Photos/img.png')).toBe(false)
+ })
+
+ it('rejects a rooted Windows path (drive prefix)', () => {
+ expect(isSafeRelativePath('C:\\foo\\bar')).toBe(false)
+ expect(isSafeRelativePath('C:/foo/bar')).toBe(false)
+ expect(isSafeRelativePath('\\\\server\\share')).toBe(false)
+ })
+
+ it('rejects empty string', () => {
+ expect(isSafeRelativePath('')).toBe(false)
+ })
+
+ it('rejects a path with no real segments', () => {
+ expect(isSafeRelativePath('///')).toBe(false)
+ })
+
+ it('rejects parent traversal in any segment', () => {
+ expect(isSafeRelativePath('Photos/../../etc/passwd')).toBe(false)
+ expect(isSafeRelativePath('..')).toBe(false)
+ })
+
+ it('rejects a current-dir segment', () => {
+ expect(isSafeRelativePath('Photos/./img.png')).toBe(false)
+ })
+
+ it('rejects null-byte injection', () => {
+ expect(isSafeRelativePath('Photos/img\0.png')).toBe(false)
+ })
+
+ it('rejects a segment over 255 chars', () => {
+ expect(isSafeRelativePath(`Photos/${'a'.repeat(256)}.png`)).toBe(false)
+ })
+
+ it('rejects non-string input', () => {
+ expect(isSafeRelativePath(null)).toBe(false)
+ expect(isSafeRelativePath(42)).toBe(false)
+ expect(isSafeRelativePath(undefined)).toBe(false)
+ })
+})
+
+describe('toRelativePath', () => {
+ it('strips a leading slash', () => {
+ expect(toRelativePath('/Photos/img.png')).toBe('Photos/img.png')
+ })
+
+ it('normalizes backslashes to forward slashes', () => {
+ expect(toRelativePath('\\Photos\\img.png')).toBe('Photos/img.png')
+ })
+
+ it('leaves an already-relative path unchanged', () => {
+ expect(toRelativePath('img.png')).toBe('img.png')
+ })
+})
+
describe('shortKey', () => {
it('returns the first 8 chars of a hex key', () => {
expect(shortKey('abcdef1234567890')).toBe('abcdef12')
diff --git a/packages/core/src/worklet/transfer/utils.ts b/packages/core/src/worklet/transfer/utils.ts
index 08efc8b..94b0ba7 100644
--- a/packages/core/src/worklet/transfer/utils.ts
+++ b/packages/core/src/worklet/transfer/utils.ts
@@ -29,6 +29,28 @@ export function isSafeFileName(name: unknown): name is string {
return true
}
+export function isSafeRelativePath(value: unknown): value is string {
+ if (typeof value !== 'string') return false
+ if (value.length === 0 || value.length > 4096) return false
+ if (value.includes('\0')) return false
+
+ if (value.startsWith('/') || value.startsWith('\\')) return false
+ if (/^[a-zA-Z]:/.test(value)) return false
+
+ const segments = value.split(/[/\\]/).filter((segment) => segment.length > 0)
+
+ if (segments.length === 0) return false
+ for (const segment of segments) {
+ if (segment === '.' || segment === '..') return false
+ if (segment.length > 255) return false
+ }
+ return true
+}
+
+export function toRelativePath(drivePath: string): string {
+ return drivePath.replace(/\\/g, '/').replace(/^\/+/, '')
+}
+
export function shortKey(hex: string | null | undefined): string {
return hex ? hex.slice(0, 8) : '(none)'
}
diff --git a/packages/domain/src/receive/downloadModel.test.ts b/packages/domain/src/receive/downloadModel.test.ts
new file mode 100644
index 0000000..4fa9908
--- /dev/null
+++ b/packages/domain/src/receive/downloadModel.test.ts
@@ -0,0 +1,98 @@
+import { describe, it, expect } from 'vitest'
+import type { IncomingFileOffer } from '@altersend/core'
+import { groupReceiveRows, getFolderRowDisplay, type DownloadItemState } from './downloadModel'
+
+type FileOffer = Extract<IncomingFileOffer, { kind: 'file' }>
+
+function offer(path: string, overrides: Partial<FileOffer> = {}): FileOffer {
+ const name = path.split('/').filter(Boolean).pop() ?? path
+ return {
+ kind: 'file',
+ id: path,
+ transferId: 't1',
+ name,
+ path,
+ size: 100,
+ driveKey: 'd1',
+ ...overrides
+ }
+}
+
+function state(status: DownloadItemState['status'], bytes = 0): DownloadItemState {
+ return { status, bytesTransferred: bytes, totalBytes: 100 }
+}
+
+describe('groupReceiveRows', () => {
+ it('keeps loose files as standalone rows', () => {
+ const rows = groupReceiveRows([offer('/a.txt'), offer('/b.txt')])
+ expect(rows.map((r) => r.kind)).toEqual(['file', 'file'])
+ })
+
+ it('collapses files sharing a top-level folder into one row', () => {
+ const rows = groupReceiveRows([
+ offer('/Photos/a/img.png'),
+ offer('/Photos/b/img.png'),
+ offer('/Photos/c.png')
+ ])
+ expect(rows).toHaveLength(1)
+ expect(rows[0]).toMatchObject({ kind: 'folder', name: 'Photos', totalSize: 300 })
+ })
+
+ it('preserves first-appearance order across folders and files', () => {
+ const rows = groupReceiveRows([
+ offer('/Photos/a.png'),
+ offer('/loose.txt'),
+ offer('/Docs/x.pdf'),
+ offer('/Photos/b.png')
+ ])
+ expect(rows.map((r) => (r.kind === 'folder' ? r.name : r.offer.name))).toEqual([
+ 'Photos',
+ 'loose.txt',
+ 'Docs'
+ ])
+ })
+})
+
+describe('getFolderRowDisplay', () => {
+ const offers = [offer('/Photos/a.png'), offer('/Photos/b.png')]
+
+ it('reports saved when every file completed', () => {
+ const display = getFolderRowDisplay(offers, {
+ '/Photos/a.png': state('completed', 100),
+ '/Photos/b.png': state('completed', 100)
+ })
+ expect(display.status.kind).toBe('saved')
+ expect(display.isCompleted).toBe(true)
+ })
+
+ it('reports failed when any file failed', () => {
+ const display = getFolderRowDisplay(offers, {
+ '/Photos/a.png': state('completed', 100),
+ '/Photos/b.png': state('failed')
+ })
+ expect(display.status.kind).toBe('failed')
+ })
+
+ it('reports progress while any file is downloading', () => {
+ const display = getFolderRowDisplay(offers, {
+ '/Photos/a.png': state('completed', 100),
+ '/Photos/b.png': state('downloading', 50)
+ })
+ expect(display.status.kind).toBe('progress')
+ expect(display.percent).toBe(75)
+ })
+
+ it('reports progress when some files saved but none in flight', () => {
+ const display = getFolderRowDisplay(offers, {
+ '/Photos/a.png': state('completed', 100)
+ })
+ expect(display.status.kind).toBe('progress')
+ expect(display.percent).toBe(50)
+ expect(display.isCompleted).toBe(false)
+ })
+
+ it('reports ready before anything starts', () => {
+ const display = getFolderRowDisplay(offers, {})
+ expect(display.status.kind).toBe('ready')
+ })
+})
diff --git a/packages/domain/src/receive/downloadModel.ts b/packages/domain/src/receive/downloadModel.ts
index 2b99fdd..c306e6a 100644
--- a/packages/domain/src/receive/downloadModel.ts
+++ b/packages/domain/src/receive/downloadModel.ts
@@ -233,6 +233,104 @@ export function getDownloadTotals(
}
}
+function pathSegments(p: string): string[] {
+ return p.replace(/\\/g, '/').split('/').filter(Boolean)
+}
+
+type FileOffer = Extract<IncomingFileOffer, { kind: 'file' }>
+
+export interface ReceiveFileRow {
+ kind: 'file'
+ offer: FileOffer
+}
+
+export interface ReceiveFolderRow {
+ kind: 'folder'
+ name: string
+ offers: FileOffer[]
+ totalSize: number
+}
+
+export type ReceiveRow = ReceiveFileRow | ReceiveFolderRow
+
+export function groupReceiveRows(offers: IncomingFileOffer[]): ReceiveRow[] {
+ const rows: ReceiveRow[] = []
+ const folderRowIndex = new Map<string, number>()
+
+ for (const offer of offers) {
+ if (offer.kind !== 'file') continue
+ const segments = pathSegments(offer.path)
+ if (segments.length <= 1) {
+ rows.push({ kind: 'file', offer })
+ continue
+ }
+
+ const name = segments[0]
+ const existing = folderRowIndex.get(name)
+
+ if (existing === undefined) {
+ folderRowIndex.set(name, rows.length)
+ rows.push({ kind: 'folder', name, offers: [offer], totalSize: offer.size })
+ } else {
+ const row = rows[existing] as ReceiveFolderRow
+ row.offers.push(offer)
+ row.totalSize += offer.size
+ }
+ }
+
+ return rows
+}
+
+export function getFolderRowDisplay(
+ offers: FileOffer[],
+ states: Record<string, DownloadItemState>
+): DownloadRowDisplay {
+ const totals = getDownloadTotals(offers, states)
+ const anyFailed = offers.some((offer) => states[getOfferKey(offer)]?.status === 'failed')
+
+ if (totals.completedCount === offers.length) {
+ return {
+ description: undefined,
+ progressPercent: 100,
+ status: { kind: 'saved', tone: 'success' },
+ percent: 100,
+ isActive: false,
+ isCompleted: true
+ }
+ }
+
+ if (anyFailed) {
+ return {
+ description: undefined,
+ progressPercent: totals.bytesTransferred > 0 ? totals.percent : undefined,
+ status: { kind: 'failed', tone: 'muted' },
+ percent: totals.percent,
+ isActive: false,
+ isCompleted: false
+ }
+ }
+
+ if (totals.activeCount > 0 || totals.completedCount > 0) {
+ return {
+ description: `${formatFileSize(totals.bytesTransferred)} / ${formatFileSize(totals.totalBytes)}`,
+ progressPercent: totals.percent,
+ status: { kind: 'progress', tone: totals.percent > 0 ? 'active' : 'muted' },
+ percent: totals.percent,
+ isActive: totals.activeCount > 0,
+ isCompleted: false
+ }
+ }
+
+ return {
+ description: undefined,
+ progressPercent: undefined,
+ status: { kind: 'ready', tone: 'muted' },
+ percent: 0,
+ isActive: false,
+ isCompleted: false
+ }
+}
+
export function createSingleDownloadRequest(
file: IncomingFileOffer,
targetPath: string
diff --git a/packages/domain/src/send/draftModel.test.ts b/packages/domain/src/send/draftModel.test.ts
new file mode 100644
index 0000000..e6b4845
--- /dev/null
+++ b/packages/domain/src/send/draftModel.test.ts
@@ -0,0 +1,50 @@
+import { describe, it, expect } from 'vitest'
+import type { SelectedFile } from './draftTypes'
+import { groupSelectedFiles } from './draftModel'
+
+function file(path: string, relativePath?: string, size = 100): SelectedFile {
+ const name = path.split('/').filter(Boolean).pop() ?? path
+ return { name, path, size, relativePath }
+}
+
+describe('groupSelectedFiles', () => {
+ it('keeps plain files (no relativePath) as standalone rows', () => {
+ const rows = groupSelectedFiles([file('/tmp/a.txt'), file('/tmp/b.txt')])
+ expect(rows.map((r) => r.kind)).toEqual(['file', 'file'])
+ })
+
+ it('collapses files sharing a folder into one row with summed size', () => {
+ const rows = groupSelectedFiles([
+ file('/tmp/Photos/a.png', 'Photos/a.png', 100),
+ file('/tmp/Photos/sub/b.png', 'Photos/sub/b.png', 200)
+ ])
+ expect(rows).toHaveLength(1)
+ expect(rows[0]).toMatchObject({ kind: 'folder', name: 'Photos', totalSize: 300 })
+ })
+
+ it('treats a single-segment relativePath as a plain file', () => {
+ const rows = groupSelectedFiles([file('/tmp/a.txt', 'a.txt')])
+ expect(rows[0].kind).toBe('file')
+ })
+
+ it('preserves first-appearance order across folders and files', () => {
+ const rows = groupSelectedFiles([
+ file('/tmp/Photos/a.png', 'Photos/a.png'),
+ file('/tmp/loose.txt'),
+ file('/tmp/Photos/b.png', 'Photos/b.png')
+ ])
+ expect(rows.map((r) => (r.kind === 'folder' ? r.name : r.file.name))).toEqual([
+ 'Photos',
+ 'loose.txt'
+ ])
+ })
+
+ it('keeps two same-named folders from different source paths as separate rows', () => {
+ const rows = groupSelectedFiles([
+ file('/Users/d/Desktop/Photos/a.png', 'Photos/a.png'),
+ file('/Users/d/Work/Photos/b.png', 'Photos/b.png')
+ ])
+ expect(rows).toHaveLength(2)
+ expect(rows.every((r) => r.kind === 'folder' && r.name === 'Photos')).toBe(true)
+ })
+})
diff --git a/packages/domain/src/send/draftModel.ts b/packages/domain/src/send/draftModel.ts
index 01abed7..38868df 100644
--- a/packages/domain/src/send/draftModel.ts
+++ b/packages/domain/src/send/draftModel.ts
@@ -25,14 +25,22 @@ export function normalizeSelectedFiles(
filesOrData: Array<File | BrowserFileLike>,
getPathForFile: (file: File) => string
): SelectedFile[] {
- return filesOrData.flatMap((fileOrData) => {
+ return filesOrData.flatMap((fileOrData): SelectedFile[] => {
if ('path' in fileOrData && fileOrData.path) {
- return [{ name: fileOrData.name, path: fileOrData.path, size: fileOrData.size }]
+ return [
+ {
+ name: fileOrData.name,
+ path: fileOrData.path,
+ size: fileOrData.size,
+ relativePath: fileOrData.relativePath
+ }
+ ]
}
if (fileOrData instanceof File) {
const filePath = getPathForFile(fileOrData)
if (!filePath) return []
+
return [{ name: fileOrData.name, path: filePath, size: fileOrData.size }]
}
@@ -40,6 +48,53 @@ export function normalizeSelectedFiles(
})
}
+export interface SelectedFileRow {
+ kind: 'file'
+ file: SelectedFile
+}
+
+export interface SelectedFolderRow {
+ kind: 'folder'
+ name: string
+ files: SelectedFile[]
+ totalSize: number
+}
+
+export type SelectedRow = SelectedFileRow | SelectedFolderRow
+
+export function groupSelectedFiles(files: SelectedFile[]): SelectedRow[] {
+ const rows: SelectedRow[] = []
+ const folderRowIndex = new Map<string, number>()
+
+ for (const file of files) {
+ const relativePath = (file.relativePath ?? '').replace(/\\/g, '/')
+ const segments = relativePath.split('/').filter(Boolean)
+ if (segments.length <= 1) {
+ rows.push({ kind: 'file', file })
+ continue
+ }
+
+ const name = segments[0]
+
+ const normalizedPath = file.path.replace(/\\/g, '/')
+ const key = normalizedPath.endsWith(relativePath)
+ ? normalizedPath.slice(0, normalizedPath.length - relativePath.length) + name
+ : name
+
+ const existing = folderRowIndex.get(key)
+ if (existing === undefined) {
+ folderRowIndex.set(key, rows.length)
+ rows.push({ kind: 'folder', name, files: [file], totalSize: file.size ?? 0 })
+ } else {
+ const row = rows[existing] as SelectedFolderRow
+ row.files.push(file)
+ row.totalSize += file.size ?? 0
+ }
+ }
+
+ return rows
+}
+
export function createInitialUploadItems(selectedFiles: SelectedFile[]): SenderUploadItem[] {
return selectedFiles.map((file) => ({
...file,
diff --git a/packages/domain/src/send/draftTypes.ts b/packages/domain/src/send/draftTypes.ts
index 1f0e5d5..d23a512 100644
--- a/packages/domain/src/send/draftTypes.ts
+++ b/packages/domain/src/send/draftTypes.ts
@@ -5,6 +5,7 @@ export interface SelectedFile {
isTemporary?: boolean
kind?: 'file' | 'text'
content?: string
+ relativePath?: string
}
export type SenderUploadStatus = 'waiting' | 'uploading' | 'completed'
@@ -17,4 +18,5 @@ export interface BrowserFileLike {
name: string
path?: string
size?: number
+ relativePath?: string
}
diff --git a/packages/domain/src/send/useShareViewModel.ts b/packages/domain/src/send/useShareViewModel.ts
index d6a1a27..0ab4798 100644
--- a/packages/domain/src/send/useShareViewModel.ts
+++ b/packages/domain/src/send/useShareViewModel.ts
@@ -45,6 +45,7 @@ export interface FileRow {
path: string
name: string
size?: number
+ relativePath?: string
}
export interface ShareViewModel {
@@ -316,7 +317,12 @@ export function useShareViewModel(
return {
phase: connectionState === 'peer-connected' ? 'connected' : 'waiting',
topic,
- files: selectedFiles.map((f) => ({ path: f.path, name: f.name, size: f.size })),
+ files: selectedFiles.map((f) => ({
+ path: f.path,
+ name: f.name,
+ size: f.size,
+ relativePath: f.relativePath
+ })),
totalSize: selectedFiles.reduce((sum, f) => sum + (f.size ?? 0), 0),
devices,
connectedCount: connectedRows.length,
diff --git a/packages/domain/src/transfer/commands.ts b/packages/domain/src/transfer/commands.ts
index 20d269c..c9c4878 100644
--- a/packages/domain/src/transfer/commands.ts
+++ b/packages/domain/src/transfer/commands.ts
@@ -234,6 +234,7 @@ export const continueShare = async (files: SelectedFile[]): Promise<void> => {
const fileRequests: ShareFileRequest[] = files.map((file) => ({
path: file.path,
+ relativePath: file.relativePath,
isTemporary: file.isTemporary,
kind: file.kind,
content: file.content