Open source Loom alternative. Beautiful, shareable screen recordings.
Rust appcapcossloommacnextjsnextjs15open-sourceossreactrecordrustscreen-capturescreen-recorderscreenshotsolidjstauritauri-apptypescriptvite
feat(mobile): extend recording upload queue and provider
Richie McIlroydf81b8b0eee1
diff --git a/apps/mobile/src/uploads/recording-upload-provider.tsx b/apps/mobile/src/uploads/recording-upload-provider.tsxindex 01756f1ad..a2f10f569 100644--- a/apps/mobile/src/uploads/recording-upload-provider.tsx+++ b/apps/mobile/src/uploads/recording-upload-provider.tsx@@ -5,6 +5,7 @@ import {useCallback,useContext,useEffect,+ useMemo,useRef,useState,} from "react";@@ -12,10 +13,15 @@ import { AppState } from "react-native";import { uploadToTarget } from "@/api/mobile";import { useAuth } from "@/auth/AuthContext";import type { CapRecorderSegmentEvent } from "../../modules/cap-recorder";+import {+ cancelScreenRecording,+ getScreenRecordingUpdates,+} from "../../modules/cap-screen-recorder";import {emptyRecordingUploadQueue,hydrateRecordingUploadQueue,type RecordingUploadJob,+ type RecordingUploadOwner,type RecordingUploadQueue,type RecordingUploadQueueAction,recordingUploadQueueReducer,@@ -25,17 +31,21 @@ const persistedQueueUri = FileSystem.documentDirectory? `${FileSystem.documentDirectory}recording-upload-queue.json`: null;const completionDisplayDurationMs = 4000;+const externalReconcileIntervalMs = 750;const maximumRetryDelayMs = 30_000;+const progressReportIntervalMs = 1500;+const serverReconcileIntervalMs = 3000;+const segmentPersistDelayMs = 1000;type BeginRecordingInput = {fileName: string;width: number;height: number;fps: number;+ uploadOwner?: RecordingUploadOwner;};-type RecordingUploadContextValue = {- queue: RecordingUploadQueue;+type RecordingUploadActions = {beginRecording: (input: BeginRecordingInput) => Promise<{id: string;shareUrl: string;@@ -49,12 +59,26 @@ type RecordingUploadContextValue = {},) => void;discardRecording: (id: string) => Promise<void>;+ dismissRecording: (id: string) => void;failRecording: (id: string, error: string) => void;retryRecording: (id: string) => void;};-const RecordingUploadContext =- createContext<RecordingUploadContextValue | null>(null);+type RecordingUploadContextValue = RecordingUploadActions & {+ queue: RecordingUploadQueue;+ libraryRevision: number;+};++const RecordingUploadActionsContext =+ createContext<RecordingUploadActions | null>(null);+const RecordingUploadQueueContext = createContext<RecordingUploadQueue | null>(+ null,+);+const RecordingUploadDisplayQueueContext =+ createContext<RecordingUploadQueue | null>(null);+const RecordingUploadLibraryRevisionContext = createContext<number | null>(+ null,+);const segmentSubpath = (segment: RecordingUploadJob["segments"][number]) =>segment.type === "initialization"@@ -74,23 +98,134 @@ const errorMessage = (error: unknown) =>? error.message: "The recording upload was interrupted.";+const displayQueueFrom = (+ queue: RecordingUploadQueue,+ current: RecordingUploadQueue = emptyRecordingUploadQueue,+) => {+ const jobs = queue.jobs.filter(+ (job) => job.status !== "recording" || job.uploadOwner === "external",+ );+ if (+ jobs.length === current.jobs.length &&+ jobs.every((job, index) => job === current.jobs[index])+ ) {+ return current;+ }+ return { jobs };+};++const reconcileExternalRecordings = async (queue: RecordingUploadQueue) => {+ let nextQueue = queue;+ let libraryChanged = false;+ const cancelledIds: string[] = [];++ for (const job of queue.jobs) {+ if (job.uploadOwner !== "external") continue;+ try {+ const updates = await getScreenRecordingUpdates(job.id);+ if (updates.status === "uploaded") {+ nextQueue = recordingUploadQueueReducer(nextQueue, {+ type: "externalProcessing",+ id: job.id,+ durationSeconds: updates.durationSeconds,+ totalBytes: updates.totalBytes,+ });+ libraryChanged = true;+ continue;+ }+ if (updates.status === "uploading") {+ nextQueue = recordingUploadQueueReducer(nextQueue, {+ type: "externalProcessing",+ id: job.id,+ durationSeconds: updates.durationSeconds,+ totalBytes: updates.totalBytes,+ });+ continue;+ }+ if (updates.status === "finished") {+ for (const segment of updates.segments) {+ nextQueue = recordingUploadQueueReducer(nextQueue, {+ type: "segment",+ id: job.id,+ segment,+ });+ }+ nextQueue = recordingUploadQueueReducer(nextQueue, {+ type: "finish",+ id: job.id,+ durationSeconds: updates.durationSeconds ?? 0.1,+ totalBytes: updates.totalBytes,+ });+ continue;+ }+ if (updates.status === "cancelled") {+ nextQueue = recordingUploadQueueReducer(nextQueue, {+ type: "remove",+ id: job.id,+ });+ cancelledIds.push(job.id);+ libraryChanged = true;+ continue;+ }+ if (updates.status === "missing") {+ nextQueue = recordingUploadQueueReducer(nextQueue, {+ type: "fail",+ id: job.id,+ error: "The screen recording could not be recovered.",+ });+ continue;+ }+ if (+ updates.status === "failed" &&+ (job.status !== "failed" || job.error !== updates.error)+ ) {+ nextQueue = recordingUploadQueueReducer(nextQueue, {+ type: "fail",+ id: job.id,+ error: updates.error ?? "The screen recording stopped unexpectedly.",+ });+ }+ } catch {}+ }++ return { cancelledIds, libraryChanged, queue: nextQueue };+};+export function RecordingUploadProvider({ children }: { children: ReactNode }) {const auth = useAuth();+ const authStatus = auth.status;+ const authClient = auth.client;+ const activeOrganizationId = auth.bootstrap?.activeOrganizationId;+ const refreshAuth = auth.refresh;const [queue, setQueue] = useState(emptyRecordingUploadQueue);+ const [displayQueue, setDisplayQueue] = useState(emptyRecordingUploadQueue);+ const [libraryRevision, setLibraryRevision] = useState(0);const queueRef = useRef(queue);const processingJobs = useRef(new Set<string>());+ const progressReportTimes = useRef(new Map<string, number>());+ const progressReports = useRef(new Map<string, Promise<void>>());const removedJobs = useRef(new Set<string>());const persistence = useRef(Promise.resolve());const processJobRef = useRef<(id: string) => Promise<void>>(async () => {});const hydrationResolve = useRef<(() => void) | null>(null);+ const hydrationStarted = useRef(false);const hydration = useRef(new Promise<void>((resolve) => {hydrationResolve.current = resolve;}),);- const persist = useCallback((nextQueue: RecordingUploadQueue) => {- if (!persistedQueueUri) return;+ const pendingPersistQueue = useRef<RecordingUploadQueue | null>(null);+ const persistTimer = useRef<ReturnType<typeof setTimeout> | null>(null);++ const flushPersist = useCallback(() => {+ if (persistTimer.current) {+ clearTimeout(persistTimer.current);+ persistTimer.current = null;+ }+ const nextQueue = pendingPersistQueue.current;+ pendingPersistQueue.current = null;+ if (!nextQueue || !persistedQueueUri) return;persistence.current = persistence.current.catch(() => undefined).then(() =>@@ -102,12 +237,30 @@ export function RecordingUploadProvider({ children }: { children: ReactNode }) {.catch(() => undefined);}, []);+ const persist = useCallback(+ (nextQueue: RecordingUploadQueue, immediate: boolean) => {+ if (!persistedQueueUri) return;+ pendingPersistQueue.current = nextQueue;+ if (immediate) {+ flushPersist();+ return;+ }+ if (persistTimer.current) return;+ persistTimer.current = setTimeout(() => {+ persistTimer.current = null;+ flushPersist();+ }, segmentPersistDelayMs);+ },+ [flushPersist],+ );+const kick = useCallback(() => {queueMicrotask(() => {for (const job of queueRef.current.jobs) {if (- job.status !== "failed" &&- job.status !== "complete" &&+ job.uploadOwner === "app" &&+ (job.status === "recording" || job.status === "uploading") &&+ job.serverPhase === null &&!processingJobs.current.has(job.id)) {void processJobRef.current(job.id);@@ -118,16 +271,59 @@ export function RecordingUploadProvider({ children }: { children: ReactNode }) {const apply = useCallback((action: RecordingUploadQueueAction) => {- const nextQueue = recordingUploadQueueReducer(queueRef.current, action);+ const currentQueue = queueRef.current;+ const nextQueue = recordingUploadQueueReducer(currentQueue, action);+ if (nextQueue === currentQueue) return;+ if (action.type === "remove") {+ progressReportTimes.current.delete(action.id);+ progressReports.current.delete(action.id);+ }queueRef.current = nextQueue;setQueue(nextQueue);- persist(nextQueue);+ setDisplayQueue((current) => displayQueueFrom(nextQueue, current));+ persist(+ nextQueue,+ action.type !== "segment" && action.type !== "segmentUploaded",+ );kick();},[kick, persist],);+ const notifyLibraryChanged = useCallback(() => {+ setLibraryRevision((revision) => revision + 1);+ }, []);+ const externalRecordingIdsKey = useMemo(+ () =>+ queue.jobs+ .filter(+ (job) =>+ job.uploadOwner === "external" &&+ job.status !== "failed" &&+ job.status !== "complete",+ )+ .map((job) => job.id)+ .sort()+ .join(","),+ [queue.jobs],+ );+ const serverTrackedIdsKey = useMemo(+ () =>+ queue.jobs+ .filter(+ (job) =>+ job.status === "processing" ||+ job.serverPhase !== null ||+ (job.uploadOwner === "external" && job.status === "uploading"),+ )+ .map((job) => job.id)+ .sort()+ .join(","),+ [queue.jobs],+ );useEffect(() => {+ if (hydrationStarted.current) return;+ hydrationStarted.current = true;void (async () => {let restored = emptyRecordingUploadQueue;if (persistedQueueUri) {@@ -140,23 +336,239 @@ export function RecordingUploadProvider({ children }: { children: ReactNode }) {restored = emptyRecordingUploadQueue;}}+ const reconciliation = await reconcileExternalRecordings(restored);+ restored = reconciliation.queue;+ for (const id of reconciliation.cancelledIds) {+ removedJobs.current.add(id);+ void cancelScreenRecording(id).catch(() => undefined);+ if (authStatus === "signedIn") {+ void authClient.deleteCap(id).catch(() => undefined);+ }+ }queueRef.current = restored;setQueue(restored);+ setDisplayQueue(displayQueueFrom(restored));+ persist(restored, true);+ if (reconciliation.libraryChanged) {+ notifyLibraryChanged();+ void refreshAuth().catch(() => undefined);+ }hydrationResolve.current?.();hydrationResolve.current = null;kick();})();- }, [kick]);+ }, [+ authClient,+ authStatus,+ kick,+ notifyLibraryChanged,+ persist,+ refreshAuth,+ ]);++ useEffect(() => {+ if (externalRecordingIdsKey.length === 0) return;+ let cancelled = false;+ let inFlight = false;+ const reconcile = async () => {+ if (cancelled || inFlight) return;+ inFlight = true;+ try {+ const jobs = queueRef.current.jobs.filter(+ (job) =>+ job.uploadOwner === "external" &&+ job.status !== "failed" &&+ job.status !== "complete",+ );+ const results = await Promise.all(+ jobs.map(async (job) => {+ try {+ return {+ id: job.id,+ updates: await getScreenRecordingUpdates(job.id),+ };+ } catch {+ return null;+ }+ }),+ );+ if (cancelled) return;+ for (const result of results) {+ if (!result) continue;+ const job = queueRef.current.jobs.find(+ (candidate) => candidate.id === result.id,+ );+ if (!job || job.uploadOwner !== "external") continue;+ const updates = result.updates;+ if (!updates) continue;+ if (updates.status === "cancelled") {+ removedJobs.current.add(job.id);+ apply({ type: "remove", id: job.id });+ await Promise.all([+ authClient.deleteCap(job.id).catch(() => undefined),+ cancelScreenRecording(job.id).catch(() => undefined),+ ]);+ notifyLibraryChanged();+ continue;+ }+ if (updates.status === "missing") {+ apply({+ type: "fail",+ id: job.id,+ error: "The screen recording could not be recovered.",+ });+ continue;+ }+ if (updates.status === "uploading" || updates.status === "uploaded") {+ apply({+ type: "externalProcessing",+ id: job.id,+ durationSeconds: updates.durationSeconds,+ totalBytes: updates.totalBytes,+ });+ continue;+ }+ if (updates.status === "finished") {+ for (const segment of updates.segments) {+ apply({ type: "segment", id: job.id, segment });+ }+ apply({+ type: "finish",+ id: job.id,+ durationSeconds: updates.durationSeconds ?? 0.1,+ totalBytes: updates.totalBytes,+ });+ continue;+ }+ if (updates.status === "failed") {+ apply({+ type: "fail",+ id: job.id,+ error:+ updates.error ?? "The screen recording stopped unexpectedly.",+ });+ }+ }+ } finally {+ inFlight = false;+ }+ };+ void reconcile();+ const interval = setInterval(() => {+ void reconcile();+ }, externalReconcileIntervalMs);+ return () => {+ cancelled = true;+ clearInterval(interval);+ };+ }, [apply, authClient, externalRecordingIdsKey, notifyLibraryChanged]);++ useEffect(() => {+ if (authStatus !== "signedIn" || serverTrackedIdsKey.length === 0) return;+ const ids = serverTrackedIdsKey.split(",");+ let cancelled = false;+ let inFlight = false;+ const reconcile = async () => {+ if (cancelled || inFlight) return;+ inFlight = true;+ try {+ const response = await authClient.getCapStatuses(ids);+ if (cancelled) return;+ const statuses = new Map<+ string,+ (typeof response.caps)[number]["upload"]+ >(response.caps.map((cap) => [cap.id, cap.upload] as const));+ let libraryChanged = false;+ for (const id of ids) {+ const job = queueRef.current.jobs.find(+ (candidate) => candidate.id === id,+ );+ if (!job) continue;+ if (!statuses.has(id)) {+ removedJobs.current.add(id);+ apply({ type: "remove", id });+ if (job.uploadOwner === "external") {+ void cancelScreenRecording(id).catch(() => undefined);+ }+ continue;+ }+ const upload = statuses.get(id) ?? null;+ if (!upload || upload.phase === "complete") {+ apply({ type: "complete", id });+ if (job.uploadOwner === "external") {+ void cancelScreenRecording(id).catch(() => undefined);+ }+ setTimeout(+ () => apply({ type: "remove", id }),+ completionDisplayDurationMs,+ );+ libraryChanged = true;+ continue;+ }+ if (upload.phase === "error") {+ apply({+ type: "fail",+ id,+ error:+ upload.processingError ??+ upload.processingMessage ??+ "Cap could not finish processing this recording.",+ });+ libraryChanged = true;+ continue;+ }+ apply({+ type: "serverUpload",+ id,+ phase: upload.phase,+ uploaded: upload.uploaded,+ total: upload.total,+ progress: upload.processingProgress,+ message: upload.processingMessage,+ });+ }+ if (libraryChanged) {+ notifyLibraryChanged();+ void refreshAuth().catch(() => undefined);+ }+ } catch {+ } finally {+ inFlight = false;+ }+ };+ void reconcile();+ const interval = setInterval(() => {+ void reconcile();+ }, serverReconcileIntervalMs);+ return () => {+ cancelled = true;+ clearInterval(interval);+ };+ }, [+ apply,+ authClient,+ authStatus,+ notifyLibraryChanged,+ refreshAuth,+ serverTrackedIdsKey,+ ]);processJobRef.current = async (id: string) => {- if (auth.status !== "signedIn" || processingJobs.current.has(id)) return;+ if (authStatus !== "signedIn" || processingJobs.current.has(id)) return;processingJobs.current.add(id);try {while (!removedJobs.current.has(id)) {const job = queueRef.current.jobs.find((candidate) => candidate.id === id,);- if (!job || job.status === "failed" || job.status === "complete")+ if (+ !job ||+ job.uploadOwner !== "app" ||+ job.status === "failed" ||+ job.status === "complete" ||+ job.status === "processing" ||+ job.serverPhase !== null+ )return;const pendingSegments = job.segments.filter((segment) => !segment.uploaded,@@ -164,7 +576,7 @@ export function RecordingUploadProvider({ children }: { children: ReactNode }) {if (pendingSegments.length > 0) {const batch = pendingSegments.slice(0, 4);const subpaths = batch.map(segmentSubpath);- const { uploads } = await auth.client.createRecordingUploadTargets(+ const { uploads } = await authClient.createRecordingUploadTargets(job.id,subpaths,);@@ -188,6 +600,27 @@ export function RecordingUploadProvider({ children }: { children: ReactNode }) {});}),);+ const latestJob = queueRef.current.jobs.find(+ (candidate) => candidate.id === job.id,+ );+ const now = Date.now();+ const lastReport = progressReportTimes.current.get(job.id) ?? 0;+ if (latestJob && now - lastReport >= progressReportIntervalMs) {+ progressReportTimes.current.set(job.id, now);+ const previous =+ progressReports.current.get(job.id) ?? Promise.resolve();+ const report = previous+ .catch(() => undefined)+ .then(() =>+ authClient.updateUploadProgress(job.id, {+ uploaded: latestJob.uploadedBytes,+ total: latestJob.totalBytes,+ }),+ )+ .then(() => undefined)+ .catch(() => undefined);+ progressReports.current.set(job.id, report);+ }continue;}@@ -211,16 +644,16 @@ export function RecordingUploadProvider({ children }: { children: ReactNode }) {segment.track === "audio" && segment.type === "initialization",);if (!hasVideoInitialization || videoSegments.length === 0) {- throw new Error("The camera did not produce a playable recording.");+ throw new Error("The recording did not produce playable video.");}if (audioSegments.length > 0 && !hasAudioInitialization) {throw new Error(- "The microphone did not produce a playable recording.",+ "The recording did not produce playable microphone audio.",);}apply({ type: "processing", id: job.id });- await auth.client.completeRecording(job.id, {+ await authClient.completeRecording(job.id, {durationSeconds: job.durationSeconds,totalBytes: job.totalBytes,videoSegments: videoSegments.map((segment) => ({@@ -232,18 +665,14 @@ export function RecordingUploadProvider({ children }: { children: ReactNode }) {duration: segment.durationSeconds,})),});- await auth.refresh().catch(() => undefined);+ notifyLibraryChanged();+ await refreshAuth().catch(() => undefined);const directory = recordingDirectoryFromSegment(job.segments[0]);if (directory) {await FileSystem.deleteAsync(directory, { idempotent: true }).catch(() => undefined,);}- apply({ type: "complete", id: job.id });- setTimeout(- () => apply({ type: "remove", id: job.id }),- completionDisplayDurationMs,- );return;}} catch (error) {@@ -269,43 +698,95 @@ export function RecordingUploadProvider({ children }: { children: ReactNode }) {};useEffect(() => {- if (auth.status !== "signedIn") return;+ if (authStatus !== "signedIn") return;for (const job of queueRef.current.jobs) {- if (job.status === "failed" && job.durationSeconds !== null) {+ if (+ job.uploadOwner === "app" &&+ job.status === "failed" &&+ job.durationSeconds !== null+ ) {apply({ type: "retry", id: job.id });}}kick();- }, [apply, auth.status, kick]);+ }, [apply, authStatus, kick]);useEffect(() => {const subscription = AppState.addEventListener("change", (state) => {- if (state !== "active") return;+ if (state !== "active") {+ flushPersist();+ return;+ }for (const job of queueRef.current.jobs) {- if (job.status === "failed" && job.durationSeconds !== null) {+ if (+ job.uploadOwner === "app" &&+ job.status === "failed" &&+ job.durationSeconds !== null+ ) {apply({ type: "retry", id: job.id });}}kick();});return () => subscription.remove();- }, [apply, kick]);+ }, [apply, flushPersist, kick]);++ useEffect(() => {+ if (authStatus !== "signedOut") return;+ void (async () => {+ await hydration.current;+ const jobs = queueRef.current.jobs;+ if (persistTimer.current) {+ clearTimeout(persistTimer.current);+ persistTimer.current = null;+ }+ pendingPersistQueue.current = null;+ for (const job of jobs) {+ removedJobs.current.add(job.id);+ }+ queueRef.current = emptyRecordingUploadQueue;+ setQueue(emptyRecordingUploadQueue);+ setDisplayQueue(emptyRecordingUploadQueue);+ await Promise.all(+ jobs.map((job) => {+ const directory = recordingDirectoryFromSegment(job.segments[0]);+ return directory+ ? FileSystem.deleteAsync(directory, { idempotent: true }).catch(+ () => undefined,+ )+ : Promise.resolve();+ }),+ );+ if (persistedQueueUri) {+ await FileSystem.deleteAsync(persistedQueueUri, {+ idempotent: true,+ }).catch(() => undefined);+ }+ })();+ }, [authStatus]);const beginRecording = useCallback(async (input: BeginRecordingInput) => {await hydration.current;- if (auth.status !== "signedIn") {+ if (authStatus !== "signedIn") {throw new Error("Sign in before recording.");}- const created = await auth.client.createRecording({- ...input,- organizationId: auth.bootstrap?.activeOrganizationId ?? undefined,+ const { uploadOwner = "app", ...recordingInput } = input;+ const created = await authClient.createRecording({+ ...recordingInput,+ organizationId: activeOrganizationId ?? undefined,});removedJobs.current.delete(created.id);- apply({ type: "begin", id: created.id, shareUrl: created.shareUrl });+ apply({+ type: "begin",+ id: created.id,+ shareUrl: created.shareUrl,+ uploadOwner,+ });+ notifyLibraryChanged();return { id: created.id, shareUrl: created.shareUrl };},- [apply, auth],+ [activeOrganizationId, apply, authClient, authStatus, notifyLibraryChanged],);const addSegment = useCallback(@@ -345,8 +826,8 @@ export function RecordingUploadProvider({ children }: { children: ReactNode }) {apply({ type: "remove", id });const directory = recordingDirectoryFromSegment(job?.segments[0]);await Promise.all([- auth.status === "signedIn"- ? auth.client.deleteCap(id).catch(() => undefined)+ authStatus === "signedIn"+ ? authClient.deleteCap(id).catch(() => undefined): Promise.resolve(),directory? FileSystem.deleteAsync(directory, { idempotent: true }).catch(@@ -354,31 +835,99 @@ export function RecordingUploadProvider({ children }: { children: ReactNode }) {): Promise.resolve(),]);+ notifyLibraryChanged();+ },+ [apply, authClient, authStatus, notifyLibraryChanged],+ );++ const dismissRecording = useCallback(+ (id: string) => {+ removedJobs.current.add(id);+ apply({ type: "remove", id });},- [apply, auth],+ [apply],+ );++ const actions = useMemo<RecordingUploadActions>(+ () => ({+ beginRecording,+ addSegment,+ finishRecording,+ discardRecording,+ dismissRecording,+ failRecording,+ retryRecording,+ }),+ [+ beginRecording,+ addSegment,+ finishRecording,+ discardRecording,+ dismissRecording,+ failRecording,+ retryRecording,+ ],);return (- <RecordingUploadContext.Provider- value={{- queue,- beginRecording,- addSegment,- finishRecording,- discardRecording,- failRecording,- retryRecording,- }}- >- {children}- </RecordingUploadContext.Provider>+ <RecordingUploadActionsContext.Provider value={actions}>+ <RecordingUploadLibraryRevisionContext.Provider value={libraryRevision}>+ <RecordingUploadQueueContext.Provider value={queue}>+ <RecordingUploadDisplayQueueContext.Provider value={displayQueue}>+ {children}+ </RecordingUploadDisplayQueueContext.Provider>+ </RecordingUploadQueueContext.Provider>+ </RecordingUploadLibraryRevisionContext.Provider>+ </RecordingUploadActionsContext.Provider>);}-export const useRecordingUploads = () => {- const value = useContext(RecordingUploadContext);- if (!value) {- throw new Error("useRecordingUploads must be used within its provider.");+export const useRecordingUploadActions = () => {+ const actions = useContext(RecordingUploadActionsContext);+ if (!actions) {+ throw new Error(+ "useRecordingUploadActions must be used within its provider.",+ );}- return value;+ return actions;+};++export const useRecordingUploadQueue = () => {+ const queue = useContext(RecordingUploadQueueContext);+ if (!queue) {+ throw new Error(+ "useRecordingUploadQueue must be used within its provider.",+ );+ }+ return queue;+};++export const useRecordingUploadDisplayQueue = () => {+ const queue = useContext(RecordingUploadDisplayQueueContext);+ if (!queue) {+ throw new Error(+ "useRecordingUploadDisplayQueue must be used within its provider.",+ );+ }+ return queue;+};++export const useRecordingUploadLibraryRevision = () => {+ const revision = useContext(RecordingUploadLibraryRevisionContext);+ if (revision === null) {+ throw new Error(+ "useRecordingUploadLibraryRevision must be used within its provider.",+ );+ }+ return revision;+};++export const useRecordingUploads = (): RecordingUploadContextValue => {+ const actions = useRecordingUploadActions();+ const queue = useRecordingUploadQueue();+ const libraryRevision = useRecordingUploadLibraryRevision();+ return useMemo(+ () => ({ ...actions, queue, libraryRevision }),+ [actions, libraryRevision, queue],+ );};diff --git a/apps/mobile/src/uploads/recording-upload-queue.ts b/apps/mobile/src/uploads/recording-upload-queue.tsindex 411e8aedb..135f1b6a5 100644--- a/apps/mobile/src/uploads/recording-upload-queue.ts+++ b/apps/mobile/src/uploads/recording-upload-queue.ts@@ -5,6 +5,14 @@ export type RecordingUploadStatus =| "failed"| "complete";+export type RecordingUploadOwner = "app" | "external";++export type RecordingUploadServerPhase =+ | "uploading"+ | "processing"+ | "generating_thumbnail"+ | "complete";+export type RecordingUploadSegment = {track: "video" | "audio";type: "initialization" | "media";@@ -22,7 +30,12 @@ export type RecordingUploadJob = {status: RecordingUploadStatus;durationSeconds: number | null;totalBytes: number;+ uploadedBytes: number;segments: RecordingUploadSegment[];+ uploadOwner: RecordingUploadOwner;+ serverPhase: RecordingUploadServerPhase | null;+ processingProgress: number;+ processingMessage: string | null;error: string | null;retryCount: number;};@@ -32,7 +45,12 @@ export type RecordingUploadQueue = {};export type RecordingUploadQueueAction =- | { type: "begin"; id: string; shareUrl: string }+ | {+ type: "begin";+ id: string;+ shareUrl: string;+ uploadOwner?: RecordingUploadOwner;+ }| {type: "segment";id: string;@@ -46,7 +64,28 @@ export type RecordingUploadQueueAction =track: RecordingUploadSegment["track"];segmentType: RecordingUploadSegment["type"];}- | { type: "processing"; id: string }+ | {+ type: "processing";+ id: string;+ progress?: number;+ message?: string | null;+ serverPhase?: RecordingUploadServerPhase | null;+ }+ | {+ type: "externalProcessing";+ id: string;+ durationSeconds: number | null;+ totalBytes: number;+ }+ | {+ type: "serverUpload";+ id: string;+ phase: RecordingUploadServerPhase;+ uploaded: number;+ total: number;+ progress: number;+ message: string | null;+ }| { type: "complete"; id: string }| { type: "fail"; id: string; error: string }| { type: "retry"; id: string }@@ -58,9 +97,16 @@ const updateJob = (queue: RecordingUploadQueue,id: string,update: (job: RecordingUploadJob) => RecordingUploadJob,-): RecordingUploadQueue => ({- jobs: queue.jobs.map((job) => (job.id === id ? update(job) : job)),-});+): RecordingUploadQueue => {+ const index = queue.jobs.findIndex((job) => job.id === id);+ const current = queue.jobs[index];+ if (!current) return queue;+ const next = update(current);+ if (next === current) return queue;+ const jobs = [...queue.jobs];+ jobs[index] = next;+ return { jobs };+};export const recordingUploadQueueReducer = (queue: RecordingUploadQueue,@@ -78,7 +124,12 @@ export const recordingUploadQueueReducer = (status: "recording",durationSeconds: null,totalBytes: 0,+ uploadedBytes: 0,segments: [],+ uploadOwner: action.uploadOwner ?? "app",+ serverPhase: null,+ processingProgress: 0,+ processingMessage: null,error: null,retryCount: 0,},@@ -105,34 +156,118 @@ export const recordingUploadQueueReducer = (status: job.status === "failed" ? "failed" : "uploading",durationSeconds: action.durationSeconds,totalBytes: Math.max(job.totalBytes, action.totalBytes),+ uploadOwner: "app",+ serverPhase: null,+ processingProgress: 0,+ processingMessage: null,}));case "segmentUploaded":- return updateJob(queue, action.id, (job) => ({- ...job,- segments: job.segments.map((segment) =>- segment.track === action.track &&- segment.type === action.segmentType &&- segment.index === action.index- ? { ...segment, uploaded: true }- : segment,- ),- }));+ return updateJob(queue, action.id, (job) => {+ const segmentIndex = job.segments.findIndex(+ (segment) =>+ segment.track === action.track &&+ segment.type === action.segmentType &&+ segment.index === action.index,+ );+ const segment = job.segments[segmentIndex];+ if (!segment || segment.uploaded) return job;+ const segments = [...job.segments];+ segments[segmentIndex] = { ...segment, uploaded: true };+ return {+ ...job,+ uploadedBytes: job.uploadedBytes + segment.byteLength,+ segments,+ };+ });case "processing":- return updateJob(queue, action.id, (job) => ({- ...job,- status: "processing",- error: null,- }));+ return updateJob(queue, action.id, (job) => {+ const processingProgress = action.progress ?? job.processingProgress;+ const processingMessage =+ action.message === undefined ? job.processingMessage : action.message;+ const serverPhase =+ action.serverPhase === undefined+ ? job.serverPhase+ : action.serverPhase;+ if (+ job.status === "processing" &&+ job.processingProgress === processingProgress &&+ job.processingMessage === processingMessage &&+ job.serverPhase === serverPhase &&+ job.error === null+ ) {+ return job;+ }+ return {+ ...job,+ status: "processing",+ serverPhase,+ processingProgress,+ processingMessage,+ error: null,+ };+ });+ case "externalProcessing":+ return updateJob(queue, action.id, (job) => {+ if (job.status !== "recording" || job.uploadOwner !== "external") {+ return job;+ }+ return {+ ...job,+ status: "processing",+ durationSeconds: action.durationSeconds,+ totalBytes: Math.max(job.totalBytes, action.totalBytes),+ serverPhase: null,+ processingProgress: 0,+ processingMessage: "Finishing your recording",+ error: null,+ };+ });+ case "serverUpload":+ return updateJob(queue, action.id, (job) => {+ const status =+ action.phase === "uploading" ? "uploading" : "processing";+ const totalBytes = Math.max(0, action.total);+ const uploadedBytes = Math.min(+ totalBytes,+ Math.max(0, action.uploaded),+ );+ const processingProgress = Math.min(100, Math.max(0, action.progress));+ if (+ job.status === status &&+ job.serverPhase === action.phase &&+ job.totalBytes === totalBytes &&+ job.uploadedBytes === uploadedBytes &&+ job.processingProgress === processingProgress &&+ job.processingMessage === action.message &&+ job.error === null+ ) {+ return job;+ }+ return {+ ...job,+ status,+ totalBytes,+ uploadedBytes,+ serverPhase: action.phase,+ processingProgress,+ processingMessage: action.message,+ error: null,+ };+ });case "complete":return updateJob(queue, action.id, (job) => ({...job,status: "complete",+ serverPhase: null,+ processingProgress: 100,+ processingMessage: null,error: null,}));case "fail":return updateJob(queue, action.id, (job) => ({...job,status: "failed",+ serverPhase: null,error: action.error,retryCount: job.retryCount + 1,}));@@ -140,20 +275,25 @@ export const recordingUploadQueueReducer = (return updateJob(queue, action.id, (job) => ({...job,status: job.durationSeconds === null ? "recording" : "uploading",+ uploadOwner: "app",+ serverPhase: null,+ processingProgress: 0,+ processingMessage: null,error: null,}));- case "remove":- return { jobs: queue.jobs.filter((job) => job.id !== action.id) };+ case "remove": {+ const jobs = queue.jobs.filter((job) => job.id !== action.id);+ return jobs.length === queue.jobs.length ? queue : { jobs };+ }}};export const recordingUploadProgress = (job: RecordingUploadJob) => {+ if (job.status === "processing") {+ return Math.min(1, Math.max(0, job.processingProgress / 100));+ }if (job.totalBytes <= 0) return 0;- const uploadedBytes = job.segments.reduce(- (total, segment) => total + (segment.uploaded ? segment.byteLength : 0),- 0,- );- return Math.min(1, Math.max(0, uploadedBytes / job.totalBytes));+ return Math.min(1, Math.max(0, job.uploadedBytes / job.totalBytes));};const isRecord = (value: unknown): value is Record<string, unknown> =>@@ -215,11 +355,36 @@ const parseJob = (value: unknown): RecordingUploadJob | null => {const status: RecordingUploadStatus =storedStatus === "complete"? "complete"- : storedStatus === "failed" && durationSeconds === null- ? "failed"- : durationSeconds === null- ? "recording"- : "uploading";+ : storedStatus === "processing"+ ? "processing"+ : storedStatus === "failed" && durationSeconds === null+ ? "failed"+ : durationSeconds === null+ ? "recording"+ : "uploading";+ const uploadOwner: RecordingUploadOwner =+ value.uploadOwner === "app" || value.uploadOwner === "external"+ ? value.uploadOwner+ : parsedSegments.some((segment) =>+ segment.uri.includes("/CapScreenRecordings/"),+ )+ ? "external"+ : "app";+ const serverPhase: RecordingUploadServerPhase | null =+ value.serverPhase === "uploading" ||+ value.serverPhase === "processing" ||+ value.serverPhase === "generating_thumbnail" ||+ value.serverPhase === "complete"+ ? value.serverPhase+ : null;+ const segmentUploadedBytes = parsedSegments.reduce(+ (total, segment) => total + (segment.uploaded ? segment.byteLength : 0),+ 0,+ );+ const uploadedBytes =+ serverPhase !== null && typeof value.uploadedBytes === "number"+ ? Math.min(value.totalBytes, Math.max(0, value.uploadedBytes))+ : segmentUploadedBytes;return {id: value.id,@@ -228,7 +393,20 @@ const parseJob = (value: unknown): RecordingUploadJob | null => {status,durationSeconds,totalBytes: value.totalBytes,+ uploadedBytes,segments: parsedSegments,+ uploadOwner,+ serverPhase,+ processingProgress:+ typeof value.processingProgress === "number"+ ? Math.min(100, Math.max(0, value.processingProgress))+ : storedStatus === "complete"+ ? 100+ : 0,+ processingMessage:+ typeof value.processingMessage === "string"+ ? value.processingMessage+ : null,error: typeof value.error === "string" ? value.error : null,retryCount: value.retryCount,};diff --git a/apps/mobile/src/uploads/runMobileUpload.ts b/apps/mobile/src/uploads/runMobileUpload.tsindex ef1f066fe..882755167 100644--- a/apps/mobile/src/uploads/runMobileUpload.ts+++ b/apps/mobile/src/uploads/runMobileUpload.ts@@ -1,4 +1,3 @@-import { Folder, Organisation } from "@cap/web-domain";import type { MobileApiClient, UploadFile } from "@/api/mobile";import { uploadToTarget } from "@/api/mobile";@@ -13,6 +12,8 @@ type RunMobileUploadInput = {const uploadProgressSyncIntervalMs = 1000;const uploadProgressSyncMinDelta = 0.05;+const uploadProgressUiIntervalMs = 100;+const uploadProgressUiMinPercentDelta = 2;const nonNegativeFiniteNumber = (value: number | null | undefined) =>typeof value === "number" && Number.isFinite(value) ? Math.max(0, value) : 0;@@ -47,10 +48,8 @@ export const runMobileUpload = async ({onProgress,}: RunMobileUploadInput) => {const created = await client.createUpload({- organizationId: organizationId- ? Organisation.OrganisationId.make(organizationId)- : undefined,- folderId: folderId ? Folder.FolderId.make(folderId) : undefined,+ organizationId: organizationId ?? undefined,+ folderId: folderId ?? undefined,fileName: file.name,contentType: file.type,contentLength: file.size,@@ -62,6 +61,31 @@ export const runMobileUpload = async ({let lastSyncedProgress: number | null = null;let lastSyncedAt = 0;+ let lastUiPercent = -1;+ let lastUiAt = 0;+ let pendingProgress: { uploaded: number; total: number } | null = null;+ let progressSync: Promise<void> | null = null;+ const syncProgress = async (initial: { uploaded: number; total: number }) => {+ let next: { uploaded: number; total: number } | null = initial;+ while (next) {+ try {+ await client.updateUploadProgress(created.id, next);+ } catch {}+ next = pendingProgress;+ pendingProgress = null;+ }+ progressSync = null;+ };+ const enqueueProgressSync = (progress: {+ uploaded: number;+ total: number;+ }) => {+ if (progressSync) {+ pendingProgress = progress;+ return;+ }+ progressSync = syncProgress(progress);+ };await uploadToTarget(created.upload, file, ({ loaded, total }) => {const safeLoaded = nonNegativeFiniteNumber(loaded);@@ -71,8 +95,18 @@ export const runMobileUpload = async ({safeLoaded;const progress = safeTotal > 0 ? safeLoaded / safeTotal : 0;const clampedProgress = clampProgress(progress);- onProgress?.(clampedProgress);const now = Date.now();+ const uiPercent = Math.floor(clampedProgress * 100);+ if (+ lastUiPercent < 0 ||+ uiPercent >= 100 ||+ uiPercent - lastUiPercent >= uploadProgressUiMinPercentDelta ||+ now - lastUiAt >= uploadProgressUiIntervalMs+ ) {+ lastUiPercent = uiPercent;+ lastUiAt = now;+ onProgress?.(clampedProgress);+ }if (shouldSyncUploadProgress(clampedProgress,@@ -83,14 +117,10 @@ export const runMobileUpload = async ({) {lastSyncedProgress = clampedProgress;lastSyncedAt = now;- client- .updateUploadProgress(created.id, {- uploaded: safeLoaded,- total: safeTotal,- })- .catch(() => {});+ enqueueProgressSync({ uploaded: safeLoaded, total: safeTotal });}});+ await progressSync;await client.completeUpload(created.id, {rawFileKey: created.rawFileKey,