Open source Loom alternative. Beautiful, shareable screen recordings.
Rust appcapcossloommacnextjsnextjs15open-sourceossreactrecordrustscreen-capturescreen-recorderscreenshotsolidjstauritauri-apptypescriptvite
feat(mobile): add upload queue and runner
Richie McIlroyb85d8714a475
diff --git a/apps/mobile/src/uploads/fileTypes.test.ts b/apps/mobile/src/uploads/fileTypes.test.tsnew file mode 100644index 000000000..d253cfb31--- /dev/null+++ b/apps/mobile/src/uploads/fileTypes.test.ts@@ -0,0 +1,27 @@+import { describe, expect, it } from "vitest";+import { contentTypeForUpload, contentTypeFromName } from "./fileTypes";++describe("mobile upload file type inference", () => {+ it.each([+ ["demo.mp4", "video/mp4"],+ ["demo.mov", "video/quicktime"],+ ["demo.webm", "video/webm"],+ ["demo.mkv", "video/x-matroska"],+ ["demo.avi", "video/x-msvideo"],+ ["demo.m4v", "video/x-m4v"],+ ])("infers %s as %s", (name, contentType) => {+ expect(contentTypeFromName(name)).toBe(contentType);+ });++ it("keeps picker-provided video content types", () => {+ expect(contentTypeForUpload("demo.mkv", "video/custom")).toBe(+ "video/custom",+ );+ });++ it("falls back to the filename when the picker returns an opaque type", () => {+ expect(contentTypeForUpload("demo.mkv", "application/octet-stream")).toBe(+ "video/x-matroska",+ );+ });+});diff --git a/apps/mobile/src/uploads/fileTypes.ts b/apps/mobile/src/uploads/fileTypes.tsnew file mode 100644index 000000000..b75393056--- /dev/null+++ b/apps/mobile/src/uploads/fileTypes.ts@@ -0,0 +1,24 @@+const videoContentTypesByExtension: Record<string, string> = {+ avi: "video/x-msvideo",+ m4v: "video/x-m4v",+ mkv: "video/x-matroska",+ mov: "video/quicktime",+ mp4: "video/mp4",+ webm: "video/webm",+};++const extensionFromName = (name: string) => {+ const extension = name.split(".").at(-1)?.toLowerCase();+ return extension && extension !== name.toLowerCase() ? extension : null;+};++export const contentTypeFromName = (name: string) =>+ videoContentTypesByExtension[extensionFromName(name) ?? ""] ?? "video/mp4";++export const contentTypeForUpload = (+ name: string,+ contentType?: string | null,+) => {+ if (contentType?.startsWith("video/")) return contentType;+ return contentTypeFromName(name);+};diff --git a/apps/mobile/src/uploads/runMobileUpload.test.ts b/apps/mobile/src/uploads/runMobileUpload.test.tsnew file mode 100644index 000000000..3b664f133--- /dev/null+++ b/apps/mobile/src/uploads/runMobileUpload.test.ts@@ -0,0 +1,173 @@+import { Folder, Organisation, Video } from "@cap/web-domain";+import { describe, expect, it, vi } from "vitest";+import type { MobileApiClient, UploadFile } from "@/api/mobile";+import { runMobileUpload } from "./runMobileUpload";++const uploadMock = vi.hoisted(() => ({+ uploadToTarget: vi.fn(+ async (+ _target: unknown,+ _file: UploadFile,+ onProgress?: (progress: { loaded: number; total: number }) => void,+ ) => {+ onProgress?.({ loaded: 40, total: 80 });+ },+ ),+}));++vi.mock("@/api/mobile", () => ({+ uploadToTarget: uploadMock.uploadToTarget,+}));++describe("runMobileUpload", () => {+ it("passes native video metadata through upload creation and retry-safe progress", async () => {+ const createUpload = vi.fn(async () => ({+ id: Video.VideoId.make("video_123"),+ shareUrl: "https://cap.so/s/video_123",+ rawFileKey: "user_123/video_123/raw-upload.mov",+ upload: {+ type: "put" as const,+ url: "https://uploads.example/video",+ headers: {+ "Content-Type": "video/quicktime",+ },+ },+ cap: {+ id: Video.VideoId.make("video_123"),+ shareUrl: "https://cap.so/s/video_123",+ title: "video",+ createdAt: "2026-05-18T10:00:00.000Z",+ updatedAt: "2026-05-18T10:00:00.000Z",+ ownerName: "Richie",+ durationSeconds: 12.5,+ thumbnailUrl: null,+ folderId: null,+ public: true,+ protected: false,+ viewCount: 0,+ commentCount: 0,+ reactionCount: 0,+ upload: null,+ },+ }));+ const updateUploadProgress = vi.fn(async () => ({+ success: true as const,+ }));+ const completeUpload = vi.fn(async () => ({ success: true as const }));+ const client = {+ createUpload,+ updateUploadProgress,+ completeUpload,+ } as unknown as MobileApiClient;+ const file: UploadFile = {+ uri: "file:///tmp/video.mov",+ name: "video.mov",+ type: "video/quicktime",+ size: 80,+ durationSeconds: 12.5,+ width: 1920,+ height: 1080,+ };+ const onProgress = vi.fn();++ await runMobileUpload({+ client,+ file,+ organizationId: Organisation.OrganisationId.make("org_123"),+ folderId: Folder.FolderId.make("folder_123"),+ onProgress,+ });++ expect(createUpload).toHaveBeenCalledWith({+ organizationId: "org_123",+ folderId: "folder_123",+ fileName: "video.mov",+ contentType: "video/quicktime",+ contentLength: 80,+ durationSeconds: 12.5,+ width: 1920,+ height: 1080,+ });+ expect(updateUploadProgress).toHaveBeenCalledWith("video_123", {+ uploaded: 40,+ total: 80,+ });+ expect(completeUpload).toHaveBeenCalledWith("video_123", {+ rawFileKey: "user_123/video_123/raw-upload.mov",+ contentLength: 80,+ });+ expect(onProgress).toHaveBeenCalledWith(0.5);+ });++ it("normalizes non-finite native upload progress", async () => {+ uploadMock.uploadToTarget.mockImplementationOnce(+ async (+ _target: unknown,+ _file: UploadFile,+ onProgress?: (progress: { loaded: number; total: number }) => void,+ ) => {+ onProgress?.({ loaded: Number.NaN, total: Number.NaN });+ },+ );+ const createUpload = vi.fn(async () => ({+ id: Video.VideoId.make("video_123"),+ shareUrl: "https://cap.so/s/video_123",+ rawFileKey: "user_123/video_123/raw-upload.mov",+ upload: {+ type: "put" as const,+ url: "https://uploads.example/video",+ headers: {+ "Content-Type": "video/quicktime",+ },+ },+ cap: {+ id: Video.VideoId.make("video_123"),+ shareUrl: "https://cap.so/s/video_123",+ title: "video",+ createdAt: "2026-05-18T10:00:00.000Z",+ updatedAt: "2026-05-18T10:00:00.000Z",+ ownerName: "Richie",+ durationSeconds: 12.5,+ thumbnailUrl: null,+ folderId: null,+ public: true,+ protected: false,+ viewCount: 0,+ commentCount: 0,+ reactionCount: 0,+ upload: null,+ },+ }));+ const updateUploadProgress = vi.fn(async () => ({+ success: true as const,+ }));+ const completeUpload = vi.fn(async () => ({ success: true as const }));+ const client = {+ createUpload,+ updateUploadProgress,+ completeUpload,+ } as unknown as MobileApiClient;+ const file: UploadFile = {+ uri: "file:///tmp/video.mov",+ name: "video.mov",+ type: "video/quicktime",+ size: 80,+ durationSeconds: 12.5,+ width: 1920,+ height: 1080,+ };+ const onProgress = vi.fn();++ await runMobileUpload({+ client,+ file,+ onProgress,+ });++ expect(updateUploadProgress).toHaveBeenCalledWith("video_123", {+ uploaded: 0,+ total: 80,+ });+ expect(onProgress).toHaveBeenCalledWith(0);+ });+});diff --git a/apps/mobile/src/uploads/runMobileUpload.ts b/apps/mobile/src/uploads/runMobileUpload.tsnew file mode 100644index 000000000..a295bc388--- /dev/null+++ b/apps/mobile/src/uploads/runMobileUpload.ts@@ -0,0 +1,71 @@+import { Folder, Organisation } from "@cap/web-domain";+import type { MobileApiClient, UploadFile } from "@/api/mobile";+import { uploadToTarget } from "@/api/mobile";++type RunMobileUploadInput = {+ client: MobileApiClient;+ file: UploadFile;+ organizationId?: string | null;+ folderId?: string | null;+ onCreated?: (capId: string, rawFileKey: string) => void;+ onProgress?: (progress: number) => void;+};++const nonNegativeFiniteNumber = (value: number | null | undefined) =>+ typeof value === "number" && Number.isFinite(value) ? Math.max(0, value) : 0;++const positiveFiniteNumber = (value: number | null | undefined) =>+ typeof value === "number" && Number.isFinite(value) && value > 0+ ? value+ : null;++const clampProgress = (progress: number) => {+ const safeProgress = Number.isFinite(progress) ? progress : 0;+ return Math.min(1, Math.max(0, safeProgress));+};++export const runMobileUpload = async ({+ client,+ file,+ organizationId,+ folderId,+ onCreated,+ onProgress,+}: RunMobileUploadInput) => {+ const created = await client.createUpload({+ organizationId: organizationId+ ? Organisation.OrganisationId.make(organizationId)+ : undefined,+ folderId: folderId ? Folder.FolderId.make(folderId) : undefined,+ fileName: file.name,+ contentType: file.type,+ contentLength: file.size,+ durationSeconds: file.durationSeconds,+ width: file.width,+ height: file.height,+ });+ onCreated?.(created.id, created.rawFileKey);++ await uploadToTarget(created.upload, file, ({ loaded, total }) => {+ const safeLoaded = nonNegativeFiniteNumber(loaded);+ const safeTotal =+ positiveFiniteNumber(total) ??+ positiveFiniteNumber(file.size) ??+ safeLoaded;+ const progress = safeTotal > 0 ? safeLoaded / safeTotal : 0;+ onProgress?.(clampProgress(progress));+ client+ .updateUploadProgress(created.id, {+ uploaded: safeLoaded,+ total: safeTotal,+ })+ .catch(() => {});+ });++ await client.completeUpload(created.id, {+ rawFileKey: created.rawFileKey,+ contentLength: file.size,+ });++ return created;+};diff --git a/apps/mobile/src/uploads/uploadQueue.test.ts b/apps/mobile/src/uploads/uploadQueue.test.tsnew file mode 100644index 000000000..aa446cad2--- /dev/null+++ b/apps/mobile/src/uploads/uploadQueue.test.ts@@ -0,0 +1,318 @@+import { describe, expect, it } from "vitest";+import {+ emptyUploadQueue,+ isTerminalUploadQueueAction,+ uploadProgressPercent,+ uploadQueueActionFromCapUpload,+ uploadQueueReducer,+ uploadQueueStatusText,+} from "./uploadQueue";++const item = {+ id: "local-1",+ localUri: "file:///tmp/video.mp4",+ fileName: "video.mp4",+ contentType: "video/mp4",+ size: 100,+ folderId: null,+ organizationId: "org_123",+ status: "queued" as const,+ progress: 0,+ error: null,+ capId: null,+ rawFileKey: null,+ processingMessage: null,+};++describe("uploadQueueReducer", () => {+ it("preserves failed uploads for retry", () => {+ const queued = uploadQueueReducer(emptyUploadQueue, {+ type: "enqueue",+ item,+ });+ const failed = uploadQueueReducer(queued, {+ type: "fail",+ id: item.id,+ error: "Network unavailable",+ });+ expect(failed.items[0]?.status).toBe("failed");+ expect(failed.items[0]?.error).toBe("Network unavailable");++ const retrying = uploadQueueReducer(failed, {+ type: "retry",+ id: item.id,+ });+ expect(retrying.items[0]?.status).toBe("queued");+ expect(retrying.items[0]?.error).toBeNull();+ expect(retrying.items[0]?.localUri).toBe(item.localUri);+ });++ it("clears stale server upload metadata before retrying", () => {+ const queued = uploadQueueReducer(emptyUploadQueue, {+ type: "enqueue",+ item,+ });+ const uploading = uploadQueueReducer(queued, {+ type: "start",+ id: item.id,+ capId: "cap_123",+ rawFileKey: "raw/video.mp4",+ });+ const failed = uploadQueueReducer(uploading, {+ type: "fail",+ id: item.id,+ error: "Upload target rejected the file",+ });+ const retrying = uploadQueueReducer(failed, {+ type: "retry",+ id: item.id,+ });++ expect(retrying.items[0]?.capId).toBeNull();+ expect(retrying.items[0]?.rawFileKey).toBeNull();+ });++ it("keeps the created Cap id after upload completion", () => {+ const queued = uploadQueueReducer(emptyUploadQueue, {+ type: "enqueue",+ item,+ });+ const uploading = uploadQueueReducer(queued, {+ type: "start",+ id: item.id,+ capId: "cap_123",+ rawFileKey: "raw/video.mp4",+ });+ const complete = uploadQueueReducer(uploading, {+ type: "complete",+ id: item.id,+ });++ expect(complete.items[0]).toMatchObject({+ status: "complete",+ capId: "cap_123",+ rawFileKey: "raw/video.mp4",+ });+ });++ it("uses the web finishing label while processing after upload", () => {+ const queued = uploadQueueReducer(emptyUploadQueue, {+ type: "enqueue",+ item,+ });+ const uploading = uploadQueueReducer(queued, {+ type: "start",+ id: item.id,+ capId: "cap_123",+ rawFileKey: "raw/video.mp4",+ });+ const processing = uploadQueueReducer(uploading, {+ type: "processing",+ id: item.id,+ progress: 0,+ });++ expect(processing.items[0]).toMatchObject({+ status: "processing",+ progress: 0,+ capId: "cap_123",+ rawFileKey: "raw/video.mp4",+ });+ expect(+ processing.items[0] ? uploadQueueStatusText(processing.items[0]) : null,+ ).toBe("Finishing up");+ });++ it("uses server processing progress and messages in the queue row", () => {+ const queued = uploadQueueReducer(emptyUploadQueue, {+ type: "enqueue",+ item,+ });+ const processing = uploadQueueReducer(queued, {+ type: "processing",+ id: item.id,+ progress: 0.42,+ message: "Processing frames",+ });++ expect(processing.items[0]).toMatchObject({+ status: "processing",+ progress: 0.42,+ processingMessage: "Processing frames",+ });+ expect(+ processing.items[0] ? uploadQueueStatusText(processing.items[0]) : null,+ ).toBe("Processing frames");+ });++ it("restores uploading status when progress arrives after processing", () => {+ const queued = uploadQueueReducer(emptyUploadQueue, {+ type: "enqueue",+ item,+ });+ const processing = uploadQueueReducer(queued, {+ type: "processing",+ id: item.id,+ progress: 0.25,+ message: "Processing frames",+ });+ const uploading = uploadQueueReducer(processing, {+ type: "progress",+ id: item.id,+ progress: 0.5,+ });++ expect(uploading.items[0]).toMatchObject({+ status: "uploading",+ progress: 0.5,+ error: null,+ processingMessage: null,+ });+ expect(+ uploading.items[0] ? uploadQueueStatusText(uploading.items[0]) : null,+ ).toBe("Uploading 50%");+ });++ it("keeps invalid queue progress display-safe", () => {+ const queued = uploadQueueReducer(emptyUploadQueue, {+ type: "enqueue",+ item,+ });+ const invalidUploadProgress = uploadQueueReducer(queued, {+ type: "progress",+ id: item.id,+ progress: Number.NaN,+ });+ const invalidProcessingProgress = uploadQueueReducer(queued, {+ type: "processing",+ id: item.id,+ progress: Number.POSITIVE_INFINITY,+ message: "Processing frames",+ });++ expect(invalidUploadProgress.items[0]).toMatchObject({+ status: "uploading",+ progress: 0,+ });+ expect(+ invalidUploadProgress.items[0]+ ? uploadQueueStatusText(invalidUploadProgress.items[0])+ : null,+ ).toBe("Uploading 0%");+ expect(invalidProcessingProgress.items[0]).toMatchObject({+ status: "processing",+ progress: 0,+ });+ expect(uploadProgressPercent(Number.NaN)).toBe(0);+ expect(uploadProgressPercent(Number.POSITIVE_INFINITY)).toBe(0);+ });++ it("maps settled server upload state back to local queue actions", () => {+ expect(uploadQueueActionFromCapUpload(item.id, null)).toEqual({+ type: "complete",+ id: item.id,+ });+ expect(+ uploadQueueActionFromCapUpload(item.id, {+ uploaded: 100,+ total: 100,+ phase: "complete",+ processingProgress: 100,+ processingMessage: null,+ processingError: null,+ }),+ ).toEqual({+ type: "complete",+ id: item.id,+ });+ expect(+ uploadQueueActionFromCapUpload(item.id, {+ uploaded: 100,+ total: 100,+ phase: "error",+ processingProgress: 40,+ processingMessage: null,+ processingError: "Transcode failed",+ }),+ ).toEqual({+ type: "fail",+ id: item.id,+ error: "Transcode failed",+ });+ });++ it("maps active server upload state back to local queue progress", () => {+ expect(+ uploadQueueActionFromCapUpload(item.id, {+ uploaded: 25,+ total: 100,+ phase: "uploading",+ processingProgress: 0,+ processingMessage: null,+ processingError: null,+ }),+ ).toEqual({+ type: "progress",+ id: item.id,+ progress: 0.25,+ });+ expect(+ uploadQueueActionFromCapUpload(item.id, {+ uploaded: 100,+ total: 100,+ phase: "processing",+ processingProgress: 42,+ processingMessage: "Processing frames",+ processingError: null,+ }),+ ).toEqual({+ type: "processing",+ id: item.id,+ progress: 0.42,+ message: "Processing frames",+ });+ expect(+ uploadQueueActionFromCapUpload(item.id, {+ uploaded: 100,+ total: 100,+ phase: "generating_thumbnail",+ processingProgress: 88,+ processingMessage: null,+ processingError: null,+ }),+ ).toEqual({+ type: "processing",+ id: item.id,+ progress: 0.88,+ message: "Finishing up",+ });+ });++ it("keeps polling for non-terminal upload queue actions", () => {+ expect(isTerminalUploadQueueAction({ type: "complete", id: item.id })).toBe(+ true,+ );+ expect(+ isTerminalUploadQueueAction({+ type: "fail",+ id: item.id,+ error: "Transcode failed",+ }),+ ).toBe(true);+ expect(+ isTerminalUploadQueueAction({+ type: "progress",+ id: item.id,+ progress: 0.25,+ }),+ ).toBe(false);+ expect(+ isTerminalUploadQueueAction({+ type: "processing",+ id: item.id,+ progress: 0.42,+ message: "Processing frames",+ }),+ ).toBe(false);+ });+});diff --git a/apps/mobile/src/uploads/uploadQueue.ts b/apps/mobile/src/uploads/uploadQueue.tsnew file mode 100644index 000000000..5a3162f75--- /dev/null+++ b/apps/mobile/src/uploads/uploadQueue.ts@@ -0,0 +1,201 @@+import type { MobileCapSummary } from "@/api/mobile";++export type UploadQueueStatus =+ | "queued"+ | "uploading"+ | "processing"+ | "failed"+ | "complete";++export type UploadQueueItem = {+ id: string;+ localUri: string;+ fileName: string;+ contentType: string;+ size: number;+ durationSeconds?: number;+ width?: number;+ height?: number;+ folderId: string | null;+ organizationId: string | null;+ status: UploadQueueStatus;+ progress: number;+ error: string | null;+ capId: string | null;+ rawFileKey: string | null;+ processingMessage: string | null;+ createdAt: string;+ updatedAt: string;+};++export type UploadQueueAction =+ | { type: "enqueue"; item: Omit<UploadQueueItem, "createdAt" | "updatedAt"> }+ | { type: "start"; id: string; capId: string; rawFileKey: string }+ | { type: "progress"; id: string; progress: number }+ | {+ type: "processing";+ id: string;+ progress?: number;+ message?: string | null;+ }+ | { type: "complete"; id: string }+ | { type: "fail"; id: string; error: string }+ | { type: "remove"; id: string }+ | { type: "retry"; id: string };++export type UploadQueueState = {+ items: UploadQueueItem[];+};++const clampProgress = (progress: number) => {+ if (!Number.isFinite(progress)) return 0;+ return Math.min(1, Math.max(0, progress));+};++export const uploadProgressPercent = (progress: number) =>+ Math.round(clampProgress(progress) * 100);++export const isTerminalUploadQueueAction = (action: UploadQueueAction) =>+ action.type === "complete" || action.type === "fail";++export const uploadQueueStatusText = (item: UploadQueueItem) => {+ switch (item.status) {+ case "queued":+ return "Queued";+ case "uploading":+ return `Uploading ${uploadProgressPercent(item.progress)}%`;+ case "processing":+ return item.processingMessage ?? "Finishing up";+ case "complete":+ return "Ready to view";+ case "failed":+ return "Upload failed";+ }+};++export const uploadQueueActionFromCapUpload = (+ id: string,+ upload: MobileCapSummary["upload"],+): UploadQueueAction | null => {+ if (!upload || upload.phase === "complete") return { type: "complete", id };+ if (upload.phase === "error") {+ return {+ type: "fail",+ id,+ error: upload.processingError ?? "Processing failed",+ };+ }+ if (upload.phase === "uploading") {+ return {+ type: "progress",+ id,+ progress: upload.total > 0 ? upload.uploaded / upload.total : 0,+ };+ }+ return {+ type: "processing",+ id,+ progress: upload.processingProgress / 100,+ message:+ upload.processingMessage ??+ (upload.phase === "processing" ? "Processing" : "Finishing up"),+ };+};++const nowIso = () => new Date().toISOString();++const updateItem = (+ state: UploadQueueState,+ id: string,+ update: (item: UploadQueueItem) => UploadQueueItem,+): UploadQueueState => ({+ items: state.items.map((item) => (item.id === id ? update(item) : item)),+});++export const emptyUploadQueue: UploadQueueState = {+ items: [],+};++export const uploadQueueReducer = (+ state: UploadQueueState,+ action: UploadQueueAction,+): UploadQueueState => {+ const updatedAt = nowIso();++ switch (action.type) {+ case "enqueue":+ return {+ items: [+ ...state.items,+ {+ ...action.item,+ createdAt: updatedAt,+ updatedAt,+ },+ ],+ };+ case "start":+ return updateItem(state, action.id, (item) => ({+ ...item,+ status: "uploading",+ progress: 0,+ error: null,+ capId: action.capId,+ rawFileKey: action.rawFileKey,+ processingMessage: null,+ updatedAt,+ }));+ case "progress":+ return updateItem(state, action.id, (item) => ({+ ...item,+ status: "uploading",+ progress: clampProgress(action.progress),+ error: null,+ processingMessage: null,+ updatedAt,+ }));+ case "processing":+ return updateItem(state, action.id, (item) => ({+ ...item,+ status: "processing",+ progress:+ action.progress !== undefined+ ? clampProgress(action.progress)+ : item.progress,+ processingMessage: action.message ?? null,+ updatedAt,+ }));+ case "complete":+ return updateItem(state, action.id, (item) => ({+ ...item,+ status: "complete",+ progress: 1,+ error: null,+ processingMessage: null,+ updatedAt,+ }));+ case "fail":+ return updateItem(state, action.id, (item) => ({+ ...item,+ status: "failed",+ error: action.error,+ processingMessage: null,+ updatedAt,+ }));+ case "remove":+ return {+ items: state.items.filter((item) => item.id !== action.id),+ };+ case "retry":+ return updateItem(state, action.id, (item) => ({+ ...item,+ status: "queued",+ progress: 0,+ error: null,+ capId: null,+ rawFileKey: null,+ processingMessage: null,+ updatedAt,+ }));+ }+};