From c4422ebb95127cffe34bc275f8c04615428bfec8 Mon Sep 17 00:00:00 2001 From: Diego Mello Date: Wed, 18 Nov 2026 17:44:09 -0300 Subject: [PATCH 1/6] test: model-check the file upload lifecycle --- .../skills/verify-upload-lifecycle/SKILL.md | 73 ++++++++++++++++ .../skills/verify-upload-lifecycle/check.sh | 25 ++++++ .../model/upload-lifecycle.ts | 83 +++++++++++++++++++ .../model/upload-lifecycle.view.ts | 43 ++++++++++ .gitignore | 5 +- 5 files changed, 228 insertions(+), 1 deletion(-) create mode 100644 .claude/skills/verify-upload-lifecycle/SKILL.md create mode 100755 .claude/skills/verify-upload-lifecycle/check.sh create mode 100644 .claude/skills/verify-upload-lifecycle/model/upload-lifecycle.ts create mode 100644 .claude/skills/verify-upload-lifecycle/model/upload-lifecycle.view.ts diff --git a/.claude/skills/verify-upload-lifecycle/SKILL.md b/.claude/skills/verify-upload-lifecycle/SKILL.md new file mode 100644 index 00000000000..71d672ee260 --- /dev/null +++ b/.claude/skills/verify-upload-lifecycle/SKILL.md @@ -0,0 +1,73 @@ +--- +name: verify-upload-lifecycle +description: Model-check the file upload lifecycle (uploadQueue, createUploadRecord, persistUploadError, cancelUpload and the sendFileMessage callers) with tla-ts. Use before merging any change under app/lib/methods/sendFileMessage/, to UploadProgress retry/cancel, or to how the composer or share view call sendAttachments. +--- + +# Verify the upload lifecycle + +Sending a file in a Room goes through `sendFileMessage` (`app/lib/methods/sendFileMessage/index.ts`), which picks `sendFileMessage.ts` (servers below 6.10.0, here "v1") or `sendFileMessageV2.ts` ("v2"). Both share the in-memory `uploadQueue` and the WatermelonDB `uploads` row in `utils.ts`. A small model of that lifecycle lives in `model/upload-lifecycle.ts`, and TLC checks every order of its events. + +## The rules + +- `neverRefusedAfterUploadEnded`: once an upload of a file ends (sent, rejected by the server, cancelled), sending the same file again in the same Room is never refused as "Upload in progress". + Harm: the user can't send that photo to that Room again until they restart the app. +- `runningUploadNeverShownFailed`: an upload that is still running never shows as failed in the Room. + Harm: the progress row turns into a failed row with a retry button while the file is still uploading, and the refusal behind it is reported to Bugsnag as "Couldn't create upload record". + +## Does my change touch this? + +Yes, if it changes any line listed under Coverage, or who calls `sendFileMessage` / `sendAttachments`, or whether the caller passes `isForceTryAgain`. Then run the check and compare the model with the code. + +## Run it + +```sh +.claude/skills/verify-upload-lifecycle/check.sh +``` + +It runs `pnpm dlx tla-ts@0.0.10` on the model (about 1 s, a few dozen states) and exits 0 when every rule holds, 1 when a rule breaks (it names the rules), and 2 when the model does not compile. The compiled `UploadLifecycle.tla` and `.cfg` beside the model are regenerated on each run and are not committed. + +Read every result with `/statechart`, pointing it at `model/upload-lifecycle.ts`; it picks up `model/upload-lifecycle.view.ts` and turns each broken rule into its shortest path in plain words, or draws the chart when everything holds. + +## Real bug or modeling error? + +Replay the shortest path against the real code before believing either. Each model action is one code event: + +| Model action | Code | +| ---------------------- | ------------------------------------------------------------------------------------------------------------ | +| `userSendsFile(false)` | `sendAttachments` from `MessageComposer.tsx` or `ShareView`, or `RecordAudio.tsx`, into `createUploadRecord` | +| `userSendsFile(true)` | `UploadProgress.tsx` `tryAgain` (only offered on a failed row) | +| `preparingFails` | `Encryption.encryptFile` or `copyFileToCacheDirectoryIfNeeded` throws before the `FileUpload` is created | +| `uploadStarts` | `uploadQueue[uploadPath] = new FileUpload(...)` then `send()` | +| `serverAccepts` | `send()` (and `rooms.mediaConfirm` on v2) resolve; the row is destroyed | +| `serverRejects` | `send()` or `rooms.mediaConfirm` reject; the caller's `catch` runs | +| `userCancels` | `UploadProgress.tsx` `handleCancelUpload` → `cancelUpload` | +| `appRestarts` | process restart clears `uploadQueue`; `UploadProgress.uploadCheck` marks rows without a queue entry failed | + +Write the replay as a Jest test in `app/lib/methods/sendFileMessage/__tests__/` that drives the real `sendFileMessage`/`sendFileMessageV2` and `utils.ts` through the same steps (see `uploadLifecycle.test.ts` there). If the code does not do what the path says, the model is wrong: fix the model, not the rule. + +## When a change is intended + +Change the model action that mirrors the changed code, rerun, and replay any new path. Never weaken or delete a rule to get a pass; add a model variable when a rule needs one. + +## Scope and assumptions + +- One file in one Room; a second Room or a different file never shares a queue key (`${path}-${rid}`), so they are independent. +- One upload in flight at a time. A second send while the first is still being prepared and not refused would start a second upload of the same file; the model drops that step (`userSendsFile` returns) and does not check duplicate uploads. +- Cancel while the file is being prepared is left out (the row exists but `send()` has not started). +- Each `await` boundary that matters is one action; what happens inside `FileUpload` (progress events) is not modeled. + +## Coverage + +| Covered code | Model | +| --------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------- | +| `app/lib/methods/sendFileMessage/utils.ts`: `uploadQueue`, `isUploadActive`, `cancelUpload`, `persistUploadError`, `createUploadRecord` | `queued`, `record`, `isRefused`, `refuse`, `userCancels`, `persistUploadError` | +| `app/lib/methods/sendFileMessage/sendFileMessageV2.ts`: `sendFileMessageV2` | `api === "v2"` branches, `uploadStarts`, `serverAccepts`, `serverRejects`, `preparingFails` | +| `app/lib/methods/sendFileMessage/sendFileMessage.ts`: `sendFileMessage` | `api === "v1"` branches, same actions | +| `app/lib/methods/sendFileMessage/index.ts`: v1/v2 switch | `api` | +| `app/views/RoomView/components/UploadProgress.tsx`: `uploadCheck`, `tryAgain`, `handleCancelUpload` | `appRestarts`, `userSendsFile(true)`, `userCancels` | + +Sync commit: `776c0681c6b76c6ea3059ef6755265f32cada088`. The model describes the covered code as of this commit. Move it forward only after you have compared every covered function with its model action at the new commit. To see what changed since: + +```sh +git diff 776c0681c6b76c6ea3059ef6755265f32cada088 -- app/lib/methods/sendFileMessage app/views/RoomView/components/UploadProgress.tsx +``` diff --git a/.claude/skills/verify-upload-lifecycle/check.sh b/.claude/skills/verify-upload-lifecycle/check.sh new file mode 100755 index 00000000000..f866cd4d819 --- /dev/null +++ b/.claude/skills/verify-upload-lifecycle/check.sh @@ -0,0 +1,25 @@ +#!/usr/bin/env bash +set -euo pipefail + +model_dir="$(cd "$(dirname "$0")/model" && pwd)" +output="$(mktemp -t upload-lifecycle-tlc)" + +cd "$model_dir" +set +e +pnpm dlx tla-ts@0.0.10 upload-lifecycle.ts -continue -noGenerateSpecTE >"$output" 2>&1 +status=$? +set -e + +broken="$(grep -o 'Invariant [A-Za-z]* is violated' "$output" | sort -u || true)" +grep -E 'distinct states found' "$output" || true + +if [ -n "$broken" ]; then + echo "$broken" + echo "FAIL: full TLC output in $output" + exit 1 +fi +if [ "$status" -ne 0 ]; then + echo "ERROR: tla-ts exited $status without a rule violation (compile or model error); see $output" + exit 2 +fi +echo "PASS: every rule holds" diff --git a/.claude/skills/verify-upload-lifecycle/model/upload-lifecycle.ts b/.claude/skills/verify-upload-lifecycle/model/upload-lifecycle.ts new file mode 100644 index 00000000000..1fe323e0252 --- /dev/null +++ b/.claude/skills/verify-upload-lifecycle/model/upload-lifecycle.ts @@ -0,0 +1,83 @@ +type Api = 'v1' | 'v2'; +type UploadRecord = 'none' | 'uploading' | 'failed'; +type Attempt = 'none' | 'preparing' | 'sending'; + +let api!: Api; +let queued = false; +let record: UploadRecord = 'none'; +let attempt: Attempt = 'none'; +let refusedWithNothingInFlight = false; + +const persistUploadError = () => { + if (record !== 'none') { + record = 'failed'; + } +}; + +const isRefused = (force: boolean) => record !== 'none' && queued && !force; + +const refuse = () => { + if (attempt === 'none') { + refusedWithNothingInFlight = true; + } + if (api === 'v2') { + persistUploadError(); + } +}; + +export const userSendsFile = (force: boolean) => { + if (force && (record !== 'failed' || attempt !== 'none')) return; + if (isRefused(force)) { + refuse(); + return; + } + if (attempt !== 'none') return; + record = 'uploading'; + attempt = 'preparing'; +}; + +export const preparingFails = () => { + if (attempt !== 'preparing') return; + attempt = 'none'; + if (api === 'v1' && !queued) { + return; + } + persistUploadError(); +}; + +export const uploadStarts = () => { + if (attempt !== 'preparing') return; + queued = true; + attempt = 'sending'; +}; + +export const serverAccepts = () => { + if (attempt !== 'sending') return; + attempt = 'none'; + record = 'none'; +}; + +export const serverRejects = () => { + if (attempt !== 'sending') return; + attempt = 'none'; + persistUploadError(); +}; + +export const userCancels = () => { + if (record === 'none' || attempt === 'preparing') return; + queued = false; + record = 'none'; + attempt = 'none'; +}; + +export const appRestarts = () => { + queued = false; + attempt = 'none'; + persistUploadError(); +}; + +/** Once an upload of a file ends (sent, rejected, cancelled), sending that file again in the same Room is never refused as "Upload in progress". */ +export const neverRefusedAfterUploadEnded = () => !refusedWithNothingInFlight; + +/** An upload that is still running never shows as failed in the Room. */ +export const runningUploadNeverShownFailed = () => attempt === 'none' || record !== 'failed'; diff --git a/.claude/skills/verify-upload-lifecycle/model/upload-lifecycle.view.ts b/.claude/skills/verify-upload-lifecycle/model/upload-lifecycle.view.ts new file mode 100644 index 00000000000..2609e1a4df0 --- /dev/null +++ b/.claude/skills/verify-upload-lifecycle/model/upload-lifecycle.view.ts @@ -0,0 +1,43 @@ +type Vars = { + api: string; + queued: boolean; + record: string; + attempt: string; + refusedWithNothingInFlight: boolean; +}; + +export const title = 'Sending a file in a Room'; + +const rowLabel = (record: string) => + record === 'none' ? 'no upload row' : record === 'failed' ? 'failed upload row' : 'upload row in progress'; + +export const state = (v: Vars) => { + if (v.refusedWithNothingInFlight) { + return 'Refused: Upload in progress'; + } + if (v.attempt !== 'none') { + const phase = v.attempt === 'preparing' ? 'Preparing the file' : 'Uploading'; + return v.record === 'failed' ? `${phase}, shown as failed` : phase; + } + return `Idle, ${rowLabel(v.record)}${v.queued ? ', stale queue entry' : ''}`; +}; + +const labels: Record = { + userSendsFile: 'you send the file', + preparingFails: 'preparing the file fails', + uploadStarts: 'the upload starts', + serverAccepts: 'the server accepts it', + serverRejects: 'the server rejects it', + userCancels: 'you cancel the upload', + appRestarts: 'the app restarts' +}; + +export const step = (action: string, from: Vars, to: Vars) => { + if (action === 'userSendsFile' && from.attempt !== 'none') { + return 'you tap Send again [while it uploads]'; + } + if (action === 'userSendsFile' && from.record === 'failed' && !to.refusedWithNothingInFlight && to.attempt === 'preparing') { + return 'you send the file or tap retry'; + } + return labels[action] ?? action; +}; diff --git a/.gitignore b/.gitignore index 445b2f6dd34..9f4f0a4494e 100644 --- a/.gitignore +++ b/.gitignore @@ -86,7 +86,10 @@ e2e/e2e_account.ts *.p8 .worktrees/ .omc/ -.claude/ +.claude/* +!.claude/skills/ +.claude/skills/**/*.tla +.claude/skills/**/*.cfg .agents/ .cursor/ skills-lock.json From eb01f69d26d640cf45f0ce013ab19387d9cab9cf Mon Sep 17 00:00:00 2001 From: Diego Mello Date: Wed, 18 Nov 2026 18:01:05 -0300 Subject: [PATCH 2/6] fix: send a file again after its upload failed --- .../skills/verify-upload-lifecycle/SKILL.md | 23 ++- .../model/upload-lifecycle.ts | 10 +- .../__tests__/uploadLifecycle.test.ts | 173 ++++++++++++++++++ .../sendFileMessage/sendFileMessage.ts | 21 ++- .../sendFileMessage/sendFileMessageV2.ts | 25 ++- app/lib/methods/sendFileMessage/utils.ts | 9 + 6 files changed, 230 insertions(+), 31 deletions(-) create mode 100644 app/lib/methods/sendFileMessage/__tests__/uploadLifecycle.test.ts diff --git a/.claude/skills/verify-upload-lifecycle/SKILL.md b/.claude/skills/verify-upload-lifecycle/SKILL.md index 71d672ee260..faae004c8d2 100644 --- a/.claude/skills/verify-upload-lifecycle/SKILL.md +++ b/.claude/skills/verify-upload-lifecycle/SKILL.md @@ -5,14 +5,14 @@ description: Model-check the file upload lifecycle (uploadQueue, createUploadRec # Verify the upload lifecycle -Sending a file in a Room goes through `sendFileMessage` (`app/lib/methods/sendFileMessage/index.ts`), which picks `sendFileMessage.ts` (servers below 6.10.0, here "v1") or `sendFileMessageV2.ts` ("v2"). Both share the in-memory `uploadQueue` and the WatermelonDB `uploads` row in `utils.ts`. A small model of that lifecycle lives in `model/upload-lifecycle.ts`, and TLC checks every order of its events. +Sending a file in a Room goes through `sendFileMessage` (`app/lib/methods/sendFileMessage/index.ts`), which picks `sendFileMessage.ts` (servers below 6.10.0) or `sendFileMessageV2.ts`. Both share the in-memory `uploadQueue` and the WatermelonDB `uploads` row in `utils.ts`, and both handle the queue the same way, so one model covers them. If the two callers ever diverge, add a variable that picks the caller and branch on it. The model lives in `model/upload-lifecycle.ts`, and TLC checks every order of its events. ## The rules - `neverRefusedAfterUploadEnded`: once an upload of a file ends (sent, rejected by the server, cancelled), sending the same file again in the same Room is never refused as "Upload in progress". Harm: the user can't send that photo to that Room again until they restart the app. - `runningUploadNeverShownFailed`: an upload that is still running never shows as failed in the Room. - Harm: the progress row turns into a failed row with a retry button while the file is still uploading, and the refusal behind it is reported to Bugsnag as "Couldn't create upload record". + Harm: the progress row turns into a failed row with a retry button while the file is still uploading. ## Does my change touch this? @@ -37,9 +37,9 @@ Replay the shortest path against the real code before believing either. Each mod | `userSendsFile(false)` | `sendAttachments` from `MessageComposer.tsx` or `ShareView`, or `RecordAudio.tsx`, into `createUploadRecord` | | `userSendsFile(true)` | `UploadProgress.tsx` `tryAgain` (only offered on a failed row) | | `preparingFails` | `Encryption.encryptFile` or `copyFileToCacheDirectoryIfNeeded` throws before the `FileUpload` is created | -| `uploadStarts` | `uploadQueue[uploadPath] = new FileUpload(...)` then `send()` | -| `serverAccepts` | `send()` (and `rooms.mediaConfirm` on v2) resolve; the row is destroyed | -| `serverRejects` | `send()` or `rooms.mediaConfirm` reject; the caller's `catch` runs | +| `uploadStarts` | `uploadQueue[uploadPath] = upload` then `upload.send()` | +| `serverAccepts` | `send()` (and `rooms.mediaConfirm` on V2) resolve; the row is destroyed; `finally` runs `endUpload` | +| `serverRejects` | `send()` or `rooms.mediaConfirm` reject; `catch` persists the error; `finally` runs `endUpload` | | `userCancels` | `UploadProgress.tsx` `handleCancelUpload` → `cancelUpload` | | `appRestarts` | process restart clears `uploadQueue`; `UploadProgress.uploadCheck` marks rows without a queue entry failed | @@ -58,13 +58,12 @@ Change the model action that mirrors the changed code, rerun, and replay any new ## Coverage -| Covered code | Model | -| --------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------- | -| `app/lib/methods/sendFileMessage/utils.ts`: `uploadQueue`, `isUploadActive`, `cancelUpload`, `persistUploadError`, `createUploadRecord` | `queued`, `record`, `isRefused`, `refuse`, `userCancels`, `persistUploadError` | -| `app/lib/methods/sendFileMessage/sendFileMessageV2.ts`: `sendFileMessageV2` | `api === "v2"` branches, `uploadStarts`, `serverAccepts`, `serverRejects`, `preparingFails` | -| `app/lib/methods/sendFileMessage/sendFileMessage.ts`: `sendFileMessage` | `api === "v1"` branches, same actions | -| `app/lib/methods/sendFileMessage/index.ts`: v1/v2 switch | `api` | -| `app/views/RoomView/components/UploadProgress.tsx`: `uploadCheck`, `tryAgain`, `handleCancelUpload` | `appRestarts`, `userSendsFile(true)`, `userCancels` | +| Covered code | Model | +| ------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------- | +| `app/lib/methods/sendFileMessage/utils.ts`: `uploadQueue`, `isUploadActive`, `isUploadCancelled`, `endUpload`, `cancelUpload`, `persistUploadError`, `createUploadRecord` | `queued`, `record`, `isRefused`, `refuse`, `userCancels`, `persistUploadError` | +| `app/lib/methods/sendFileMessage/sendFileMessageV2.ts`: `sendFileMessageV2` | `userSendsFile`, `preparingFails`, `uploadStarts`, `serverAccepts`, `serverRejects` | +| `app/lib/methods/sendFileMessage/sendFileMessage.ts`: `sendFileMessage` | same actions | +| `app/views/RoomView/components/UploadProgress.tsx`: `uploadCheck`, `tryAgain`, `handleCancelUpload` | `appRestarts`, `userSendsFile(true)`, `userCancels` | Sync commit: `776c0681c6b76c6ea3059ef6755265f32cada088`. The model describes the covered code as of this commit. Move it forward only after you have compared every covered function with its model action at the new commit. To see what changed since: diff --git a/.claude/skills/verify-upload-lifecycle/model/upload-lifecycle.ts b/.claude/skills/verify-upload-lifecycle/model/upload-lifecycle.ts index 1fe323e0252..49f79822aed 100644 --- a/.claude/skills/verify-upload-lifecycle/model/upload-lifecycle.ts +++ b/.claude/skills/verify-upload-lifecycle/model/upload-lifecycle.ts @@ -1,8 +1,6 @@ -type Api = 'v1' | 'v2'; type UploadRecord = 'none' | 'uploading' | 'failed'; type Attempt = 'none' | 'preparing' | 'sending'; -let api!: Api; let queued = false; let record: UploadRecord = 'none'; let attempt: Attempt = 'none'; @@ -20,9 +18,6 @@ const refuse = () => { if (attempt === 'none') { refusedWithNothingInFlight = true; } - if (api === 'v2') { - persistUploadError(); - } }; export const userSendsFile = (force: boolean) => { @@ -39,9 +34,6 @@ export const userSendsFile = (force: boolean) => { export const preparingFails = () => { if (attempt !== 'preparing') return; attempt = 'none'; - if (api === 'v1' && !queued) { - return; - } persistUploadError(); }; @@ -54,12 +46,14 @@ export const uploadStarts = () => { export const serverAccepts = () => { if (attempt !== 'sending') return; attempt = 'none'; + queued = false; record = 'none'; }; export const serverRejects = () => { if (attempt !== 'sending') return; attempt = 'none'; + queued = false; persistUploadError(); }; diff --git a/app/lib/methods/sendFileMessage/__tests__/uploadLifecycle.test.ts b/app/lib/methods/sendFileMessage/__tests__/uploadLifecycle.test.ts new file mode 100644 index 00000000000..e43d6da6b07 --- /dev/null +++ b/app/lib/methods/sendFileMessage/__tests__/uploadLifecycle.test.ts @@ -0,0 +1,173 @@ +import { Alert } from 'react-native'; + +import { sendFileMessage } from '../sendFileMessage'; +import { sendFileMessageV2 } from '../sendFileMessageV2'; +import { cancelUpload, getUploadPath, isUploadActive, uploadQueue } from '../utils'; + +type UploadRow = { + id: string; + path: string; + error: boolean; + progress: number; + update: (change: (row: UploadRow) => void) => Promise; + destroyPermanently: () => Promise; +}; + +type PendingSend = { resolve: (response: unknown) => void; reject: (error: unknown) => void }; + +const mockRows = new Map(); +const mockSends: PendingSend[] = []; + +jest.mock('react-native', () => ({ Alert: { alert: jest.fn() } })); +jest.mock('~/i18n', () => ({ __esModule: true, default: { t: (key: string) => key } })); +jest.mock('../../helpers/log', () => ({ __esModule: true, default: jest.fn() })); +jest.mock('../../helpers/fetch', () => ({ __esModule: true, default: jest.fn(() => Promise.resolve({})) })); +jest.mock('~/lib/database/services/Upload', () => ({ + getUploadByPath: (id: string) => Promise.resolve(mockRows.get(id) ?? null) +})); +jest.mock('@nozbe/watermelondb/RawRecord', () => ({ sanitizedRaw: (raw: unknown) => raw })); +jest.mock('expo-file-system/legacy', () => ({ cacheDirectory: 'file://cache/', copyAsync: jest.fn(() => Promise.resolve()) })); +jest.mock('~/lib/encryption', () => ({ + Encryption: { + encryptFile: jest.fn((_rid: string, file: unknown) => + Promise.resolve({ file, getContent: undefined, fileContent: undefined }) + ) + } +})); +jest.mock('../../helpers/fileUpload', () => ({ + __esModule: true, + default: class { + private pending?: PendingSend; + + send() { + return new Promise((resolve, reject) => { + this.pending = { resolve, reject }; + mockSends.push(this.pending); + }); + } + + cancel() { + setImmediate(() => this.pending?.reject(new Error('Upload Cancelled'))); + } + } +})); + +jest.mock('~/lib/database', () => { + const createRow = (id: string): UploadRow => { + const row: UploadRow = { + id, + path: '', + error: false, + progress: 0, + update: async change => change(row), + destroyPermanently: async () => { + mockRows.delete(id); + } + }; + return row; + }; + const uploads = { + schema: {}, + find: async (id: string) => { + const row = mockRows.get(id); + if (!row) { + throw new Error(`Record uploads#${id} not found`); + } + return row; + }, + create: async (build: (row: UploadRow & { _raw?: { id: string } }) => void) => { + const draft: UploadRow & { _raw?: { id: string } } = createRow(''); + build(draft); + const row = Object.assign(createRow(draft._raw!.id), { path: draft.path }); + mockRows.set(row.id, row); + return row; + } + }; + return { + __esModule: true, + default: { active: { get: () => uploads, write: (work: () => Promise) => work() } } + }; +}); + +const rid = 'room-id'; +const server = 'https://server'; +const user = { id: 'user-id', token: 'token' }; +const file = () => ({ rid, path: 'file:///tmp/pic.jpg', name: 'pic.jpg', type: 'image/jpeg', size: 1 }) as any; +const uploadPath = getUploadPath('file:///tmp/pic.jpg', rid); + +const flush = () => new Promise(resolve => setImmediate(resolve)); + +const latestSend = () => mockSends[mockSends.length - 1]; + +beforeEach(() => { + mockRows.clear(); + mockSends.length = 0; + Object.keys(uploadQueue).forEach(key => delete uploadQueue[key]); + (Alert.alert as jest.Mock).mockClear(); + jest.spyOn(console, 'error').mockImplementation(() => {}); + jest.spyOn(console, 'log').mockImplementation(() => {}); +}); + +describe.each([ + ['sendFileMessageV2', sendFileMessageV2, { file: { _id: 'file-id', url: '/file' } }], + ['sendFileMessage (servers below 6.10)', sendFileMessage, {}] +])('%s upload lifecycle', (_name, send, acceptedResponse) => { + it('sends the same file again after the server rejected it', async () => { + const first = send(rid, file(), undefined, server, user); + await flush(); + latestSend().reject({ status: 403 }); + await expect(first).rejects.toEqual({ status: 403 }); + expect(mockRows.get(uploadPath)?.error).toBe(true); + expect(isUploadActive('file:///tmp/pic.jpg', rid)).toBe(false); + + const second = send(rid, file(), undefined, server, user); + await flush(); + expect(Alert.alert).not.toHaveBeenCalled(); + expect(mockSends).toHaveLength(2); + latestSend().resolve(acceptedResponse); + await expect(second).resolves.toBeUndefined(); + expect(mockRows.has(uploadPath)).toBe(false); + }); + + it('sends the same file again after it was sent', async () => { + const first = send(rid, file(), undefined, server, user); + await flush(); + latestSend().resolve(acceptedResponse); + await first; + expect(isUploadActive('file:///tmp/pic.jpg', rid)).toBe(false); + + const second = send(rid, file(), undefined, server, user); + await flush(); + expect(Alert.alert).not.toHaveBeenCalled(); + expect(mockSends).toHaveLength(2); + latestSend().resolve(acceptedResponse); + await second; + }); + + it('refuses a second send while the first is uploading, without failing the running upload', async () => { + const first = send(rid, file(), undefined, server, user); + await flush(); + + await expect(send(rid, file(), undefined, server, user)).resolves.toBeUndefined(); + expect(Alert.alert).toHaveBeenCalledWith('FileUpload_Error', 'Upload_in_progress'); + expect(mockRows.get(uploadPath)?.error).toBe(false); + expect(mockSends).toHaveLength(1); + + latestSend().resolve(acceptedResponse); + await expect(first).resolves.toBeUndefined(); + }); + + it('settles a cancelled upload quietly and lets the file be sent again', async () => { + const first = send(rid, file(), undefined, server, user); + await flush(); + await cancelUpload(mockRows.get(uploadPath) as any, rid); + await expect(first).resolves.toBeUndefined(); + expect(mockRows.has(uploadPath)).toBe(false); + + const second = send(rid, file(), undefined, server, user); + await flush(); + expect(Alert.alert).not.toHaveBeenCalled(); + latestSend().resolve(acceptedResponse); + await second; + }); +}); diff --git a/app/lib/methods/sendFileMessage/sendFileMessage.ts b/app/lib/methods/sendFileMessage/sendFileMessage.ts index 4f98efd4d99..5187d7e90d7 100644 --- a/app/lib/methods/sendFileMessage/sendFileMessage.ts +++ b/app/lib/methods/sendFileMessage/sendFileMessage.ts @@ -4,7 +4,14 @@ import { type IUser } from '~/definitions/IUser'; import { type TSendFileMessageFileInfo, type TUploadModel } from '~/definitions/IUpload'; import database from '~/lib/database'; import FileUpload from '../helpers/fileUpload'; -import { copyFileToCacheDirectoryIfNeeded, createUploadRecord, persistUploadError, uploadQueue } from './utils'; +import { + copyFileToCacheDirectoryIfNeeded, + createUploadRecord, + endUpload, + isUploadCancelled, + persistUploadError, + uploadQueue +} from './utils'; import { type IFormData } from '../helpers/fileUpload/definitions'; export async function sendFileMessage( @@ -17,6 +24,7 @@ export async function sendFileMessage( ): Promise { let uploadPath: string | null = ''; let uploadRecord: TUploadModel | null; + let upload: FileUpload | undefined; try { const { id, token } = user; const uploadUrl = `${server}/api/v1/rooms.upload/${rid}`; @@ -67,7 +75,7 @@ export async function sendFileMessage( 'X-User-Id': id }; - uploadQueue[uploadPath] = new FileUpload(uploadUrl, headers, formData, async (loaded, total) => { + upload = new FileUpload(uploadUrl, headers, formData, async (loaded, total) => { try { await db.write(async () => { await uploadRecord?.update(u => { @@ -78,16 +86,21 @@ export async function sendFileMessage( console.error(e); } }); - await uploadQueue[uploadPath].send(); + uploadQueue[uploadPath] = upload; + await upload.send(); await db.write(async () => { await uploadRecord?.destroyPermanently(); }); } catch (e) { - if (uploadPath && !uploadQueue[uploadPath]) { + if (upload && isUploadCancelled(uploadPath, upload)) { console.log('Upload cancelled'); } else { await persistUploadError(fileInfo.path, rid); throw e; } + } finally { + if (upload) { + endUpload(uploadPath, upload); + } } } diff --git a/app/lib/methods/sendFileMessage/sendFileMessageV2.ts b/app/lib/methods/sendFileMessage/sendFileMessageV2.ts index 37ce9c26177..c6199ddc40f 100644 --- a/app/lib/methods/sendFileMessage/sendFileMessageV2.ts +++ b/app/lib/methods/sendFileMessage/sendFileMessageV2.ts @@ -4,7 +4,14 @@ import { type TSendFileMessageFileInfo, type TUploadModel } from '~/definitions/ import { type IUser } from '~/definitions/IUser'; import database from '~/lib/database'; import { Encryption } from '~/lib/encryption'; -import { copyFileToCacheDirectoryIfNeeded, createUploadRecord, persistUploadError, uploadQueue } from './utils'; +import { + copyFileToCacheDirectoryIfNeeded, + createUploadRecord, + endUpload, + isUploadCancelled, + persistUploadError, + uploadQueue +} from './utils'; import FileUpload from '../helpers/fileUpload'; import { type IFormData } from '../helpers/fileUpload/definitions'; import fetch from '../helpers/fetch'; @@ -19,7 +26,7 @@ export async function sendFileMessageV2( ): Promise { let uploadPath: string | null = ''; let uploadRecord: TUploadModel | null; - let uploadStarted = false; + let upload: FileUpload | undefined; try { const { id, token } = user; const headers = { @@ -32,7 +39,7 @@ export async function sendFileMessageV2( [uploadPath, uploadRecord] = await createUploadRecord({ rid, fileInfo, tmid, isForceTryAgain }); if (!uploadPath || !uploadRecord) { - throw new Error("Couldn't create upload record"); + return; } const { file, getContent, fileContent } = await Encryption.encryptFile(rid, fileInfo); file.path = await copyFileToCacheDirectoryIfNeeded(file.path, file.name); @@ -51,7 +58,7 @@ export async function sendFileMessageV2( }); } - uploadQueue[uploadPath] = new FileUpload(`${server}/api/v1/rooms.media/${rid}`, headers, formData, async (loaded, total) => { + upload = new FileUpload(`${server}/api/v1/rooms.media/${rid}`, headers, formData, async (loaded, total) => { try { await db.write(async () => { await uploadRecord?.update(u => { @@ -62,8 +69,8 @@ export async function sendFileMessageV2( console.error(e); } }); - uploadStarted = true; - const response = await uploadQueue[uploadPath].send(); + uploadQueue[uploadPath] = upload; + const response = await upload.send(); let content; if (getContent) { @@ -88,11 +95,15 @@ export async function sendFileMessageV2( }); } catch (e: any) { console.error(e); - if (uploadStarted && uploadPath && !uploadQueue[uploadPath]) { + if (upload && isUploadCancelled(uploadPath, upload)) { console.log('Upload cancelled'); } else { await persistUploadError(fileInfo.path, rid); throw e; } + } finally { + if (upload) { + endUpload(uploadPath, upload); + } } } diff --git a/app/lib/methods/sendFileMessage/utils.ts b/app/lib/methods/sendFileMessage/utils.ts index 7c779b92e66..cf53ee119c8 100644 --- a/app/lib/methods/sendFileMessage/utils.ts +++ b/app/lib/methods/sendFileMessage/utils.ts @@ -18,6 +18,15 @@ export function isUploadActive(path: string, rid: string): boolean { return !!uploadQueue[getUploadPath(path, rid)]; } +export const isUploadCancelled = (uploadPath: string | null, upload: IFileUpload): boolean => + !uploadPath || uploadQueue[uploadPath] !== upload; + +export const endUpload = (uploadPath: string | null, upload: IFileUpload): void => { + if (uploadPath && uploadQueue[uploadPath] === upload) { + delete uploadQueue[uploadPath]; + } +}; + export async function cancelUpload(item: TUploadModel, rid: string): Promise { const uploadPath = getUploadPath(item.path, rid); if (!isEmpty(uploadQueue[uploadPath])) { From 97e1d499b57038c832768ddf030f27f5455e48cd Mon Sep 17 00:00:00 2001 From: Diego Mello Date: Wed, 18 Nov 2026 18:01:09 -0300 Subject: [PATCH 3/6] chore: move the upload lifecycle model's sync commit to the fix --- .claude/skills/verify-upload-lifecycle/SKILL.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/.claude/skills/verify-upload-lifecycle/SKILL.md b/.claude/skills/verify-upload-lifecycle/SKILL.md index faae004c8d2..dea892a0cd0 100644 --- a/.claude/skills/verify-upload-lifecycle/SKILL.md +++ b/.claude/skills/verify-upload-lifecycle/SKILL.md @@ -65,8 +65,8 @@ Change the model action that mirrors the changed code, rerun, and replay any new | `app/lib/methods/sendFileMessage/sendFileMessage.ts`: `sendFileMessage` | same actions | | `app/views/RoomView/components/UploadProgress.tsx`: `uploadCheck`, `tryAgain`, `handleCancelUpload` | `appRestarts`, `userSendsFile(true)`, `userCancels` | -Sync commit: `776c0681c6b76c6ea3059ef6755265f32cada088`. The model describes the covered code as of this commit. Move it forward only after you have compared every covered function with its model action at the new commit. To see what changed since: +Sync commit: `9f973888ce1418d3063e5c6077dcde6fe7fbada2`. The model describes the covered code as of this commit. Move it forward only after you have compared every covered function with its model action at the new commit. To see what changed since: ```sh -git diff 776c0681c6b76c6ea3059ef6755265f32cada088 -- app/lib/methods/sendFileMessage app/views/RoomView/components/UploadProgress.tsx +git diff 9f973888ce1418d3063e5c6077dcde6fe7fbada2 -- app/lib/methods/sendFileMessage app/views/RoomView/components/UploadProgress.tsx ``` From 9d6685752e39dde7ebe26c4524ccf5716b189da9 Mon Sep 17 00:00:00 2001 From: Diego Mello Date: Thu, 19 Nov 2026 11:55:30 -0300 Subject: [PATCH 4/6] test: replace the upload lifecycle model check with a cancel race test - Remove the verify-upload-lifecycle skill and its tla-ts model - Ignore the whole .claude/ directory again - Cover a cancelled upload that settles after the same file is sent again: the new upload keeps running and is not marked failed --- .../skills/verify-upload-lifecycle/SKILL.md | 72 ----------------- .../skills/verify-upload-lifecycle/check.sh | 25 ------ .../model/upload-lifecycle.ts | 77 ------------------- .../model/upload-lifecycle.view.ts | 43 ----------- .gitignore | 5 +- .../__tests__/uploadLifecycle.test.ts | 28 +++++++ 6 files changed, 29 insertions(+), 221 deletions(-) delete mode 100644 .claude/skills/verify-upload-lifecycle/SKILL.md delete mode 100755 .claude/skills/verify-upload-lifecycle/check.sh delete mode 100644 .claude/skills/verify-upload-lifecycle/model/upload-lifecycle.ts delete mode 100644 .claude/skills/verify-upload-lifecycle/model/upload-lifecycle.view.ts diff --git a/.claude/skills/verify-upload-lifecycle/SKILL.md b/.claude/skills/verify-upload-lifecycle/SKILL.md deleted file mode 100644 index dea892a0cd0..00000000000 --- a/.claude/skills/verify-upload-lifecycle/SKILL.md +++ /dev/null @@ -1,72 +0,0 @@ ---- -name: verify-upload-lifecycle -description: Model-check the file upload lifecycle (uploadQueue, createUploadRecord, persistUploadError, cancelUpload and the sendFileMessage callers) with tla-ts. Use before merging any change under app/lib/methods/sendFileMessage/, to UploadProgress retry/cancel, or to how the composer or share view call sendAttachments. ---- - -# Verify the upload lifecycle - -Sending a file in a Room goes through `sendFileMessage` (`app/lib/methods/sendFileMessage/index.ts`), which picks `sendFileMessage.ts` (servers below 6.10.0) or `sendFileMessageV2.ts`. Both share the in-memory `uploadQueue` and the WatermelonDB `uploads` row in `utils.ts`, and both handle the queue the same way, so one model covers them. If the two callers ever diverge, add a variable that picks the caller and branch on it. The model lives in `model/upload-lifecycle.ts`, and TLC checks every order of its events. - -## The rules - -- `neverRefusedAfterUploadEnded`: once an upload of a file ends (sent, rejected by the server, cancelled), sending the same file again in the same Room is never refused as "Upload in progress". - Harm: the user can't send that photo to that Room again until they restart the app. -- `runningUploadNeverShownFailed`: an upload that is still running never shows as failed in the Room. - Harm: the progress row turns into a failed row with a retry button while the file is still uploading. - -## Does my change touch this? - -Yes, if it changes any line listed under Coverage, or who calls `sendFileMessage` / `sendAttachments`, or whether the caller passes `isForceTryAgain`. Then run the check and compare the model with the code. - -## Run it - -```sh -.claude/skills/verify-upload-lifecycle/check.sh -``` - -It runs `pnpm dlx tla-ts@0.0.10` on the model (about 1 s, a few dozen states) and exits 0 when every rule holds, 1 when a rule breaks (it names the rules), and 2 when the model does not compile. The compiled `UploadLifecycle.tla` and `.cfg` beside the model are regenerated on each run and are not committed. - -Read every result with `/statechart`, pointing it at `model/upload-lifecycle.ts`; it picks up `model/upload-lifecycle.view.ts` and turns each broken rule into its shortest path in plain words, or draws the chart when everything holds. - -## Real bug or modeling error? - -Replay the shortest path against the real code before believing either. Each model action is one code event: - -| Model action | Code | -| ---------------------- | ------------------------------------------------------------------------------------------------------------ | -| `userSendsFile(false)` | `sendAttachments` from `MessageComposer.tsx` or `ShareView`, or `RecordAudio.tsx`, into `createUploadRecord` | -| `userSendsFile(true)` | `UploadProgress.tsx` `tryAgain` (only offered on a failed row) | -| `preparingFails` | `Encryption.encryptFile` or `copyFileToCacheDirectoryIfNeeded` throws before the `FileUpload` is created | -| `uploadStarts` | `uploadQueue[uploadPath] = upload` then `upload.send()` | -| `serverAccepts` | `send()` (and `rooms.mediaConfirm` on V2) resolve; the row is destroyed; `finally` runs `endUpload` | -| `serverRejects` | `send()` or `rooms.mediaConfirm` reject; `catch` persists the error; `finally` runs `endUpload` | -| `userCancels` | `UploadProgress.tsx` `handleCancelUpload` → `cancelUpload` | -| `appRestarts` | process restart clears `uploadQueue`; `UploadProgress.uploadCheck` marks rows without a queue entry failed | - -Write the replay as a Jest test in `app/lib/methods/sendFileMessage/__tests__/` that drives the real `sendFileMessage`/`sendFileMessageV2` and `utils.ts` through the same steps (see `uploadLifecycle.test.ts` there). If the code does not do what the path says, the model is wrong: fix the model, not the rule. - -## When a change is intended - -Change the model action that mirrors the changed code, rerun, and replay any new path. Never weaken or delete a rule to get a pass; add a model variable when a rule needs one. - -## Scope and assumptions - -- One file in one Room; a second Room or a different file never shares a queue key (`${path}-${rid}`), so they are independent. -- One upload in flight at a time. A second send while the first is still being prepared and not refused would start a second upload of the same file; the model drops that step (`userSendsFile` returns) and does not check duplicate uploads. -- Cancel while the file is being prepared is left out (the row exists but `send()` has not started). -- Each `await` boundary that matters is one action; what happens inside `FileUpload` (progress events) is not modeled. - -## Coverage - -| Covered code | Model | -| ------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------- | -| `app/lib/methods/sendFileMessage/utils.ts`: `uploadQueue`, `isUploadActive`, `isUploadCancelled`, `endUpload`, `cancelUpload`, `persistUploadError`, `createUploadRecord` | `queued`, `record`, `isRefused`, `refuse`, `userCancels`, `persistUploadError` | -| `app/lib/methods/sendFileMessage/sendFileMessageV2.ts`: `sendFileMessageV2` | `userSendsFile`, `preparingFails`, `uploadStarts`, `serverAccepts`, `serverRejects` | -| `app/lib/methods/sendFileMessage/sendFileMessage.ts`: `sendFileMessage` | same actions | -| `app/views/RoomView/components/UploadProgress.tsx`: `uploadCheck`, `tryAgain`, `handleCancelUpload` | `appRestarts`, `userSendsFile(true)`, `userCancels` | - -Sync commit: `9f973888ce1418d3063e5c6077dcde6fe7fbada2`. The model describes the covered code as of this commit. Move it forward only after you have compared every covered function with its model action at the new commit. To see what changed since: - -```sh -git diff 9f973888ce1418d3063e5c6077dcde6fe7fbada2 -- app/lib/methods/sendFileMessage app/views/RoomView/components/UploadProgress.tsx -``` diff --git a/.claude/skills/verify-upload-lifecycle/check.sh b/.claude/skills/verify-upload-lifecycle/check.sh deleted file mode 100755 index f866cd4d819..00000000000 --- a/.claude/skills/verify-upload-lifecycle/check.sh +++ /dev/null @@ -1,25 +0,0 @@ -#!/usr/bin/env bash -set -euo pipefail - -model_dir="$(cd "$(dirname "$0")/model" && pwd)" -output="$(mktemp -t upload-lifecycle-tlc)" - -cd "$model_dir" -set +e -pnpm dlx tla-ts@0.0.10 upload-lifecycle.ts -continue -noGenerateSpecTE >"$output" 2>&1 -status=$? -set -e - -broken="$(grep -o 'Invariant [A-Za-z]* is violated' "$output" | sort -u || true)" -grep -E 'distinct states found' "$output" || true - -if [ -n "$broken" ]; then - echo "$broken" - echo "FAIL: full TLC output in $output" - exit 1 -fi -if [ "$status" -ne 0 ]; then - echo "ERROR: tla-ts exited $status without a rule violation (compile or model error); see $output" - exit 2 -fi -echo "PASS: every rule holds" diff --git a/.claude/skills/verify-upload-lifecycle/model/upload-lifecycle.ts b/.claude/skills/verify-upload-lifecycle/model/upload-lifecycle.ts deleted file mode 100644 index 49f79822aed..00000000000 --- a/.claude/skills/verify-upload-lifecycle/model/upload-lifecycle.ts +++ /dev/null @@ -1,77 +0,0 @@ -type UploadRecord = 'none' | 'uploading' | 'failed'; -type Attempt = 'none' | 'preparing' | 'sending'; - -let queued = false; -let record: UploadRecord = 'none'; -let attempt: Attempt = 'none'; -let refusedWithNothingInFlight = false; - -const persistUploadError = () => { - if (record !== 'none') { - record = 'failed'; - } -}; - -const isRefused = (force: boolean) => record !== 'none' && queued && !force; - -const refuse = () => { - if (attempt === 'none') { - refusedWithNothingInFlight = true; - } -}; - -export const userSendsFile = (force: boolean) => { - if (force && (record !== 'failed' || attempt !== 'none')) return; - if (isRefused(force)) { - refuse(); - return; - } - if (attempt !== 'none') return; - record = 'uploading'; - attempt = 'preparing'; -}; - -export const preparingFails = () => { - if (attempt !== 'preparing') return; - attempt = 'none'; - persistUploadError(); -}; - -export const uploadStarts = () => { - if (attempt !== 'preparing') return; - queued = true; - attempt = 'sending'; -}; - -export const serverAccepts = () => { - if (attempt !== 'sending') return; - attempt = 'none'; - queued = false; - record = 'none'; -}; - -export const serverRejects = () => { - if (attempt !== 'sending') return; - attempt = 'none'; - queued = false; - persistUploadError(); -}; - -export const userCancels = () => { - if (record === 'none' || attempt === 'preparing') return; - queued = false; - record = 'none'; - attempt = 'none'; -}; - -export const appRestarts = () => { - queued = false; - attempt = 'none'; - persistUploadError(); -}; - -/** Once an upload of a file ends (sent, rejected, cancelled), sending that file again in the same Room is never refused as "Upload in progress". */ -export const neverRefusedAfterUploadEnded = () => !refusedWithNothingInFlight; - -/** An upload that is still running never shows as failed in the Room. */ -export const runningUploadNeverShownFailed = () => attempt === 'none' || record !== 'failed'; diff --git a/.claude/skills/verify-upload-lifecycle/model/upload-lifecycle.view.ts b/.claude/skills/verify-upload-lifecycle/model/upload-lifecycle.view.ts deleted file mode 100644 index 2609e1a4df0..00000000000 --- a/.claude/skills/verify-upload-lifecycle/model/upload-lifecycle.view.ts +++ /dev/null @@ -1,43 +0,0 @@ -type Vars = { - api: string; - queued: boolean; - record: string; - attempt: string; - refusedWithNothingInFlight: boolean; -}; - -export const title = 'Sending a file in a Room'; - -const rowLabel = (record: string) => - record === 'none' ? 'no upload row' : record === 'failed' ? 'failed upload row' : 'upload row in progress'; - -export const state = (v: Vars) => { - if (v.refusedWithNothingInFlight) { - return 'Refused: Upload in progress'; - } - if (v.attempt !== 'none') { - const phase = v.attempt === 'preparing' ? 'Preparing the file' : 'Uploading'; - return v.record === 'failed' ? `${phase}, shown as failed` : phase; - } - return `Idle, ${rowLabel(v.record)}${v.queued ? ', stale queue entry' : ''}`; -}; - -const labels: Record = { - userSendsFile: 'you send the file', - preparingFails: 'preparing the file fails', - uploadStarts: 'the upload starts', - serverAccepts: 'the server accepts it', - serverRejects: 'the server rejects it', - userCancels: 'you cancel the upload', - appRestarts: 'the app restarts' -}; - -export const step = (action: string, from: Vars, to: Vars) => { - if (action === 'userSendsFile' && from.attempt !== 'none') { - return 'you tap Send again [while it uploads]'; - } - if (action === 'userSendsFile' && from.record === 'failed' && !to.refusedWithNothingInFlight && to.attempt === 'preparing') { - return 'you send the file or tap retry'; - } - return labels[action] ?? action; -}; diff --git a/.gitignore b/.gitignore index 9f4f0a4494e..445b2f6dd34 100644 --- a/.gitignore +++ b/.gitignore @@ -86,10 +86,7 @@ e2e/e2e_account.ts *.p8 .worktrees/ .omc/ -.claude/* -!.claude/skills/ -.claude/skills/**/*.tla -.claude/skills/**/*.cfg +.claude/ .agents/ .cursor/ skills-lock.json diff --git a/app/lib/methods/sendFileMessage/__tests__/uploadLifecycle.test.ts b/app/lib/methods/sendFileMessage/__tests__/uploadLifecycle.test.ts index e43d6da6b07..9af3ed4ac8a 100644 --- a/app/lib/methods/sendFileMessage/__tests__/uploadLifecycle.test.ts +++ b/app/lib/methods/sendFileMessage/__tests__/uploadLifecycle.test.ts @@ -17,6 +17,8 @@ type PendingSend = { resolve: (response: unknown) => void; reject: (error: unkno const mockRows = new Map(); const mockSends: PendingSend[] = []; +const mockCancelledSends: PendingSend[] = []; +let mockHoldCancelledSends = false; jest.mock('react-native', () => ({ Alert: { alert: jest.fn() } })); jest.mock('~/i18n', () => ({ __esModule: true, default: { t: (key: string) => key } })); @@ -47,6 +49,10 @@ jest.mock('../../helpers/fileUpload', () => ({ } cancel() { + if (mockHoldCancelledSends && this.pending) { + mockCancelledSends.push(this.pending); + return; + } setImmediate(() => this.pending?.reject(new Error('Upload Cancelled'))); } } @@ -102,6 +108,8 @@ const latestSend = () => mockSends[mockSends.length - 1]; beforeEach(() => { mockRows.clear(); mockSends.length = 0; + mockCancelledSends.length = 0; + mockHoldCancelledSends = false; Object.keys(uploadQueue).forEach(key => delete uploadQueue[key]); (Alert.alert as jest.Mock).mockClear(); jest.spyOn(console, 'error').mockImplementation(() => {}); @@ -170,4 +178,24 @@ describe.each([ latestSend().resolve(acceptedResponse); await second; }); + + it('keeps the new upload running when a cancelled upload settles after the file was sent again', async () => { + mockHoldCancelledSends = true; + const first = send(rid, file(), undefined, server, user); + await flush(); + await cancelUpload(mockRows.get(uploadPath) as any, rid); + + const second = send(rid, file(), undefined, server, user); + await flush(); + expect(mockSends).toHaveLength(2); + + mockCancelledSends[0].reject(new Error('Upload Cancelled')); + await expect(first).resolves.toBeUndefined(); + expect(mockRows.get(uploadPath)?.error).toBe(false); + expect(isUploadActive('file:///tmp/pic.jpg', rid)).toBe(true); + + latestSend().resolve(acceptedResponse); + await expect(second).resolves.toBeUndefined(); + expect(isUploadActive('file:///tmp/pic.jpg', rid)).toBe(false); + }); }); From 9a45d0dd36c6a59559b68eefa0d7e860d52aab37 Mon Sep 17 00:00:00 2001 From: Diego Mello Date: Thu, 19 Nov 2026 13:34:31 -0300 Subject: [PATCH 5/6] fix: mark a rejected upload failed when its file was copied to the cache Both senders overwrote the file path with the cache copy's path, so persistUploadError looked up a row that doesn't exist and the progress row kept showing "Uploading" for files whose path isn't file://, such as Android content:// files. Keep the cache path in a local instead. The upload lifecycle test mock now always holds a cancelled send, so every cancel test settles it explicitly. --- .../__tests__/uploadLifecycle.test.ts | 21 ++++++++++++------- .../sendFileMessage/sendFileMessage.ts | 4 ++-- .../sendFileMessage/sendFileMessageV2.ts | 4 ++-- 3 files changed, 17 insertions(+), 12 deletions(-) diff --git a/app/lib/methods/sendFileMessage/__tests__/uploadLifecycle.test.ts b/app/lib/methods/sendFileMessage/__tests__/uploadLifecycle.test.ts index 9af3ed4ac8a..a23b0cb2430 100644 --- a/app/lib/methods/sendFileMessage/__tests__/uploadLifecycle.test.ts +++ b/app/lib/methods/sendFileMessage/__tests__/uploadLifecycle.test.ts @@ -18,7 +18,6 @@ type PendingSend = { resolve: (response: unknown) => void; reject: (error: unkno const mockRows = new Map(); const mockSends: PendingSend[] = []; const mockCancelledSends: PendingSend[] = []; -let mockHoldCancelledSends = false; jest.mock('react-native', () => ({ Alert: { alert: jest.fn() } })); jest.mock('~/i18n', () => ({ __esModule: true, default: { t: (key: string) => key } })); @@ -49,11 +48,9 @@ jest.mock('../../helpers/fileUpload', () => ({ } cancel() { - if (mockHoldCancelledSends && this.pending) { + if (this.pending) { mockCancelledSends.push(this.pending); - return; } - setImmediate(() => this.pending?.reject(new Error('Upload Cancelled'))); } } })); @@ -109,7 +106,6 @@ beforeEach(() => { mockRows.clear(); mockSends.length = 0; mockCancelledSends.length = 0; - mockHoldCancelledSends = false; Object.keys(uploadQueue).forEach(key => delete uploadQueue[key]); (Alert.alert as jest.Mock).mockClear(); jest.spyOn(console, 'error').mockImplementation(() => {}); @@ -141,7 +137,7 @@ describe.each([ const first = send(rid, file(), undefined, server, user); await flush(); latestSend().resolve(acceptedResponse); - await first; + await expect(first).resolves.toBeUndefined(); expect(isUploadActive('file:///tmp/pic.jpg', rid)).toBe(false); const second = send(rid, file(), undefined, server, user); @@ -169,6 +165,7 @@ describe.each([ const first = send(rid, file(), undefined, server, user); await flush(); await cancelUpload(mockRows.get(uploadPath) as any, rid); + mockCancelledSends[0].reject(new Error('Upload Cancelled')); await expect(first).resolves.toBeUndefined(); expect(mockRows.has(uploadPath)).toBe(false); @@ -176,11 +173,10 @@ describe.each([ await flush(); expect(Alert.alert).not.toHaveBeenCalled(); latestSend().resolve(acceptedResponse); - await second; + await expect(second).resolves.toBeUndefined(); }); it('keeps the new upload running when a cancelled upload settles after the file was sent again', async () => { - mockHoldCancelledSends = true; const first = send(rid, file(), undefined, server, user); await flush(); await cancelUpload(mockRows.get(uploadPath) as any, rid); @@ -198,4 +194,13 @@ describe.each([ await expect(second).resolves.toBeUndefined(); expect(isUploadActive('file:///tmp/pic.jpg', rid)).toBe(false); }); + + it('marks the row failed when the server rejects a file that was copied to the cache first', async () => { + const sharedPath = 'content://media/pic.jpg'; + const sent = send(rid, { ...file(), path: sharedPath }, undefined, server, user); + await flush(); + latestSend().reject({ status: 403 }); + await expect(sent).rejects.toEqual({ status: 403 }); + expect(mockRows.get(getUploadPath(sharedPath, rid))?.error).toBe(true); + }); }); diff --git a/app/lib/methods/sendFileMessage/sendFileMessage.ts b/app/lib/methods/sendFileMessage/sendFileMessage.ts index 5187d7e90d7..a3074751488 100644 --- a/app/lib/methods/sendFileMessage/sendFileMessage.ts +++ b/app/lib/methods/sendFileMessage/sendFileMessage.ts @@ -37,14 +37,14 @@ export async function sendFileMessage( return; } - fileInfo.path = await copyFileToCacheDirectoryIfNeeded(fileInfo.path, fileInfo.name); + const fileUri = await copyFileToCacheDirectoryIfNeeded(fileInfo.path, fileInfo.name); const formData: IFormData[] = []; formData.push({ name: 'file', type: fileInfo.type, filename: fileInfo.name || 'fileMessage', - uri: fileInfo.path + uri: fileUri }); if (fileInfo.description) { diff --git a/app/lib/methods/sendFileMessage/sendFileMessageV2.ts b/app/lib/methods/sendFileMessage/sendFileMessageV2.ts index c6199ddc40f..5ce5f0c9233 100644 --- a/app/lib/methods/sendFileMessage/sendFileMessageV2.ts +++ b/app/lib/methods/sendFileMessage/sendFileMessageV2.ts @@ -42,14 +42,14 @@ export async function sendFileMessageV2( return; } const { file, getContent, fileContent } = await Encryption.encryptFile(rid, fileInfo); - file.path = await copyFileToCacheDirectoryIfNeeded(file.path, file.name); + const fileUri = await copyFileToCacheDirectoryIfNeeded(file.path, file.name); const formData: IFormData[] = []; formData.push({ name: 'file', type: file.type, filename: file.name, - uri: file.path + uri: fileUri }); if (fileContent) { formData.push({ From 64a5186b9872d527ba0d560ff6508765789adffa Mon Sep 17 00:00:00 2001 From: Diego Mello Date: Mon, 23 Nov 2026 11:58:14 -0300 Subject: [PATCH 6/6] test: cover an upload that fails while its file is copied to the cache --- .../__tests__/uploadLifecycle.test.ts | 18 ++++++++++++++++++ 1 file changed, 18 insertions(+) diff --git a/app/lib/methods/sendFileMessage/__tests__/uploadLifecycle.test.ts b/app/lib/methods/sendFileMessage/__tests__/uploadLifecycle.test.ts index a23b0cb2430..962b0519aa2 100644 --- a/app/lib/methods/sendFileMessage/__tests__/uploadLifecycle.test.ts +++ b/app/lib/methods/sendFileMessage/__tests__/uploadLifecycle.test.ts @@ -1,4 +1,5 @@ import { Alert } from 'react-native'; +import { copyAsync } from 'expo-file-system/legacy'; import { sendFileMessage } from '../sendFileMessage'; import { sendFileMessageV2 } from '../sendFileMessageV2'; @@ -203,4 +204,21 @@ describe.each([ await expect(sent).rejects.toEqual({ status: 403 }); expect(mockRows.get(getUploadPath(sharedPath, rid))?.error).toBe(true); }); + + it('marks the row failed when copying the file to the cache fails, and lets the file be sent again', async () => { + const sharedPath = 'content://media/pic.jpg'; + const copyError = new Error('copy failed'); + (copyAsync as jest.Mock).mockRejectedValueOnce(copyError); + await expect(send(rid, { ...file(), path: sharedPath }, undefined, server, user)).rejects.toBe(copyError); + expect(mockRows.get(getUploadPath(sharedPath, rid))?.error).toBe(true); + expect(isUploadActive(sharedPath, rid)).toBe(false); + + const second = send(rid, { ...file(), path: sharedPath }, undefined, server, user); + await flush(); + expect(Alert.alert).not.toHaveBeenCalled(); + expect(mockSends).toHaveLength(1); + latestSend().resolve(acceptedResponse); + await expect(second).resolves.toBeUndefined(); + expect(mockRows.has(getUploadPath(sharedPath, rid))).toBe(false); + }); });